@loaders.gl/core 5.0.0 → 5.0.2

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 (219) hide show
  1. package/dist/api.cjs +4129 -0
  2. package/dist/api.cjs.map +6 -0
  3. package/dist/api.d.ts +34 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +50 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/arrow-geometry/index.cjs +5 -2
  8. package/dist/arrow-geometry/index.cjs.map +2 -2
  9. package/dist/arrow-geometry/index.d.ts +1 -0
  10. package/dist/arrow-geometry/index.d.ts.map +1 -1
  11. package/dist/arrow-geometry/index.js +1 -0
  12. package/dist/arrow-geometry/index.js.map +1 -1
  13. package/dist/arrow-geometry/triangulate-wkb-geometry-column.cjs +100 -0
  14. package/dist/arrow-geometry/triangulate-wkb-geometry-column.cjs.map +7 -0
  15. package/dist/arrow-geometry/triangulate-wkb-geometry-column.d.ts +15 -0
  16. package/dist/arrow-geometry/triangulate-wkb-geometry-column.d.ts.map +1 -0
  17. package/dist/arrow-geometry/triangulate-wkb-geometry-column.js +87 -0
  18. package/dist/arrow-geometry/triangulate-wkb-geometry-column.js.map +1 -0
  19. package/dist/dist.dev.js +458 -539
  20. package/dist/dist.min.js +3 -3
  21. package/dist/geoarrow/geoarrow-converter/geoarrow-converter.d.ts +1 -1
  22. package/dist/geoarrow/geoarrow-converter/geoarrow-converter.d.ts.map +1 -1
  23. package/dist/geoarrow/index.cjs +1 -1
  24. package/dist/geoarrow/index.cjs.map +1 -1
  25. package/dist/geoarrow/index.d.ts +2 -2
  26. package/dist/geoarrow/index.d.ts.map +1 -1
  27. package/dist/geoarrow/index.js +1 -1
  28. package/dist/geoarrow/index.js.map +1 -1
  29. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs +1 -1
  30. package/dist/geoarrow/lib/kernels/decode-wkt-native.cjs.map +1 -1
  31. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts +1 -1
  32. package/dist/geoarrow/lib/kernels/decode-wkt-native.d.ts.map +1 -1
  33. package/dist/geoarrow/lib/kernels/decode-wkt-native.js +1 -1
  34. package/dist/geoarrow/lib/kernels/decode-wkt-native.js.map +1 -1
  35. package/dist/index.cjs +67 -4114
  36. package/dist/index.cjs.map +3 -3
  37. package/dist/index.d.ts +1 -33
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +2 -46
  40. package/dist/index.js.map +1 -1
  41. package/dist/lib/api/encode-table.d.ts +4 -4
  42. package/dist/lib/api/encode-table.d.ts.map +1 -1
  43. package/dist/lib/api/encode-table.js +21 -3
  44. package/dist/lib/api/encode-table.js.map +1 -1
  45. package/dist/lib/api/encode.d.ts +6 -6
  46. package/dist/lib/api/encode.d.ts.map +1 -1
  47. package/dist/lib/api/encode.js +46 -7
  48. package/dist/lib/api/encode.js.map +1 -1
  49. package/dist/lib/init.js +1 -1
  50. package/dist/loader-utils/index.cjs +94 -24
  51. package/dist/loader-utils/index.cjs.map +3 -3
  52. package/dist/loader-utils/index.d.ts +3 -2
  53. package/dist/loader-utils/index.d.ts.map +1 -1
  54. package/dist/loader-utils/index.js +2 -1
  55. package/dist/loader-utils/index.js.map +1 -1
  56. package/dist/loader-utils/json-loader-metadata.cjs +85 -0
  57. package/dist/loader-utils/json-loader-metadata.cjs.map +6 -0
  58. package/dist/loader-utils/json-loader-metadata.d.ts +51 -0
  59. package/dist/loader-utils/json-loader-metadata.d.ts.map +1 -0
  60. package/dist/loader-utils/json-loader-metadata.js +31 -0
  61. package/dist/loader-utils/json-loader-metadata.js.map +1 -0
  62. package/dist/loader-utils/json-loader.cjs +80 -0
  63. package/dist/loader-utils/json-loader.cjs.map +6 -0
  64. package/dist/loader-utils/json-loader.d.ts +4 -4
  65. package/dist/loader-utils/json-loader.d.ts.map +1 -1
  66. package/dist/loader-utils/json-loader.js +3 -17
  67. package/dist/loader-utils/json-loader.js.map +1 -1
  68. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  69. package/dist/loader-utils/lib/request-utils/authentication.d.ts +2 -0
  70. package/dist/loader-utils/lib/request-utils/authentication.d.ts.map +1 -1
  71. package/dist/loader-utils/lib/request-utils/authentication.js +12 -0
  72. package/dist/loader-utils/lib/request-utils/authentication.js.map +1 -1
  73. package/dist/loader-utils/lib/scan-utils/table-query.d.ts +1 -1
  74. package/dist/loader-utils/lib/scan-utils/table-query.d.ts.map +1 -1
  75. package/dist/loader-utils/lib/sources/data-source.d.ts +1 -1
  76. package/dist/loader-utils/lib/sources/data-source.d.ts.map +1 -1
  77. package/dist/loader-utils/lib/sources/raster-source.d.ts +21 -1
  78. package/dist/loader-utils/lib/sources/raster-source.d.ts.map +1 -1
  79. package/dist/loader-utils/lib/sources/raster-source.js.map +1 -1
  80. package/dist/loader-utils/lib/sources/raster-tile.d.ts +7 -0
  81. package/dist/loader-utils/lib/sources/raster-tile.d.ts.map +1 -0
  82. package/dist/loader-utils/lib/sources/raster-tile.js +34 -0
  83. package/dist/loader-utils/lib/sources/raster-tile.js.map +1 -0
  84. package/dist/loader-utils/lib/sources/utils/utils.d.ts +1 -1
  85. package/dist/loader-utils/lib/sources/utils/utils.d.ts.map +1 -1
  86. package/dist/loader-utils/tile-grid.d.ts +2 -1
  87. package/dist/loader-utils/tile-grid.d.ts.map +1 -1
  88. package/dist/loader-utils/tile-grid.js +1 -1
  89. package/dist/loader-utils/tile-grid.js.map +1 -1
  90. package/dist/loader-utils/writer-types.d.ts +2 -0
  91. package/dist/loader-utils/writer-types.d.ts.map +1 -1
  92. package/dist/null-loader-metadata.cjs +89 -0
  93. package/dist/null-loader-metadata.cjs.map +6 -0
  94. package/dist/null-loader-metadata.d.ts +48 -0
  95. package/dist/null-loader-metadata.d.ts.map +1 -0
  96. package/dist/null-loader-metadata.js +30 -0
  97. package/dist/null-loader-metadata.js.map +1 -0
  98. package/dist/null-loader.cjs +84 -0
  99. package/dist/null-loader.cjs.map +6 -0
  100. package/dist/null-loader.d.ts +6 -6
  101. package/dist/null-loader.d.ts.map +1 -1
  102. package/dist/null-loader.js +2 -15
  103. package/dist/null-loader.js.map +1 -1
  104. package/dist/null-worker-node.js +58 -28
  105. package/dist/null-worker.js +58 -28
  106. package/dist/scan/arrow-execution/expressions.d.ts +1 -1
  107. package/dist/scan/arrow-execution/expressions.d.ts.map +1 -1
  108. package/dist/scan/arrow-query.cjs +2 -0
  109. package/dist/scan/arrow-query.cjs.map +2 -2
  110. package/dist/scan/arrow-query.d.ts +1 -1
  111. package/dist/scan/arrow-query.d.ts.map +1 -1
  112. package/dist/scan/arrow-query.js +1 -1
  113. package/dist/scan/arrow-query.js.map +1 -1
  114. package/dist/scan/index.cjs +16 -22
  115. package/dist/scan/index.cjs.map +2 -2
  116. package/dist/scan/index.d.ts +7 -7
  117. package/dist/scan/index.d.ts.map +1 -1
  118. package/dist/scan/index.js +4 -6
  119. package/dist/scan/index.js.map +1 -1
  120. package/dist/scan/plan-arrow-table-query.d.ts +1 -1
  121. package/dist/scan/plan-arrow-table-query.d.ts.map +1 -1
  122. package/dist/scan/query-arrow-table-in-batches.cjs +7 -19
  123. package/dist/scan/query-arrow-table-in-batches.cjs.map +2 -2
  124. package/dist/scan/query-arrow-table-in-batches.d.ts.map +1 -1
  125. package/dist/scan/query-arrow-table-in-batches.js +7 -22
  126. package/dist/scan/query-arrow-table-in-batches.js.map +1 -1
  127. package/dist/scan/query-executor.cjs +202 -0
  128. package/dist/scan/query-executor.cjs.map +7 -0
  129. package/dist/scan/query-executor.d.ts +27 -0
  130. package/dist/scan/query-executor.d.ts.map +1 -0
  131. package/dist/scan/query-executor.js +203 -0
  132. package/dist/scan/query-executor.js.map +1 -0
  133. package/dist/scan/query.cjs +92 -205
  134. package/dist/scan/query.cjs.map +3 -3
  135. package/dist/scan/query.d.ts +5 -4
  136. package/dist/scan/query.d.ts.map +1 -1
  137. package/dist/scan/query.js +94 -238
  138. package/dist/scan/query.js.map +1 -1
  139. package/dist/schema-utils/index.cjs +182 -0
  140. package/dist/schema-utils/index.cjs.map +3 -3
  141. package/dist/schema-utils/index.d.ts +3 -0
  142. package/dist/schema-utils/index.d.ts.map +1 -1
  143. package/dist/schema-utils/index.js +3 -0
  144. package/dist/schema-utils/index.js.map +1 -1
  145. package/dist/schema-utils/lib/arrow/arrow-converter.d.ts +24 -0
  146. package/dist/schema-utils/lib/arrow/arrow-converter.d.ts.map +1 -0
  147. package/dist/schema-utils/lib/arrow/arrow-converter.js +43 -0
  148. package/dist/schema-utils/lib/arrow/arrow-converter.js.map +1 -0
  149. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.d.ts +29 -0
  150. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.d.ts.map +1 -0
  151. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.js +89 -0
  152. package/dist/schema-utils/lib/arrow/convert-arrow-variable-width.js.map +1 -0
  153. package/dist/schema-utils/lib/arrow/convert-arrow.d.ts +17 -0
  154. package/dist/schema-utils/lib/arrow/convert-arrow.d.ts.map +1 -0
  155. package/dist/schema-utils/lib/arrow/convert-arrow.js +24 -0
  156. package/dist/schema-utils/lib/arrow/convert-arrow.js.map +1 -0
  157. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.d.ts +4 -0
  158. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.d.ts.map +1 -0
  159. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.js +51 -0
  160. package/dist/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.js.map +1 -0
  161. package/dist/worker-utils/index.cjs +2 -2
  162. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  163. package/package.json +49 -23
  164. package/src/api.ts +99 -0
  165. package/src/arrow-geometry/index.ts +5 -0
  166. package/src/arrow-geometry/triangulate-wkb-geometry-column.ts +122 -0
  167. package/src/geoarrow/index.ts +2 -2
  168. package/src/geoarrow/lib/kernels/decode-wkt-native.ts +1 -1
  169. package/src/index.ts +2 -94
  170. package/src/lib/api/encode-table.ts +31 -6
  171. package/src/lib/api/encode.ts +61 -11
  172. package/src/loader-utils/index.ts +3 -0
  173. package/src/loader-utils/json-loader-metadata.ts +35 -0
  174. package/src/loader-utils/json-loader.ts +3 -18
  175. package/src/loader-utils/lib/request-utils/authentication.ts +17 -0
  176. package/src/loader-utils/lib/sources/raster-source.ts +22 -1
  177. package/src/loader-utils/lib/sources/raster-tile.ts +46 -0
  178. package/src/loader-utils/tile-grid.ts +16 -1
  179. package/src/loader-utils/writer-types.ts +2 -0
  180. package/src/null-loader-metadata.ts +32 -0
  181. package/src/null-loader.ts +2 -17
  182. package/src/scan/arrow-query.ts +1 -1
  183. package/src/scan/index.ts +24 -13
  184. package/src/scan/query-arrow-table-in-batches.ts +7 -24
  185. package/src/scan/query-executor.ts +286 -0
  186. package/src/scan/query.ts +112 -299
  187. package/src/schema-utils/index.ts +14 -0
  188. package/src/schema-utils/lib/arrow/arrow-converter.ts +74 -0
  189. package/src/schema-utils/lib/arrow/convert-arrow-variable-width.ts +121 -0
  190. package/src/schema-utils/lib/arrow/convert-arrow.ts +52 -0
  191. package/src/schema-utils/lib/arrow/tighten-arrow-table-schema-nullability.ts +83 -0
  192. package/dist/cluster-source.cjs +0 -6360
  193. package/dist/cluster-source.cjs.map +0 -6
  194. package/dist/cluster-source.d.ts +0 -2
  195. package/dist/cluster-source.d.ts.map +0 -1
  196. package/dist/cluster-source.js +0 -2
  197. package/dist/cluster-source.js.map +0 -1
  198. package/dist/federated-table-scan-source.cjs +0 -1905
  199. package/dist/federated-table-scan-source.cjs.map +0 -6
  200. package/dist/federated-table-scan-source.d.ts +0 -2
  201. package/dist/federated-table-scan-source.d.ts.map +0 -1
  202. package/dist/federated-table-scan-source.js +0 -2
  203. package/dist/federated-table-scan-source.js.map +0 -1
  204. package/dist/geoarrow/geoarrow-builder.cjs +0 -31
  205. package/dist/geoarrow/geoarrow-builder.cjs.map +0 -7
  206. package/dist/geoarrow/geoarrow-builder.d.ts +0 -3
  207. package/dist/geoarrow/geoarrow-builder.d.ts.map +0 -1
  208. package/dist/geoarrow/geoarrow-builder.js +0 -5
  209. package/dist/geoarrow/geoarrow-builder.js.map +0 -1
  210. package/dist/vector-table-scan-source.cjs +0 -1200
  211. package/dist/vector-table-scan-source.cjs.map +0 -6
  212. package/dist/vector-table-scan-source.d.ts +0 -2
  213. package/dist/vector-table-scan-source.d.ts.map +0 -1
  214. package/dist/vector-table-scan-source.js +0 -2
  215. package/dist/vector-table-scan-source.js.map +0 -1
  216. package/src/cluster-source.ts +0 -1
  217. package/src/federated-table-scan-source.ts +0 -1
  218. package/src/geoarrow/geoarrow-builder.ts +0 -21
  219. package/src/vector-table-scan-source.ts +0 -1
@@ -1,1905 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // dist/federated-table-scan-source.js
31
- var federated_table_scan_source_exports = {};
32
- __export(federated_table_scan_source_exports, {
33
- FEDERATED_TABLE_QUERY_CAPABILITIES: () => FEDERATED_TABLE_QUERY_CAPABILITIES,
34
- FederatedTableScanSource: () => FederatedTableScanSource,
35
- getFederatedTableBatchProvenance: () => getFederatedTableBatchProvenance
36
- });
37
- module.exports = __toCommonJS(federated_table_scan_source_exports);
38
-
39
- // dist/scan/federated-table-scan-source.js
40
- var arrow5 = __toESM(require("apache-arrow"), 1);
41
-
42
- // src/loader-utils/lib/scan-utils/columnar-predicate.ts
43
- var import_columnar_predicate = require("@math.gl/sql/columnar-predicate");
44
- var import_columnar_predicate2 = require("@math.gl/sql/columnar-predicate");
45
-
46
- // src/loader-utils/lib/scan-utils/scan-query-metadata.ts
47
- var import_crs = require("@math.gl/geospatial/crs");
48
- function emitQueryComplete(callback, summary) {
49
- if (!callback) return;
50
- try {
51
- callback(summary);
52
- } catch {
53
- }
54
- }
55
- function createScanQueryMetadata(options) {
56
- validateScanExecutionSupport(options.queryType, options.execution);
57
- const schema = Object.freeze({
58
- fields: Object.freeze(
59
- options.schema.fields.map(
60
- (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
61
- )
62
- ),
63
- metadata: Object.freeze({ ...options.schema.metadata })
64
- });
65
- const columns = schema.fields.map(
66
- (field) => {
67
- var _a;
68
- return Object.freeze({
69
- name: field.name,
70
- type: field.type,
71
- nullable: field.nullable !== false,
72
- role: ((_a = options.columnRoles) == null ? void 0 : _a[field.name]) || "attribute",
73
- title: getNonEmptyMetadataValue(field.metadata, "title"),
74
- description: getNonEmptyMetadataValue(field.metadata, "description"),
75
- metadata: field.metadata || Object.freeze({})
76
- });
77
- }
78
- );
79
- const queryCapabilities = Object.freeze({ ...options.capabilities });
80
- return Object.freeze({
81
- sourceType: options.sourceType,
82
- queryType: options.queryType,
83
- execution: Object.freeze({ ...options.execution }),
84
- name: options.name,
85
- description: options.description,
86
- schema,
87
- columns: Object.freeze(columns),
88
- capabilities: queryCapabilities,
89
- queryCapabilities,
90
- ...options.hasDefaultRowWindow ? { hasDefaultRowWindow: true } : {},
91
- spatial: options.spatial ? Object.freeze({
92
- ...options.spatial,
93
- bounds: options.spatial.bounds ? Object.freeze({
94
- minimum: Object.freeze([...options.spatial.bounds.minimum]),
95
- maximum: Object.freeze([...options.spatial.bounds.maximum])
96
- }) : void 0,
97
- coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
98
- spatialReference: options.spatial.spatialReference ? (0, import_crs.createSpatialReference)(options.spatial.spatialReference) : void 0
99
- }) : void 0,
100
- statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
101
- levels: options.levels ? Object.freeze(
102
- options.levels.map(
103
- (level) => Object.freeze({
104
- ...level,
105
- scale: level.scale ? Object.freeze([...level.scale]) : void 0
106
- })
107
- )
108
- ) : void 0
109
- });
110
- }
111
- function validateScanExecutionSupport(queryType, execution) {
112
- if (execution.status === "metadata-only") {
113
- if (!execution.reason.trim()) {
114
- throw new Error("Metadata-only scan support requires a concrete reason");
115
- }
116
- return;
117
- }
118
- const validMethods = {
119
- table: ["read", "query"],
120
- raster: ["getRaster"],
121
- "point-cloud": ["scan"]
122
- };
123
- if (!validMethods[queryType].includes(execution.method)) {
124
- throw new Error(
125
- `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
126
- );
127
- }
128
- }
129
- function getNonEmptyMetadataValue(metadata, key) {
130
- const value = metadata == null ? void 0 : metadata[key];
131
- return value || void 0;
132
- }
133
-
134
- // src/loader-utils/lib/scan-utils/table-query.ts
135
- function planTableQuery(sourceColumnNames, options = {}) {
136
- validateTableQueryOptions(sourceColumnNames, options);
137
- const outputColumnNames = options.columns ? [...options.columns] : [...sourceColumnNames];
138
- const predicateColumnNames = options.predicate ? (0, import_columnar_predicate2.getColumnarPredicateColumns)(options.predicate) : [];
139
- const requiredColumnNames = /* @__PURE__ */ new Set([...outputColumnNames, ...predicateColumnNames]);
140
- const scanColumnNames = sourceColumnNames.filter(
141
- (columnName) => requiredColumnNames.has(columnName)
142
- );
143
- const steps = [
144
- Object.freeze({ kind: "scan", columns: Object.freeze(scanColumnNames) })
145
- ];
146
- if (options.predicate) {
147
- steps.push(Object.freeze({ kind: "filter", predicate: options.predicate }));
148
- }
149
- steps.push(Object.freeze({ kind: "project", columns: Object.freeze(outputColumnNames) }));
150
- if (options.limit !== void 0) {
151
- steps.push(Object.freeze({ kind: "limit", limit: options.limit }));
152
- }
153
- return Object.freeze(steps);
154
- }
155
- function validateTableQueryOptions(sourceColumnNames, options) {
156
- const availableColumnNames = new Set(sourceColumnNames);
157
- const outputColumnNames = options.columns ?? sourceColumnNames;
158
- const seenColumnNames = /* @__PURE__ */ new Set();
159
- for (const columnName of outputColumnNames) {
160
- if (!availableColumnNames.has(columnName)) {
161
- throw new Error(`Table query column not found: ${columnName}`);
162
- }
163
- if (seenColumnNames.has(columnName)) {
164
- throw new Error(`Table query column was selected more than once: ${columnName}`);
165
- }
166
- seenColumnNames.add(columnName);
167
- }
168
- validateTableQueryLimit(options.limit);
169
- if (options.predicate) {
170
- (0, import_columnar_predicate2.validateColumnarPredicate)(options.predicate, availableColumnNames);
171
- }
172
- }
173
- function validateTableQueryLimit(limit) {
174
- if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) {
175
- throw new Error("Table query limit must be a non-negative safe integer.");
176
- }
177
- }
178
-
179
- // src/loader-utils/lib/scan-utils/relational-query.ts
180
- function planRelationalQuery(sourceColumnNames, options = {}) {
181
- var _a, _b, _c, _d, _e, _f;
182
- const available = new Set(sourceColumnNames);
183
- const expressionNames = /* @__PURE__ */ new Set();
184
- for (const expression of options.expressions || []) {
185
- if (!expression.name) throw new Error("Relational expression names must be non-empty.");
186
- if (available.has(expression.name) || expressionNames.has(expression.name)) {
187
- throw new Error(`Relational expression duplicates column: ${expression.name}`);
188
- }
189
- expressionNames.add(expression.name);
190
- }
191
- const aggregateNames = new Set((options.aggregates || []).map((aggregate) => aggregate.name));
192
- const requiredColumns = /* @__PURE__ */ new Set();
193
- const availableColumns = new Set(sourceColumnNames);
194
- for (const expression of options.expressions || []) {
195
- const definition = expression.expression;
196
- if (definition.op === "column") {
197
- validateRelationalColumnReference(definition.column, availableColumns);
198
- if (available.has(definition.column)) requiredColumns.add(definition.column);
199
- }
200
- if ("left" in definition) {
201
- validateRelationalColumnReference(definition.left, availableColumns);
202
- validateRelationalColumnReference(definition.right, availableColumns);
203
- if (available.has(definition.left)) requiredColumns.add(definition.left);
204
- if (available.has(definition.right)) requiredColumns.add(definition.right);
205
- }
206
- availableColumns.add(expression.name);
207
- }
208
- for (const key of options.orderBy || []) requiredColumns.add(key.column);
209
- for (const key of options.groupBy || []) requiredColumns.add(key);
210
- for (const aggregate of options.aggregates || []) {
211
- if (aggregate.column) requiredColumns.add(aggregate.column);
212
- }
213
- const outputColumns = (_a = options.columns) == null ? void 0 : _a.filter(
214
- (column) => !expressionNames.has(column) && !aggregateNames.has(column)
215
- );
216
- const tablePlan = [
217
- ...planTableQuery(sourceColumnNames, {
218
- ...options,
219
- columns: outputColumns,
220
- predicate: options.predicate
221
- })
222
- ];
223
- const scanStep = tablePlan[0];
224
- if ((scanStep == null ? void 0 : scanStep.kind) === "scan") {
225
- const scanColumns = new Set(scanStep.columns);
226
- for (const column of requiredColumns) {
227
- if (available.has(column)) scanColumns.add(column);
228
- }
229
- tablePlan[0] = Object.freeze({ kind: "scan", columns: Object.freeze([...scanColumns]) });
230
- }
231
- for (const expression of expressionNames) available.add(expression);
232
- for (const aggregate of aggregateNames) available.add(aggregate);
233
- for (const key of options.orderBy || []) {
234
- if (!available.has(key.column))
235
- throw new Error(`Relational order column not found: ${key.column}`);
236
- }
237
- for (const key of options.groupBy || []) {
238
- if (!available.has(key)) throw new Error(`Relational group column not found: ${key}`);
239
- }
240
- for (const aggregate of options.aggregates || []) {
241
- if (!aggregate.name) throw new Error("Relational aggregate names must be non-empty.");
242
- if (aggregate.function !== "count" && !aggregate.column) {
243
- throw new Error(`Relational aggregate ${aggregate.function} requires a column.`);
244
- }
245
- if (aggregate.column && !available.has(aggregate.column)) {
246
- throw new Error(`Relational aggregate column not found: ${aggregate.column}`);
247
- }
248
- }
249
- const relationalSteps = [];
250
- if ((_b = options.expressions) == null ? void 0 : _b.length)
251
- relationalSteps.push({ kind: "expression", detail: options.expressions });
252
- if ((_c = options.orderBy) == null ? void 0 : _c.length) relationalSteps.push({ kind: "order", detail: options.orderBy });
253
- if (((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.groupBy) == null ? void 0 : _e.length)) {
254
- relationalSteps.push({
255
- kind: "aggregate",
256
- detail: { groupBy: options.groupBy, aggregates: options.aggregates }
257
- });
258
- }
259
- if ((_f = options.union) == null ? void 0 : _f.length) relationalSteps.push({ kind: "union", detail: options.union });
260
- if (options.join) relationalSteps.push({ kind: "join", detail: options.join });
261
- return { tablePlan, relationalSteps: Object.freeze(relationalSteps) };
262
- }
263
- function validateRelationalColumnReference(columnName, availableColumns) {
264
- if (!availableColumns.has(columnName)) {
265
- throw new Error(`Relational expression column not found: ${columnName}`);
266
- }
267
- }
268
-
269
- // src/loader-utils/lib/scan-utils/table-query-explain.ts
270
- function explainTableQuery(sourceColumnNames, options, capabilities) {
271
- const plan = planTableQuery(sourceColumnNames, options);
272
- const outputColumns = options.columns ? [...options.columns] : [...sourceColumnNames];
273
- const predicateColumns = options.predicate ? (0, import_columnar_predicate2.getColumnarPredicateColumns)(options.predicate) : [];
274
- const requiredColumns = [...plan[0].kind === "scan" ? plan[0].columns : []];
275
- return Object.freeze({
276
- sourceColumns: Object.freeze([...sourceColumnNames]),
277
- outputColumns: Object.freeze(outputColumns),
278
- requiredColumns: Object.freeze(requiredColumns),
279
- predicateColumns: Object.freeze(predicateColumns),
280
- plan,
281
- capabilities: Object.freeze({ ...capabilities }),
282
- operators: Object.freeze({
283
- projection: createOperatorExplanation(options.columns !== void 0, capabilities.projection),
284
- predicate: createOperatorExplanation(options.predicate !== void 0, capabilities.predicate),
285
- limit: createOperatorExplanation(options.limit !== void 0, capabilities.limit)
286
- })
287
- });
288
- }
289
- function createOperatorExplanation(enabled, support) {
290
- return Object.freeze({ enabled, support });
291
- }
292
-
293
- // src/schema-utils/lib/schema/data-type.ts
294
- var import_types = require("@math.gl/core/types");
295
- function getDataTypeFromValue(value, defaultNumberType = "float32") {
296
- if (value instanceof Date) {
297
- return "date-millisecond";
298
- }
299
- if (typeof value === "number") {
300
- return defaultNumberType;
301
- }
302
- if (typeof value === "boolean") {
303
- return "bool";
304
- }
305
- if (typeof value === "string") {
306
- return "utf8";
307
- }
308
- if (value === null || value === "undefined") {
309
- return "null";
310
- }
311
- return "null";
312
- }
313
- function getDataTypeFromArray(array) {
314
- let type = getDataTypeFromTypedArray(array);
315
- if (type !== "null") {
316
- return { type, nullable: false };
317
- }
318
- if (array.length > 0) {
319
- type = getDataTypeFromValue(array[0]);
320
- return { type, nullable: true };
321
- }
322
- return { type: "null", nullable: true };
323
- }
324
- function getDataTypeFromTypedArray(array) {
325
- if (typeof Float16Array !== "undefined" && array instanceof Float16Array) {
326
- return "float16";
327
- }
328
- switch (array.constructor) {
329
- case Int8Array:
330
- return "int8";
331
- case Uint8Array:
332
- case Uint8ClampedArray:
333
- return "uint8";
334
- case Int16Array:
335
- return "int16";
336
- case Uint16Array:
337
- return "uint16";
338
- case Int32Array:
339
- return "int32";
340
- case Uint32Array:
341
- return "uint32";
342
- case BigInt64Array:
343
- return "int64";
344
- case BigUint64Array:
345
- return "uint64";
346
- case Float32Array:
347
- return "float32";
348
- case Float64Array:
349
- return "float64";
350
- default:
351
- return "null";
352
- }
353
- }
354
-
355
- // src/schema-utils/lib/schema/convert-arrow-schema.ts
356
- var arrow = __toESM(require("apache-arrow"), 1);
357
- function convertArrowToSchema(arrowSchema) {
358
- return serializeArrowSchema(arrowSchema);
359
- }
360
- function convertSchemaToArrow(schema, options) {
361
- return deserializeArrowSchema(schema, options);
362
- }
363
- function serializeArrowSchema(arrowSchema) {
364
- return {
365
- fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
366
- metadata: serializeArrowMetadata(arrowSchema.metadata)
367
- };
368
- }
369
- function deserializeArrowSchema(schema, options) {
370
- return new arrow.Schema(
371
- schema.fields.map((field) => deserializeArrowField(field, options)),
372
- deserializeArrowMetadata(schema.metadata)
373
- );
374
- }
375
- function serializeArrowMetadata(arrowMetadata) {
376
- return Object.fromEntries(arrowMetadata);
377
- }
378
- function deserializeArrowMetadata(metadata) {
379
- return metadata ? new Map(Object.entries(metadata)) : /* @__PURE__ */ new Map();
380
- }
381
- function serializeArrowField(field) {
382
- return {
383
- name: field.name,
384
- type: serializeArrowType(field.type),
385
- nullable: field.nullable,
386
- metadata: serializeArrowMetadata(field.metadata)
387
- };
388
- }
389
- function deserializeArrowField(field, options) {
390
- return new arrow.Field(
391
- field.name,
392
- deserializeArrowType(field.type, options),
393
- field.nullable,
394
- deserializeArrowMetadata(field.metadata)
395
- );
396
- }
397
- function serializeArrowType(arrowType) {
398
- if (isArrowViewType(arrowType, "BinaryView")) {
399
- return "binary-view";
400
- }
401
- if (isArrowViewType(arrowType, "Utf8View")) {
402
- return "utf8-view";
403
- }
404
- if (isOptionalArrowType(arrowType, "LargeList")) {
405
- const largeListType = arrowType;
406
- return {
407
- type: "large-list",
408
- children: [serializeArrowField(largeListType.valueField)]
409
- };
410
- }
411
- switch (arrowType.constructor) {
412
- case arrow.Null:
413
- return "null";
414
- case arrow.Binary:
415
- return "binary";
416
- case arrow.FixedSizeBinary:
417
- return {
418
- type: "fixed-size-binary",
419
- byteWidth: arrowType.byteWidth
420
- };
421
- case arrow.Bool:
422
- return "bool";
423
- case arrow.Int:
424
- const intType = arrowType;
425
- return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
426
- case arrow.Int8:
427
- return "int8";
428
- case arrow.Int16:
429
- return "int16";
430
- case arrow.Int32:
431
- return "int32";
432
- case arrow.Int64:
433
- return "int64";
434
- case arrow.Uint8:
435
- return "uint8";
436
- case arrow.Uint16:
437
- return "uint16";
438
- case arrow.Uint32:
439
- return "uint32";
440
- case arrow.Uint64:
441
- return "uint64";
442
- case arrow.Float:
443
- const precision = arrowType.precision;
444
- switch (precision) {
445
- case arrow.Precision.HALF:
446
- return "float16";
447
- case arrow.Precision.SINGLE:
448
- return "float32";
449
- case arrow.Precision.DOUBLE:
450
- return "float64";
451
- default:
452
- return "float16";
453
- }
454
- case arrow.Float16:
455
- return "float16";
456
- case arrow.Float32:
457
- return "float32";
458
- case arrow.Float64:
459
- return "float64";
460
- case arrow.Utf8:
461
- return "utf8";
462
- case arrow.Decimal:
463
- const decimal = arrowType;
464
- return {
465
- type: "decimal",
466
- bitWidth: decimal.bitWidth,
467
- precision: decimal.precision,
468
- scale: decimal.scale
469
- };
470
- case arrow.Date_:
471
- const dateUnit = arrowType.unit;
472
- return dateUnit === arrow.DateUnit.DAY ? "date-day" : "date-millisecond";
473
- case arrow.DateDay:
474
- return "date-day";
475
- case arrow.DateMillisecond:
476
- return "date-millisecond";
477
- case arrow.Time:
478
- const timeUnit = arrowType.unit;
479
- switch (timeUnit) {
480
- case arrow.TimeUnit.SECOND:
481
- return "time-second";
482
- case arrow.TimeUnit.MILLISECOND:
483
- return "time-millisecond";
484
- case arrow.TimeUnit.MICROSECOND:
485
- return "time-microsecond";
486
- case arrow.TimeUnit.NANOSECOND:
487
- return "time-nanosecond";
488
- default:
489
- return "time-second";
490
- }
491
- case arrow.TimeMillisecond:
492
- return "time-millisecond";
493
- case arrow.TimeSecond:
494
- return "time-second";
495
- case arrow.TimeMicrosecond:
496
- return "time-microsecond";
497
- case arrow.TimeNanosecond:
498
- return "time-nanosecond";
499
- case arrow.Timestamp:
500
- const timeStampUnit = arrowType.unit;
501
- switch (timeStampUnit) {
502
- case arrow.TimeUnit.SECOND:
503
- return "timestamp-second";
504
- case arrow.TimeUnit.MILLISECOND:
505
- return "timestamp-millisecond";
506
- case arrow.TimeUnit.MICROSECOND:
507
- return "timestamp-microsecond";
508
- case arrow.TimeUnit.NANOSECOND:
509
- return "timestamp-nanosecond";
510
- default:
511
- return "timestamp-second";
512
- }
513
- case arrow.TimestampSecond:
514
- return "timestamp-second";
515
- case arrow.TimestampMillisecond:
516
- return "timestamp-millisecond";
517
- case arrow.TimestampMicrosecond:
518
- return "timestamp-microsecond";
519
- case arrow.TimestampNanosecond:
520
- return "timestamp-nanosecond";
521
- case arrow.Interval:
522
- const intervalUnit = arrowType.unit;
523
- switch (intervalUnit) {
524
- case arrow.IntervalUnit.DAY_TIME:
525
- return "interval-daytime";
526
- case arrow.IntervalUnit.YEAR_MONTH:
527
- return "interval-yearmonth";
528
- default:
529
- return "interval-daytime";
530
- }
531
- case arrow.IntervalDayTime:
532
- return "interval-daytime";
533
- case arrow.IntervalYearMonth:
534
- return "interval-yearmonth";
535
- case arrow.Map_:
536
- const mapType = arrowType;
537
- return {
538
- type: "map",
539
- keysSorted: mapType.keysSorted,
540
- children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
541
- };
542
- case arrow.List:
543
- const listType = arrowType;
544
- const listField = listType.valueField;
545
- return {
546
- type: "list",
547
- children: [serializeArrowField(listField)]
548
- };
549
- case arrow.FixedSizeList:
550
- const fixedSizeList = arrowType;
551
- return {
552
- type: "fixed-size-list",
553
- listSize: fixedSizeList.listSize,
554
- children: [serializeArrowField(fixedSizeList.children[0])]
555
- };
556
- case arrow.Struct:
557
- const structType = arrowType;
558
- return {
559
- type: "struct",
560
- children: structType.children.map((arrowField) => serializeArrowField(arrowField))
561
- };
562
- case arrow.SparseUnion:
563
- case arrow.DenseUnion:
564
- const unionType = arrowType;
565
- return {
566
- type: unionType instanceof arrow.DenseUnion ? "dense-union" : "sparse-union",
567
- typeIds: unionType.typeIds,
568
- children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
569
- typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
570
- };
571
- case arrow.Dictionary:
572
- const dictionaryType = arrowType;
573
- return {
574
- type: "dictionary",
575
- id: dictionaryType.id,
576
- indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
577
- dictionary: serializeArrowType(dictionaryType.dictionary),
578
- isOrdered: dictionaryType.isOrdered
579
- };
580
- default:
581
- throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
582
- }
583
- }
584
- function deserializeArrowType(dataType, options) {
585
- if (typeof dataType === "object") {
586
- switch (dataType.type) {
587
- case "decimal":
588
- return new arrow.Decimal(dataType.scale, dataType.precision, dataType.bitWidth);
589
- case "map": {
590
- const children = dataType.children.map(
591
- (arrowField) => deserializeArrowField(arrowField, options)
592
- );
593
- return new arrow.Map_(children[0], dataType.keysSorted);
594
- }
595
- case "list": {
596
- const field = deserializeArrowField(dataType.children[0], options);
597
- return new arrow.List(field);
598
- }
599
- case "large-list": {
600
- const field = deserializeArrowField(dataType.children[0], options);
601
- const LargeList = getOptionalArrowConstructor("LargeList");
602
- if (!LargeList) {
603
- throw new Error(
604
- "LargeList requires an Apache Arrow runtime that exports the LargeList constructor"
605
- );
606
- }
607
- return new LargeList(field);
608
- }
609
- case "fixed-size-list": {
610
- const child = deserializeArrowField(dataType.children[0], options);
611
- return new arrow.FixedSizeList(dataType.listSize, child);
612
- }
613
- case "fixed-size-binary":
614
- return new arrow.FixedSizeBinary(dataType.byteWidth);
615
- case "struct": {
616
- const children = dataType.children.map(
617
- (arrowField) => deserializeArrowField(arrowField, options)
618
- );
619
- return new arrow.Struct(children);
620
- }
621
- case "sparse-union":
622
- case "dense-union": {
623
- const children = dataType.children.map(
624
- (arrowField) => deserializeArrowField(arrowField, options)
625
- );
626
- return dataType.type === "dense-union" ? new arrow.DenseUnion(dataType.typeIds, children) : new arrow.SparseUnion(dataType.typeIds, children);
627
- }
628
- case "dictionary": {
629
- return new arrow.Dictionary(
630
- deserializeArrowType(dataType.dictionary, options),
631
- deserializeArrowDictionaryKeyType(dataType.indices),
632
- dataType.id,
633
- dataType.isOrdered
634
- );
635
- }
636
- default:
637
- throw new Error("array type not supported");
638
- }
639
- }
640
- switch (dataType) {
641
- case "null":
642
- return new arrow.Null();
643
- case "binary":
644
- return makeVariableWidthArrowType("BinaryView", new arrow.Binary(), options);
645
- case "binary-view":
646
- return makeRequiredArrowViewType("BinaryView");
647
- case "bool":
648
- return new arrow.Bool();
649
- case "int8":
650
- return new arrow.Int8();
651
- case "int16":
652
- return new arrow.Int16();
653
- case "int32":
654
- return new arrow.Int32();
655
- case "int64":
656
- return new arrow.Int64();
657
- case "uint8":
658
- return new arrow.Uint8();
659
- case "uint16":
660
- return new arrow.Uint16();
661
- case "uint32":
662
- return new arrow.Uint32();
663
- case "uint64":
664
- return new arrow.Uint64();
665
- case "float16":
666
- return new arrow.Float16();
667
- case "float32":
668
- return new arrow.Float32();
669
- case "float64":
670
- return new arrow.Float64();
671
- case "utf8":
672
- return makeVariableWidthArrowType("Utf8View", new arrow.Utf8(), options);
673
- case "utf8-view":
674
- return makeRequiredArrowViewType("Utf8View");
675
- case "date-day":
676
- return new arrow.DateDay();
677
- case "date-millisecond":
678
- return new arrow.DateMillisecond();
679
- case "time-second":
680
- return new arrow.TimeSecond();
681
- case "time-millisecond":
682
- return new arrow.TimeMillisecond();
683
- case "time-microsecond":
684
- return new arrow.TimeMicrosecond();
685
- case "time-nanosecond":
686
- return new arrow.TimeNanosecond();
687
- case "timestamp-second":
688
- return new arrow.TimestampSecond();
689
- case "timestamp-millisecond":
690
- return new arrow.TimestampMillisecond();
691
- case "timestamp-microsecond":
692
- return new arrow.TimestampMicrosecond();
693
- case "timestamp-nanosecond":
694
- return new arrow.TimestampNanosecond();
695
- case "interval-daytime":
696
- return new arrow.IntervalDayTime();
697
- case "interval-yearmonth":
698
- return new arrow.IntervalYearMonth();
699
- default:
700
- throw new Error("array type not supported");
701
- }
702
- }
703
- function getOptionalArrowConstructor(typeName) {
704
- return arrow[typeName];
705
- }
706
- function isArrowViewType(arrowType, viewTypeName) {
707
- const constructor = getOptionalArrowConstructor(viewTypeName);
708
- if (constructor && arrowType instanceof constructor) {
709
- return true;
710
- }
711
- const guards = arrow.DataType;
712
- const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
713
- return Boolean(guard == null ? void 0 : guard(arrowType));
714
- }
715
- function isOptionalArrowType(arrowType, typeName) {
716
- const constructor = getOptionalArrowConstructor(typeName);
717
- return Boolean(constructor && arrowType instanceof constructor);
718
- }
719
- function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
720
- const viewTypeMode = (options == null ? void 0 : options.viewTypes) || "never";
721
- if (viewTypeMode === "never") {
722
- return fallbackType;
723
- }
724
- const constructor = getOptionalArrowConstructor(viewTypeName);
725
- if (constructor) {
726
- return new constructor();
727
- }
728
- if (viewTypeMode === "require") {
729
- throw new Error(
730
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
731
- );
732
- }
733
- return fallbackType;
734
- }
735
- function makeRequiredArrowViewType(viewTypeName) {
736
- const constructor = getOptionalArrowConstructor(viewTypeName);
737
- if (!constructor) {
738
- throw new Error(
739
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
740
- );
741
- }
742
- return new constructor();
743
- }
744
- function serializeArrowDictionaryKeyType(arrowType) {
745
- if (arrowType instanceof arrow.Int) {
746
- const prefix = arrowType.isSigned ? "int" : "uint";
747
- const keyType = `${prefix}${arrowType.bitWidth}`;
748
- if (isSchemaDictionaryKeyType(keyType)) {
749
- return keyType;
750
- }
751
- }
752
- switch (arrowType.constructor) {
753
- case arrow.Int8:
754
- return "int8";
755
- case arrow.Int16:
756
- return "int16";
757
- case arrow.Int32:
758
- return "int32";
759
- case arrow.Uint8:
760
- return "uint8";
761
- case arrow.Uint16:
762
- return "uint16";
763
- case arrow.Uint32:
764
- return "uint32";
765
- default:
766
- throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
767
- }
768
- }
769
- function isSchemaDictionaryKeyType(keyType) {
770
- return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
771
- }
772
- function deserializeArrowDictionaryKeyType(keyType) {
773
- switch (keyType) {
774
- case "int8":
775
- return new arrow.Int8();
776
- case "int16":
777
- return new arrow.Int16();
778
- case "int32":
779
- return new arrow.Int32();
780
- case "uint8":
781
- return new arrow.Uint8();
782
- case "uint16":
783
- return new arrow.Uint16();
784
- case "uint32":
785
- return new arrow.Uint32();
786
- default:
787
- throw new Error(`schema dictionary index type not supported: ${keyType}`);
788
- }
789
- }
790
-
791
- // src/schema-utils/lib/schema/deduce-table-schema.ts
792
- function deduceTableSchema(table) {
793
- if (!("shape" in table)) return convertArrowToSchema(table.schema);
794
- switch (table.shape) {
795
- case "array-row-table":
796
- case "object-row-table":
797
- return deduceSchemaFromRows(table.data);
798
- case "geojson-table":
799
- return deduceSchemaFromGeoJSON(table.features);
800
- case "columnar-table":
801
- return deduceSchemaFromColumns(table.data);
802
- default:
803
- throw new Error("Deduce schema");
804
- }
805
- }
806
- function deduceSchemaFromColumns(columnarTable) {
807
- const fields = [];
808
- for (const [columnName, column] of Object.entries(columnarTable)) {
809
- const field = deduceFieldFromColumn(column, columnName);
810
- fields.push(field);
811
- }
812
- return { fields, metadata: {} };
813
- }
814
- function deduceSchemaFromRows(rowTable) {
815
- if (!rowTable.length) {
816
- throw new Error("deduce from empty table");
817
- }
818
- const fields = [];
819
- const row0 = rowTable[0];
820
- for (const [columnName, value] of Object.entries(row0)) {
821
- const name = Array.isArray(row0) ? `column${Number(columnName) + 1}` : columnName;
822
- fields.push(deduceFieldFromValue(value, name));
823
- }
824
- return { fields, metadata: {} };
825
- }
826
- function deduceSchemaFromGeoJSON(features) {
827
- if (!features.length) {
828
- throw new Error("deduce from empty table");
829
- }
830
- const fields = [];
831
- const row0 = features[0].properties || {};
832
- for (const [columnName, value] of Object.entries(row0)) {
833
- fields.push(deduceFieldFromValue(value, columnName));
834
- }
835
- return { fields, metadata: {} };
836
- }
837
- function deduceFieldFromColumn(column, name) {
838
- if (ArrayBuffer.isView(column)) {
839
- const type = getDataTypeFromArray(column);
840
- return {
841
- name,
842
- type: type.type || "null",
843
- nullable: type.nullable
844
- // metadata: {}
845
- };
846
- }
847
- if (Array.isArray(column) && column.length > 0) {
848
- const value = column[0];
849
- const type = getDataTypeFromValue(value);
850
- return {
851
- name,
852
- type,
853
- nullable: true
854
- // metadata: {},
855
- };
856
- }
857
- throw new Error("empty table");
858
- }
859
- function deduceFieldFromValue(value, name) {
860
- const type = getDataTypeFromValue(value);
861
- return {
862
- name,
863
- type,
864
- nullable: true
865
- // metadata: {}
866
- };
867
- }
868
-
869
- // src/schema-utils/lib/table/tables/table-accessors.ts
870
- function getTableLength(table) {
871
- if (!("shape" in table)) return table.numRows;
872
- switch (table.shape) {
873
- case "array-row-table":
874
- case "object-row-table":
875
- return table.data.length;
876
- case "geojson-table":
877
- return table.features.length;
878
- case "columnar-table":
879
- for (const column of Object.values(table.data)) {
880
- return column.length || 0;
881
- }
882
- return 0;
883
- default:
884
- throw new Error("table");
885
- }
886
- }
887
- function getTableNumCols(table) {
888
- if (!("shape" in table)) return table.numCols;
889
- if (table.schema) {
890
- return table.schema.fields.length;
891
- }
892
- if (getTableLength(table) === 0) {
893
- throw new Error("empty table");
894
- }
895
- switch (table.shape) {
896
- case "array-row-table":
897
- return table.data[0].length;
898
- case "object-row-table":
899
- return Object.keys(table.data[0]).length;
900
- case "geojson-table":
901
- return Object.keys(table.features[0]).length;
902
- case "columnar-table":
903
- return Object.keys(table.data).length;
904
- default:
905
- throw new Error("table");
906
- }
907
- }
908
- function getTableCellAt(table, rowIndex, columnIndex) {
909
- var _a;
910
- if (!("shape" in table)) return (_a = table.getChildAt(columnIndex)) == null ? void 0 : _a.get(rowIndex);
911
- switch (table.shape) {
912
- case "array-row-table":
913
- return table.data[rowIndex][columnIndex];
914
- case "object-row-table":
915
- const columnName1 = getTableColumnName(table, columnIndex);
916
- return table.data[rowIndex][columnName1];
917
- case "geojson-table":
918
- const columnName2 = getTableColumnName(table, columnIndex);
919
- return table.features[rowIndex][columnName2];
920
- case "columnar-table":
921
- const columnName3 = getTableColumnName(table, columnIndex);
922
- const column = table.data[columnName3];
923
- return column[rowIndex];
924
- default:
925
- throw new Error("todo");
926
- }
927
- }
928
- function getTableColumnName(table, columnIndex) {
929
- var _a, _b;
930
- const columnName = (_b = (_a = table.schema) == null ? void 0 : _a.fields[columnIndex]) == null ? void 0 : _b.name;
931
- if (!columnName) {
932
- throw new Error(`${columnIndex}`);
933
- }
934
- return columnName;
935
- }
936
-
937
- // src/schema-utils/lib/table/tables/convert-arrow-table.ts
938
- var arrow3 = __toESM(require("apache-arrow"), 1);
939
-
940
- // src/schema-utils/lib/table/batches/make-arrow-batch-iterator.ts
941
- var arrow2 = __toESM(require("apache-arrow"), 1);
942
- function* makePortableTableRecordBatchIterator(table, options) {
943
- const arrowSchema = convertSchemaToArrow(table.schema);
944
- const length = getTableLength(table);
945
- const numColumns = getTableNumCols(table);
946
- const batchSize = (options == null ? void 0 : options.batchSize) || length;
947
- const builders = arrowSchema == null ? void 0 : arrowSchema.fields.map(
948
- (arrowField) => arrow2.makeBuilder({
949
- type: arrowField.type,
950
- nullValues: [null, void 0]
951
- })
952
- );
953
- const structField = new arrow2.Struct(arrowSchema.fields);
954
- let batchLength = 0;
955
- for (let rowIndex = 0; rowIndex < length; rowIndex++) {
956
- for (let columnIndex = 0; columnIndex < numColumns; ++columnIndex) {
957
- const value = getTableCellAt(table, rowIndex, columnIndex);
958
- const builder = builders[columnIndex];
959
- builder.append(value);
960
- }
961
- batchLength++;
962
- if (batchLength >= batchSize) {
963
- const datas = builders.map((builder) => builder.flush());
964
- const structData = new arrow2.Data(structField, 0, batchLength, 0, void 0, datas);
965
- yield new arrow2.RecordBatch(arrowSchema, structData);
966
- batchLength = 0;
967
- }
968
- }
969
- if (batchLength > 0) {
970
- const datas = builders.map((builder) => builder.flush());
971
- const structData = new arrow2.Data(structField, 0, batchLength, 0, void 0, datas);
972
- yield new arrow2.RecordBatch(arrowSchema, structData);
973
- batchLength = 0;
974
- }
975
- builders.map((builder) => builder.finish());
976
- }
977
-
978
- // src/schema-utils/lib/table/tables/convert-arrow-table.ts
979
- function convertTableToArrow(table, options) {
980
- if (!("shape" in table)) return table;
981
- const schema = table.schema ?? deduceTableSchema(table);
982
- return new arrow3.Table(convertSchemaToArrow(schema), [
983
- ...makePortableTableRecordBatchIterator({ ...table, schema }, options)
984
- ]);
985
- }
986
-
987
- // src/schema-utils/deprecated.ts
988
- var convertTableToArrow2 = ((...args) => convertTableToArrow(
989
- ...args
990
- ));
991
-
992
- // dist/scan/arrow-execution.js
993
- var import_arrow2 = require("@math.gl/core/arrow");
994
-
995
- // dist/scan/arrow-execution/filter-arrow-table.js
996
- var arrow4 = __toESM(require("apache-arrow"), 1);
997
- var import_arrow = require("@math.gl/core/arrow");
998
- var import_columnar_predicate6 = require("@math.gl/sql/columnar-predicate");
999
- function filterArrowTable(source, predicate, options = {}) {
1000
- (0, import_columnar_predicate2.validateColumnarPredicate)(predicate, new Set(source.schema.fields.map((field) => field.name)));
1001
- const boundPredicate = normalizeArrowDatePredicate(predicate);
1002
- return filterArrowRows(source, (batch) => {
1003
- const evaluate = (0, import_columnar_predicate6.compileColumnarPredicate)(boundPredicate, (path) => bindPredicateColumn(batch, path));
1004
- return (rowIndex) => evaluate(rowIndex) === true;
1005
- }, options);
1006
- }
1007
- function bindPredicateColumn(batch, [name, ...properties]) {
1008
- const column = batch.getChild(name);
1009
- if (!column)
1010
- throw new Error(`Arrow query column not found: ${name}`);
1011
- return (rowIndex) => {
1012
- let value = column.get(rowIndex);
1013
- for (const property of properties) {
1014
- if (value == null)
1015
- return null;
1016
- value = value[property];
1017
- }
1018
- return dateToMilliseconds(value);
1019
- };
1020
- }
1021
- function normalizeArrowDatePredicate(predicate) {
1022
- switch (predicate.op) {
1023
- case "and":
1024
- case "or":
1025
- return { ...predicate, args: predicate.args.map(normalizeArrowDatePredicate) };
1026
- case "not":
1027
- return { ...predicate, args: [normalizeArrowDatePredicate(predicate.args[0])] };
1028
- case "isNull":
1029
- return predicate;
1030
- case "in":
1031
- return { ...predicate, args: [predicate.args[0], predicate.args[1].map(dateToMilliseconds)] };
1032
- default:
1033
- return { ...predicate, args: [predicate.args[0], dateToMilliseconds(predicate.args[1])] };
1034
- }
1035
- }
1036
- function dateToMilliseconds(value) {
1037
- return value instanceof Date ? value.getTime() : value;
1038
- }
1039
- function filterArrowRows(source, selectBatch, options = {}) {
1040
- var _a, _b, _c;
1041
- let remaining = options.limit ?? Infinity;
1042
- if (remaining !== Infinity && (!Number.isSafeInteger(remaining) || remaining < 0)) {
1043
- throw new Error("Arrow filter limit must be a non-negative safe integer.");
1044
- }
1045
- (_a = options.signal) == null ? void 0 : _a.throwIfAborted();
1046
- const batches = [];
1047
- for (const batch of source.batches) {
1048
- if (remaining === 0)
1049
- break;
1050
- (_b = options.signal) == null ? void 0 : _b.throwIfAborted();
1051
- const selectRow = selectBatch(batch);
1052
- const indices = [];
1053
- for (let rowIndex = 0; rowIndex < batch.numRows && indices.length < remaining; rowIndex++) {
1054
- (_c = options.signal) == null ? void 0 : _c.throwIfAborted();
1055
- if (selectRow(rowIndex))
1056
- indices.push(rowIndex);
1057
- }
1058
- remaining -= indices.length;
1059
- const selected = (0, import_arrow.selectArrowBatchRows)(batch, indices);
1060
- if (selected)
1061
- batches.push(selected);
1062
- }
1063
- return new arrow4.Table(source.schema, batches);
1064
- }
1065
-
1066
- // dist/scan/sql-predicate-schema.js
1067
- var import_parser = require("@math.gl/sql/parser");
1068
- function validateSQLPredicate(value) {
1069
- (0, import_parser.validateSQLPredicate)(value);
1070
- rejectPredicateCasts(value, "$");
1071
- }
1072
- function rejectPredicateCasts(predicate, path) {
1073
- if (predicate.op === "and" || predicate.op === "or" || predicate.op === "not") {
1074
- predicate.args.forEach((child, index) => rejectPredicateCasts(child, path + ".args[" + index + "]"));
1075
- } else if (Object.hasOwn(predicate.args[0], "casts")) {
1076
- throw new Error("SQL predicate " + path + ".args[0] requires a non-empty property reference");
1077
- }
1078
- }
1079
-
1080
- // dist/scan/table-query.js
1081
- function planTableQuery2(sourceColumnNames, options = {}) {
1082
- if (options.predicate) {
1083
- validateSQLPredicate(options.predicate);
1084
- }
1085
- return planTableQuery(sourceColumnNames, options);
1086
- }
1087
-
1088
- // dist/scan/plan-arrow-table-query.js
1089
- var executePortableArrowQuery = (table, { select, where, limit, signal }) => {
1090
- if (where)
1091
- table = filterArrowTable(table, where, { limit, signal });
1092
- const projected = select ? (0, import_arrow2.projectArrowTable)(table, select) : table;
1093
- return projected.numRows === 0 || limit === void 0 ? projected : projected.slice(0, limit);
1094
- };
1095
- function queryArrowTable(sourceTable, options = {}, execute) {
1096
- throwIfAborted(options.signal);
1097
- if (options.select !== void 0) {
1098
- if (options.columns !== void 0 || hasRelationalOperators(options) || options.join) {
1099
- throw new Error("Arrow select cannot be combined with columns or relational operators.");
1100
- }
1101
- return (execute ?? executePortableArrowQuery)(sourceTable, {
1102
- where: options.predicate,
1103
- select: options.select,
1104
- limit: options.limit,
1105
- signal: options.signal
1106
- });
1107
- }
1108
- if (options.join || hasRelationalOperators(options)) {
1109
- if (options.join) {
1110
- validateArrowJoinQuery(sourceTable, options);
1111
- if (hasRelationalOperators(options)) {
1112
- throw new Error("Arrow joins cannot yet be combined with other relational operators.");
1113
- }
1114
- }
1115
- if (!execute)
1116
- throw new Error("Relational queries require the SQL executor.");
1117
- return options.join ? queryArrowJoin(sourceTable, options, execute) : queryArrowTableRelational(sourceTable, options, execute);
1118
- }
1119
- const plan = planTableQuery2(sourceTable.schema.fields.map((field) => field.name), options);
1120
- const projection = plan.find((step) => step.kind === "project");
1121
- return (execute ?? executePortableArrowQuery)(sourceTable, {
1122
- where: options.predicate,
1123
- select: projection == null ? void 0 : projection.columns,
1124
- limit: options.limit,
1125
- signal: options.signal
1126
- });
1127
- }
1128
- function queryArrowTableRelational(sourceTable, options, execute) {
1129
- var _a, _b, _c;
1130
- const sourceColumns = sourceTable.schema.fields.map((field) => field.name);
1131
- const grouped = ((_a = options.groupBy) == null ? void 0 : _a.length) || ((_b = options.aggregates) == null ? void 0 : _b.length);
1132
- const outputColumns = options.columns ?? (grouped ? [...options.groupBy ?? [], ...(options.aggregates ?? []).map((aggregate) => aggregate.name)] : sourceColumns);
1133
- const plan = planRelationalQuery(sourceColumns, { ...options, columns: outputColumns });
1134
- const scan = plan.tablePlan.find((step) => step.kind === "scan");
1135
- let table = execute(sourceTable, {
1136
- where: options.predicate,
1137
- select: scan.columns,
1138
- signal: options.signal
1139
- });
1140
- if ((_c = options.union) == null ? void 0 : _c.length) {
1141
- const childPlan = planRelationalQuery(sourceColumns, {
1142
- ...options,
1143
- columns: outputColumns,
1144
- predicate: void 0
1145
- });
1146
- const columns = childPlan.tablePlan.find((step) => step.kind === "scan").columns;
1147
- const union = options.union.map((child) => {
1148
- var _a2;
1149
- const input = (_a2 = options.tables) == null ? void 0 : _a2[child.source];
1150
- if (!input)
1151
- throw new Error("Arrow union source not found: " + child.source);
1152
- return queryArrowTable(input, { ...child.query, columns, signal: options.signal }, execute);
1153
- });
1154
- table = execute((0, import_arrow2.projectArrowTable)(table, columns), { union, signal: options.signal });
1155
- }
1156
- for (const { name, expression } of options.expressions ?? []) {
1157
- const select = [
1158
- ...table.schema.fields.map((field) => field.name),
1159
- expression.op === "column" ? { column: expression.column, as: name } : { expression: toArrowExpression(expression), as: name }
1160
- ];
1161
- table = execute(table, { select, signal: options.signal });
1162
- }
1163
- return execute(table, {
1164
- select: outputColumns,
1165
- groupBy: options.groupBy,
1166
- aggregates: Object.fromEntries((options.aggregates ?? []).map((aggregate) => {
1167
- const expression = aggregate.column === void 0 ? void 0 : identifier(aggregate.column);
1168
- if (aggregate.function === "count")
1169
- return [aggregate.name, { operation: "COUNT", expression }];
1170
- const operations = { sum: "SUM", min: "MIN", max: "MAX", avg: "AVG" };
1171
- return [
1172
- aggregate.name,
1173
- { operation: operations[aggregate.function], expression }
1174
- ];
1175
- })),
1176
- orderBy: options.orderBy,
1177
- limit: options.limit,
1178
- signal: options.signal
1179
- });
1180
- }
1181
- function identifier(name) {
1182
- return { type: "Identifier", name };
1183
- }
1184
- function toArrowExpression(expression) {
1185
- if (expression.op === "literal")
1186
- return literal(expression.value);
1187
- const operators = { add: "+", subtract: "-", multiply: "*", divide: "/" };
1188
- const binary = {
1189
- type: "BinaryExpression",
1190
- operator: operators[expression.op],
1191
- left: identifier(expression.left),
1192
- right: identifier(expression.right)
1193
- };
1194
- if (expression.op !== "divide")
1195
- return binary;
1196
- return {
1197
- type: "ConditionalExpression",
1198
- test: { ...binary, operator: "===", left: binary.right, right: literal(0) },
1199
- consequent: literal(null),
1200
- alternate: binary
1201
- };
1202
- }
1203
- function literal(value) {
1204
- return { type: "Literal", value };
1205
- }
1206
- function hasRelationalOperators(options) {
1207
- var _a, _b, _c, _d, _e;
1208
- return Boolean(((_a = options.expressions) == null ? void 0 : _a.length) || ((_b = options.orderBy) == null ? void 0 : _b.length) || ((_c = options.groupBy) == null ? void 0 : _c.length) || ((_d = options.aggregates) == null ? void 0 : _d.length) || ((_e = options.union) == null ? void 0 : _e.length));
1209
- }
1210
- function queryArrowJoin(sourceTable, options, executeRelational) {
1211
- var _a, _b, _c, _d;
1212
- const join = options.join;
1213
- const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
1214
- if (!childTable)
1215
- throw new Error(`Arrow join source not found: ${join.child.source}`);
1216
- const left = executeRelational(sourceTable, {
1217
- where: options.predicate,
1218
- signal: options.signal
1219
- });
1220
- const right = executeRelational(childTable, {
1221
- where: (_b = join.child.query) == null ? void 0 : _b.predicate,
1222
- select: (_c = join.child.query) == null ? void 0 : _c.columns,
1223
- limit: (_d = join.child.query) == null ? void 0 : _d.limit,
1224
- signal: options.signal
1225
- });
1226
- return executeRelational(left, {
1227
- join: {
1228
- table: right,
1229
- type: join.type,
1230
- left: join.left,
1231
- right: join.right,
1232
- rightPrefix: `${join.child.source}.`
1233
- },
1234
- select: options.columns,
1235
- limit: options.limit,
1236
- signal: options.signal
1237
- });
1238
- }
1239
- function validateArrowJoinQuery(sourceTable, options) {
1240
- var _a, _b, _c;
1241
- const join = options.join;
1242
- if (!join)
1243
- return;
1244
- const sourceColumnNames = sourceTable.schema.fields.map((field) => field.name);
1245
- const childTable = (_a = options.tables) == null ? void 0 : _a[join.child.source];
1246
- if (!childTable)
1247
- throw new Error(`Arrow join source not found: ${join.child.source}`);
1248
- const childColumnNames = childTable.schema.fields.map((field) => field.name);
1249
- if (!sourceColumnNames.includes(join.left)) {
1250
- throw new Error(`Arrow join column not found: ${join.left}`);
1251
- }
1252
- if (!childColumnNames.includes(join.right)) {
1253
- throw new Error(`Arrow join column not found: ${join.right}`);
1254
- }
1255
- const childPrefix = `${join.child.source}.`;
1256
- const rootColumns = (_b = options.columns) == null ? void 0 : _b.filter((column) => !column.startsWith(childPrefix));
1257
- planTableQuery2(sourceColumnNames, {
1258
- predicate: options.predicate,
1259
- columns: (rootColumns == null ? void 0 : rootColumns.length) ? rootColumns : void 0,
1260
- limit: options.limit,
1261
- signal: options.signal
1262
- });
1263
- const childQuery = join.child.query || {};
1264
- planTableQuery2(childColumnNames, childQuery);
1265
- const childOutputColumns = childQuery.columns || childColumnNames;
1266
- if (!childOutputColumns.includes(join.right)) {
1267
- throw new Error(`Arrow join child projection must include: ${join.right}`);
1268
- }
1269
- const projectedChildColumns = ((_c = options.columns) == null ? void 0 : _c.filter((column) => column.startsWith(childPrefix))) || [];
1270
- const seenChildColumns = /* @__PURE__ */ new Set();
1271
- for (const projectedColumn of projectedChildColumns) {
1272
- const childColumn = projectedColumn.slice(childPrefix.length);
1273
- if (!childColumnNames.includes(childColumn)) {
1274
- throw new Error(`Arrow join column not found: ${projectedColumn}`);
1275
- }
1276
- if (seenChildColumns.has(childColumn)) {
1277
- throw new Error(`Arrow query column was selected more than once: ${projectedColumn}`);
1278
- }
1279
- seenChildColumns.add(childColumn);
1280
- if (!childOutputColumns.includes(childColumn)) {
1281
- throw new Error(`Arrow join child projection does not include: ${childColumn}`);
1282
- }
1283
- }
1284
- }
1285
- function throwIfAborted(signal) {
1286
- if (signal == null ? void 0 : signal.aborted) {
1287
- const error = new Error("Arrow query was aborted.");
1288
- error.name = "AbortError";
1289
- throw error;
1290
- }
1291
- }
1292
-
1293
- // dist/scan/federated-table-scan-source.js
1294
- function getFederatedTableBatchProvenance(batch) {
1295
- return JSON.parse(batch.metadata.get("loaders.gl.federation"));
1296
- }
1297
- var FEDERATED_TABLE_QUERY_CAPABILITIES = Object.freeze({
1298
- predicate: "residual",
1299
- projection: "pushdown+residual",
1300
- limit: "pushdown+residual",
1301
- streaming: true,
1302
- cancellation: true
1303
- });
1304
- var nextFederatedSourceId = 0;
1305
- var FederatedTableScanSource = class {
1306
- /** Shared manager used as the authoritative named-source registry. */
1307
- dataSourceManager;
1308
- /** Immutable sources in physical append order. */
1309
- sources;
1310
- /** Schema reconciliation policy. */
1311
- schemaPolicy;
1312
- /** Optional caller-declared normalized output schema. */
1313
- outputSchema;
1314
- /** Optional display name reported through scan metadata. */
1315
- name;
1316
- /** Human-readable description reported through scan metadata. */
1317
- description;
1318
- /** Stable id used to isolate this adapter's manager subscriptions. */
1319
- instanceId = nextFederatedSourceId++;
1320
- /** Monotonic id used to isolate overlapping operations on this adapter. */
1321
- nextOperationId = 0;
1322
- /** Creates an ordered federated source backed by one shared DataSourceManager. */
1323
- constructor(dataSourceManager, options) {
1324
- if (!options.sources.length) {
1325
- throw new Error("Federated scans require at least one source.");
1326
- }
1327
- if (options.schemaPolicy && options.schemaPolicy !== "strict" && options.schemaPolicy !== "union") {
1328
- throw new Error(`Unsupported federated schema policy: ${options.schemaPolicy}`);
1329
- }
1330
- this.dataSourceManager = dataSourceManager;
1331
- this.sources = Object.freeze(options.sources.map(cloneSourceEntry));
1332
- this.schemaPolicy = options.schemaPolicy || "strict";
1333
- this.outputSchema = options.outputSchema ? cloneSchema(options.outputSchema) : void 0;
1334
- this.name = options.name;
1335
- this.description = options.description || `${this.sources.length} ordered table sources`;
1336
- }
1337
- /** Discovers and reconciles every child schema without reading federated result batches. */
1338
- async getQueryMetadata(options = {}) {
1339
- const consumerId = this.createConsumerId("metadata");
1340
- try {
1341
- const plan = await this.resolvePlan(consumerId, options.signal);
1342
- return createScanQueryMetadata({
1343
- sourceType: "federated-table",
1344
- queryType: "table",
1345
- execution: { status: "supported", method: "read" },
1346
- name: this.name,
1347
- description: this.description,
1348
- schema: plan.schema,
1349
- capabilities: { table: FEDERATED_TABLE_QUERY_CAPABILITIES },
1350
- statistics: getFederatedStatistics(plan.sources),
1351
- hasDefaultRowWindow: plan.sources.some(({ metadata }) => metadata.hasDefaultRowWindow)
1352
- });
1353
- } finally {
1354
- this.dataSourceManager.unsubscribe({ consumerId });
1355
- }
1356
- }
1357
- /** Explains source resolution, schema reconciliation, and the global table query. */
1358
- async explain(options = {}) {
1359
- const consumerId = this.createConsumerId("explain");
1360
- try {
1361
- const plan = await this.resolvePlan(consumerId, options.signal);
1362
- const explanation = explainTableQuery(plan.schema.fields.map((field) => field.name), options, FEDERATED_TABLE_QUERY_CAPABILITIES);
1363
- return Object.freeze({
1364
- ...explanation,
1365
- schemaPolicy: this.schemaPolicy,
1366
- sources: Object.freeze(plan.sources.map((source) => createSourceExplanation(source, plan.schema)))
1367
- });
1368
- } finally {
1369
- this.dataSourceManager.unsubscribe({ consumerId });
1370
- }
1371
- }
1372
- /**
1373
- * Emits source and batch ordered Arrow results with one global limit and batch provenance.
1374
- *
1375
- * Returning early from the iterator closes the active child iterator and releases every manager
1376
- * subscription. Later sources are never read once the global limit has been satisfied.
1377
- */
1378
- async *read(options = {}) {
1379
- var _a, _b;
1380
- const consumerId = this.createConsumerId("read");
1381
- const startedAt = Date.now();
1382
- const telemetry = {
1383
- status: "early-terminated",
1384
- sourcesPlanned: this.sources.length,
1385
- sourcesRead: 0,
1386
- batchesRead: 0,
1387
- rowsRead: 0,
1388
- rowsTested: 0,
1389
- rowsRetained: 0,
1390
- rowsReturned: 0,
1391
- bytesFetched: 0,
1392
- filesOpened: 0,
1393
- tasksOpened: 0,
1394
- rowsPruned: 0,
1395
- durationMilliseconds: 0,
1396
- sources: []
1397
- };
1398
- try {
1399
- const plan = await this.resolvePlan(consumerId, options.signal);
1400
- const scanStep = planTableQuery(plan.schema.fields.map((field) => field.name), options)[0];
1401
- let remaining = options.limit ?? Number.POSITIVE_INFINITY;
1402
- if (remaining <= 0) {
1403
- telemetry.earlyTerminationReason = "limit";
1404
- return;
1405
- }
1406
- for (const resolvedSource of plan.sources) {
1407
- throwIfAborted2(options.signal);
1408
- if (remaining <= 0) {
1409
- telemetry.earlyTerminationReason = "limit";
1410
- return;
1411
- }
1412
- const sourceStartedAt = Date.now();
1413
- let childTelemetry;
1414
- let sourceCompleted = false;
1415
- let sourceError;
1416
- let sourceBatchesDecoded = 0;
1417
- let sourceRowsRead = 0;
1418
- let sourceRowsTested = 0;
1419
- let sourceRowsRetained = 0;
1420
- let sourceRowsReturned = 0;
1421
- const sourceReadOptions = createSourceReadOptions(resolvedSource, scanStep.columns, remaining, options, (value) => {
1422
- childTelemetry = value;
1423
- });
1424
- const sourceResidualPredicate = getSourceResidualPredicate(resolvedSource);
1425
- let sourceRemaining = ((_a = resolvedSource.entry.query) == null ? void 0 : _a.limit) ?? Number.POSITIVE_INFINITY;
1426
- telemetry.sourcesRead++;
1427
- let sourceBatchIndex = 0;
1428
- try {
1429
- for await (const input of resolvedSource.source.read(sourceReadOptions)) {
1430
- const native = !("shape" in input);
1431
- const batchLength = native ? input.numRows : input.length;
1432
- throwIfAborted2(options.signal);
1433
- if (remaining <= 0) {
1434
- telemetry.earlyTerminationReason = "limit";
1435
- return;
1436
- }
1437
- if (sourceRemaining <= 0)
1438
- break;
1439
- if (!native && input.batchType !== "data")
1440
- continue;
1441
- telemetry.batchesRead++;
1442
- telemetry.rowsRead += batchLength;
1443
- sourceBatchesDecoded++;
1444
- sourceRowsRead += batchLength;
1445
- if (batchLength <= 0)
1446
- continue;
1447
- const physicalTable = native ? new arrow5.Table(input.schema, [input]) : convertTableToArrow2(input.schema ? input : { ...input, schema: resolvedSource.metadata.schema });
1448
- const sourceResult = queryArrowTable(physicalTable, {
1449
- predicate: sourceResidualPredicate,
1450
- limit: Number.isFinite(sourceRemaining) ? sourceRemaining : void 0,
1451
- signal: options.signal
1452
- });
1453
- if (sourceResidualPredicate) {
1454
- sourceRowsTested += physicalTable.numRows;
1455
- sourceRowsRetained += sourceResult.numRows;
1456
- }
1457
- sourceRemaining -= sourceResult.numRows;
1458
- const currentSourceBatchIndex = sourceBatchIndex++;
1459
- if (!sourceResult.numRows)
1460
- continue;
1461
- const canonicalTable = createCanonicalArrowTable(plan.schema, resolvedSource, sourceResult);
1462
- const result = queryArrowTable(canonicalTable, {
1463
- predicate: options.predicate,
1464
- columns: options.columns,
1465
- limit: Number.isFinite(remaining) ? remaining : void 0,
1466
- signal: options.signal
1467
- });
1468
- if (options.predicate) {
1469
- telemetry.rowsTested += canonicalTable.numRows;
1470
- telemetry.rowsRetained += result.numRows;
1471
- }
1472
- const resultLength = result.numRows;
1473
- if (!resultLength)
1474
- continue;
1475
- const provenance = Object.freeze({
1476
- sourceId: resolvedSource.entry.dataSourceId,
1477
- sourceIndex: resolvedSource.sourceIndex,
1478
- sourceBatchIndex: currentSourceBatchIndex,
1479
- sourceMetadata: native ? Object.fromEntries(input.metadata) : input.metadata
1480
- });
1481
- telemetry.rowsReturned += resultLength;
1482
- sourceRowsReturned += resultLength;
1483
- for (const recordBatch of result.batches) {
1484
- const metadata = new Map(native && resultLength === batchLength ? input.metadata : void 0);
1485
- metadata.set("loaders.gl.federation", JSON.stringify(provenance));
1486
- yield new arrow5.RecordBatch(recordBatch.schema, recordBatch.data, metadata);
1487
- }
1488
- remaining -= resultLength;
1489
- }
1490
- sourceCompleted = true;
1491
- } catch (error) {
1492
- sourceError = error;
1493
- throw error;
1494
- } finally {
1495
- const sourceTelemetry = createSourceTelemetry({
1496
- resolvedSource,
1497
- childTelemetry,
1498
- sourceStartedAt,
1499
- sourceCompleted,
1500
- sourceError,
1501
- signal: options.signal,
1502
- batchesDecoded: sourceBatchesDecoded,
1503
- rowsRead: sourceRowsRead,
1504
- rowsTested: sourceRowsTested,
1505
- rowsRetained: sourceRowsRetained,
1506
- rowsReturned: sourceRowsReturned
1507
- });
1508
- telemetry.sources.push(sourceTelemetry);
1509
- telemetry.bytesFetched += sourceTelemetry.bytesFetched || 0;
1510
- telemetry.filesOpened += sourceTelemetry.filesOpened || 0;
1511
- telemetry.tasksOpened += sourceTelemetry.tasksOpened || 0;
1512
- telemetry.rowsPruned += sourceTelemetry.rowsPruned || 0;
1513
- }
1514
- }
1515
- telemetry.status = "completed";
1516
- } catch (error) {
1517
- telemetry.status = ((_b = options.signal) == null ? void 0 : _b.aborted) ? "cancelled" : "failed";
1518
- telemetry.error = error;
1519
- throw error;
1520
- } finally {
1521
- this.dataSourceManager.unsubscribe({ consumerId });
1522
- telemetry.durationMilliseconds = Date.now() - startedAt;
1523
- if (telemetry.status === "early-terminated" && !telemetry.earlyTerminationReason) {
1524
- telemetry.earlyTerminationReason = "consumer-return";
1525
- }
1526
- emitQueryComplete(options.onQueryComplete, Object.freeze({
1527
- ...telemetry,
1528
- batchesDecoded: telemetry.batchesRead,
1529
- sources: Object.freeze([...telemetry.sources])
1530
- }));
1531
- }
1532
- }
1533
- /** Resolves managed sources, discovers their schemas, and creates one compatibility plan. */
1534
- async resolvePlan(consumerId, signal) {
1535
- const sources = [];
1536
- for (let sourceIndex = 0; sourceIndex < this.sources.length; sourceIndex++) {
1537
- throwIfAborted2(signal);
1538
- const entry = this.sources[sourceIndex];
1539
- const source = await resolveManagedSource(this.dataSourceManager, entry.dataSourceId, consumerId, String(sourceIndex), signal);
1540
- if (typeof source.getQueryMetadata !== "function" || typeof source.read !== "function") {
1541
- throw new Error(`Managed source does not implement TableScanSource: ${entry.dataSourceId}`);
1542
- }
1543
- const metadata = await source.getQueryMetadata({ signal });
1544
- if (metadata.execution.status !== "supported" || metadata.execution.method !== "read") {
1545
- throw new Error(`Source does not support read(): ${entry.dataSourceId}`);
1546
- }
1547
- if (metadata.queryType !== "table") {
1548
- throw new Error(`Federated source is not a table source: ${entry.dataSourceId}`);
1549
- }
1550
- const fields = resolveMappedFields(entry, metadata);
1551
- sources.push({
1552
- entry,
1553
- source,
1554
- metadata,
1555
- sourceIndex,
1556
- fields,
1557
- sourceNameByOutputName: new Map(fields.map((field) => [field.outputName, field.sourceName]))
1558
- });
1559
- }
1560
- return Object.freeze({
1561
- schema: reconcileSchemas(sources, this.schemaPolicy, this.outputSchema),
1562
- sources: Object.freeze(sources)
1563
- });
1564
- }
1565
- /** Returns a collision-free manager consumer id for one operation. */
1566
- createConsumerId(operation) {
1567
- return `federated-table:${this.instanceId}:${operation}:${this.nextOperationId++}`;
1568
- }
1569
- };
1570
- function cloneSourceEntry(entry) {
1571
- if (!entry.dataSourceId) {
1572
- throw new Error("Federated table source ids must be non-empty.");
1573
- }
1574
- return Object.freeze({
1575
- dataSourceId: entry.dataSourceId,
1576
- query: entry.query ? Object.freeze({
1577
- ...entry.query,
1578
- columns: entry.query.columns ? Object.freeze([...entry.query.columns]) : void 0
1579
- }) : void 0,
1580
- columnMapping: entry.columnMapping ? Object.freeze({ ...entry.columnMapping }) : void 0
1581
- });
1582
- }
1583
- function resolveMappedFields(entry, metadata) {
1584
- var _a;
1585
- const sourceFields = new Map(metadata.schema.fields.map((field) => [field.name, field]));
1586
- for (const sourceName of Object.keys(entry.columnMapping || {})) {
1587
- if (!sourceFields.has(sourceName)) {
1588
- throw new Error(`Federated column mapping source not found in ${entry.dataSourceId}: ${sourceName}`);
1589
- }
1590
- }
1591
- const selectedNames = ((_a = entry.query) == null ? void 0 : _a.columns) || metadata.schema.fields.map((field) => field.name);
1592
- if (!selectedNames.length) {
1593
- throw new Error(`Federated source projection must not be empty: ${entry.dataSourceId}`);
1594
- }
1595
- const outputNames = /* @__PURE__ */ new Set();
1596
- return Object.freeze(selectedNames.map((sourceName) => {
1597
- var _a2;
1598
- const field = sourceFields.get(sourceName);
1599
- if (!field) {
1600
- throw new Error(`Federated source column not found in ${entry.dataSourceId}: ${sourceName}`);
1601
- }
1602
- const outputName = ((_a2 = entry.columnMapping) == null ? void 0 : _a2[sourceName]) ?? sourceName;
1603
- if (!outputName) {
1604
- throw new Error(`Federated output column names must be non-empty: ${sourceName}`);
1605
- }
1606
- if (outputNames.has(outputName)) {
1607
- throw new Error(`Federated column mapping creates duplicate output column in ${entry.dataSourceId}: ${outputName}`);
1608
- }
1609
- outputNames.add(outputName);
1610
- return Object.freeze({ sourceName, outputName, field });
1611
- }));
1612
- }
1613
- function reconcileSchemas(sources, schemaPolicy, outputSchema) {
1614
- const outputFields = /* @__PURE__ */ new Map();
1615
- const firstSourceNames = sources[0].fields.map((field) => field.outputName);
1616
- for (const source of sources) {
1617
- const sourceNames = new Set(source.fields.map((field) => field.outputName));
1618
- if (schemaPolicy === "strict") {
1619
- const missing = firstSourceNames.filter((name) => !sourceNames.has(name));
1620
- const extra = source.fields.map((field) => field.outputName).filter((name) => !firstSourceNames.includes(name));
1621
- if (missing.length || extra.length) {
1622
- throw new Error(`Federated strict schema mismatch for ${source.entry.dataSourceId}: missing [${missing.join(", ")}], extra [${extra.join(", ")}]`);
1623
- }
1624
- }
1625
- for (const mappedField of source.fields) {
1626
- const current = outputFields.get(mappedField.outputName);
1627
- if (current) {
1628
- if (!outputSchema && !areDataTypesEqual(current.type, mappedField.field.type)) {
1629
- throw new Error(`Federated column type mismatch for ${mappedField.outputName}: ${formatDataType(current.type)} versus ${formatDataType(mappedField.field.type)} in ${source.entry.dataSourceId}`);
1630
- }
1631
- current.nullable = Boolean(current.nullable || mappedField.field.nullable);
1632
- current.presentCount++;
1633
- } else {
1634
- outputFields.set(mappedField.outputName, {
1635
- ...mappedField.field,
1636
- name: mappedField.outputName,
1637
- metadata: mappedField.field.metadata ? { ...mappedField.field.metadata } : void 0,
1638
- presentCount: 1
1639
- });
1640
- }
1641
- }
1642
- }
1643
- const fields = [...outputFields.values()].map(({ presentCount, ...field }) => ({
1644
- ...field,
1645
- nullable: Boolean(field.nullable || presentCount < sources.length)
1646
- }));
1647
- const inferredSchema = { fields, metadata: {} };
1648
- return outputSchema ? validateAndCloneOutputSchema(outputSchema, sources, inferredSchema, schemaPolicy) : inferredSchema;
1649
- }
1650
- function validateAndCloneOutputSchema(outputSchema, sources, inferredSchema, schemaPolicy) {
1651
- const outputFields = /* @__PURE__ */ new Map();
1652
- for (const field of outputSchema.fields) {
1653
- if (!field.name || outputFields.has(field.name)) {
1654
- throw new Error(`Federated output schema contains an invalid or duplicate field: ${field.name}`);
1655
- }
1656
- outputFields.set(field.name, field);
1657
- }
1658
- const inferredNames = new Set(inferredSchema.fields.map((field) => field.name));
1659
- const missingFromContract = [...inferredNames].filter((name) => !outputFields.has(name));
1660
- const absentFromSources = outputSchema.fields.map((field) => field.name).filter((name) => !inferredNames.has(name));
1661
- if (missingFromContract.length || schemaPolicy === "strict" && absentFromSources.length) {
1662
- throw new Error(`Federated output schema mismatch: missing [${missingFromContract.join(", ")}], absent [${absentFromSources.join(", ")}]`);
1663
- }
1664
- for (const outputField of outputSchema.fields) {
1665
- const presentFields = sources.flatMap((source) => source.fields.filter((field) => field.outputName === outputField.name).map((field) => ({ sourceId: source.entry.dataSourceId, field: field.field })));
1666
- if (!presentFields.length) {
1667
- if (!outputField.nullable) {
1668
- throw new Error(`Federated output field is absent from every source and must be nullable: ${outputField.name}`);
1669
- }
1670
- continue;
1671
- }
1672
- for (const presentField of presentFields) {
1673
- if (presentField.field.nullable && !outputField.nullable) {
1674
- throw new Error(`Federated output field cannot remove nullability for ${outputField.name} in ${presentField.sourceId}`);
1675
- }
1676
- if (!isLosslessDataTypeCast(presentField.field.type, outputField.type)) {
1677
- throw new Error(`Unsupported federated normalization for ${outputField.name}: ${formatDataType(presentField.field.type)} to ${formatDataType(outputField.type)} in ${presentField.sourceId}`);
1678
- }
1679
- }
1680
- if (presentFields.length < sources.length && !outputField.nullable) {
1681
- throw new Error(`Federated union field must be nullable when absent from a source: ${outputField.name}`);
1682
- }
1683
- }
1684
- return cloneSchema(outputSchema);
1685
- }
1686
- function createSourceReadOptions(source, requiredOutputColumns, remaining, options, onQueryComplete) {
1687
- var _a, _b;
1688
- const sourceResidualPredicate = getSourceResidualPredicate(source);
1689
- const requiredSourceColumns = requiredOutputColumns.map((outputName) => source.sourceNameByOutputName.get(outputName)).filter((sourceName) => Boolean(sourceName));
1690
- if (sourceResidualPredicate) {
1691
- requiredSourceColumns.push(...(0, import_columnar_predicate2.getColumnarPredicateColumns)(sourceResidualPredicate));
1692
- }
1693
- if (!requiredSourceColumns.length) {
1694
- requiredSourceColumns.push(source.fields[0].sourceName);
1695
- }
1696
- const sourceLimit = (_a = source.entry.query) == null ? void 0 : _a.limit;
1697
- const globalLimitCanBePushed = options.predicate === void 0 && Number.isFinite(remaining);
1698
- const limit = globalLimitCanBePushed ? Math.min(sourceLimit ?? Number.POSITIVE_INFINITY, remaining) : sourceLimit;
1699
- return {
1700
- ...source.entry.query,
1701
- columns: Object.freeze([...new Set(requiredSourceColumns)]),
1702
- predicate: sourceResidualPredicate ? void 0 : (_b = source.entry.query) == null ? void 0 : _b.predicate,
1703
- limit: sourceResidualPredicate ? void 0 : Number.isFinite(limit) ? limit : void 0,
1704
- signal: options.signal,
1705
- onQueryComplete
1706
- };
1707
- }
1708
- function getSourceResidualPredicate(source) {
1709
- var _a, _b;
1710
- return ((_a = source.metadata.capabilities.table) == null ? void 0 : _a.predicate) === "unsupported" ? (_b = source.entry.query) == null ? void 0 : _b.predicate : void 0;
1711
- }
1712
- function createCanonicalArrowTable(schema, source, physicalTable) {
1713
- const arrowSchema = convertSchemaToArrow(schema);
1714
- const columns = {};
1715
- for (const field of arrowSchema.fields) {
1716
- const sourceName = source.sourceNameByOutputName.get(field.name);
1717
- const vector = sourceName ? physicalTable.getChild(sourceName) : null;
1718
- const mappedField = source.fields.find((sourceField) => sourceField.outputName === field.name);
1719
- columns[field.name] = vector ? mappedField && !areDataTypesEqual(mappedField.field.type, schema.fields.find((schemaField) => schemaField.name === field.name).type) ? arrow5.vectorFromArray(Array.from(vector), field.type) : vector : arrow5.vectorFromArray(Array.from({ length: physicalTable.numRows }, () => null), field.type);
1720
- }
1721
- return new arrow5.Table(arrowSchema, columns);
1722
- }
1723
- function createSourceTelemetry(options) {
1724
- var _a;
1725
- const { resolvedSource, childTelemetry } = options;
1726
- const status = (childTelemetry == null ? void 0 : childTelemetry.status) || (((_a = options.signal) == null ? void 0 : _a.aborted) ? "cancelled" : options.sourceError ? "failed" : options.sourceCompleted ? "completed" : "early-terminated");
1727
- const details = childTelemetry ? Object.freeze(Object.fromEntries(Object.entries(childTelemetry).filter(([key]) => ![
1728
- "status",
1729
- "sourcesPlanned",
1730
- "sourcesRead",
1731
- "batchesRead",
1732
- "batchesDecoded",
1733
- "rowsRead",
1734
- "rowsTested",
1735
- "rowsRetained",
1736
- "rowsReturned",
1737
- "bytesRead",
1738
- "bytesFetched",
1739
- "filesOpened",
1740
- "tasksOpened",
1741
- "rowsPruned",
1742
- "durationMilliseconds",
1743
- "sources",
1744
- "details",
1745
- "error"
1746
- ].includes(key)))) : void 0;
1747
- return Object.freeze({
1748
- sourceId: resolvedSource.entry.dataSourceId,
1749
- sourceType: resolvedSource.metadata.sourceType,
1750
- sourceIndex: resolvedSource.sourceIndex,
1751
- status,
1752
- filesOpened: childTelemetry == null ? void 0 : childTelemetry.filesOpened,
1753
- tasksOpened: childTelemetry == null ? void 0 : childTelemetry.tasksOpened,
1754
- bytesFetched: (childTelemetry == null ? void 0 : childTelemetry.bytesFetched) ?? (childTelemetry == null ? void 0 : childTelemetry.bytesRead),
1755
- batchesDecoded: (childTelemetry == null ? void 0 : childTelemetry.batchesDecoded) ?? options.batchesDecoded,
1756
- rowsRead: (childTelemetry == null ? void 0 : childTelemetry.rowsRead) ?? options.rowsRead,
1757
- rowsTested: (childTelemetry == null ? void 0 : childTelemetry.rowsTested) || options.rowsTested || void 0,
1758
- rowsRetained: (childTelemetry == null ? void 0 : childTelemetry.rowsRetained) || options.rowsRetained || void 0,
1759
- rowsReturned: options.rowsReturned,
1760
- rowsPruned: childTelemetry == null ? void 0 : childTelemetry.rowsPruned,
1761
- durationMilliseconds: Date.now() - options.sourceStartedAt,
1762
- details: (childTelemetry == null ? void 0 : childTelemetry.details) ?? (details && Object.keys(details).length ? details : void 0),
1763
- error: (childTelemetry == null ? void 0 : childTelemetry.error) ?? options.sourceError
1764
- });
1765
- }
1766
- function getFederatedStatistics(sources) {
1767
- if (sources.some((source) => {
1768
- var _a, _b, _c;
1769
- return ((_a = source.entry.query) == null ? void 0 : _a.predicate) || ((_b = source.entry.query) == null ? void 0 : _b.limit) !== void 0 || ((_c = source.metadata.statistics) == null ? void 0 : _c.rowCount) === void 0;
1770
- })) {
1771
- return void 0;
1772
- }
1773
- const counts = sources.map((source) => source.metadata.statistics.rowCount);
1774
- return {
1775
- rowCount: counts.some((count) => typeof count === "bigint") ? counts.reduce((sum, count) => sum + BigInt(count), 0n) : counts.reduce((sum, count) => sum + Number(count), 0)
1776
- };
1777
- }
1778
- function createSourceExplanation(source, outputSchema) {
1779
- const normalizedTypes = Object.fromEntries(source.fields.filter((field) => {
1780
- const outputField = outputSchema.fields.find((schemaField) => schemaField.name === field.outputName);
1781
- return outputField && !areDataTypesEqual(outputField.type, field.field.type);
1782
- }).map((field) => [
1783
- field.outputName,
1784
- outputSchema.fields.find((schemaField) => schemaField.name === field.outputName).type
1785
- ]));
1786
- return Object.freeze({
1787
- sourceId: source.entry.dataSourceId,
1788
- sourceIndex: source.sourceIndex,
1789
- sourceType: source.metadata.sourceType,
1790
- sourceColumns: Object.freeze(source.fields.map((field) => field.sourceName)),
1791
- outputColumns: Object.freeze(source.fields.map((field) => field.outputName)),
1792
- columnMapping: Object.freeze({ ...source.entry.columnMapping }),
1793
- normalizedTypes: Object.freeze(normalizedTypes)
1794
- });
1795
- }
1796
- function isLosslessDataTypeCast(sourceType, outputType) {
1797
- if (areDataTypesEqual(sourceType, outputType) || sourceType === "null")
1798
- return true;
1799
- if (typeof sourceType === "object" && sourceType.type === "dictionary") {
1800
- return isLosslessDataTypeCast(sourceType.dictionary, outputType);
1801
- }
1802
- if (sourceType === "utf8-view" && outputType === "utf8")
1803
- return true;
1804
- if (sourceType === "binary-view" && outputType === "binary")
1805
- return true;
1806
- const sourceInteger = getIntegerType(sourceType);
1807
- const outputInteger = getIntegerType(outputType);
1808
- if (sourceInteger && outputInteger) {
1809
- return sourceInteger.signed === outputInteger.signed && sourceInteger.bits <= outputInteger.bits || !sourceInteger.signed && outputInteger.signed && sourceInteger.bits < outputInteger.bits;
1810
- }
1811
- const sourceFloatBits = getFloatBits(sourceType);
1812
- const outputFloatBits = getFloatBits(outputType);
1813
- if (sourceFloatBits && outputFloatBits)
1814
- return sourceFloatBits <= outputFloatBits;
1815
- return Boolean(sourceInteger && sourceInteger.bits <= 32 && outputFloatBits === 64);
1816
- }
1817
- function getIntegerType(dataType) {
1818
- const types = {
1819
- int: { signed: true, bits: 32 },
1820
- int8: { signed: true, bits: 8 },
1821
- int16: { signed: true, bits: 16 },
1822
- int32: { signed: true, bits: 32 },
1823
- int64: { signed: true, bits: 64 },
1824
- uint8: { signed: false, bits: 8 },
1825
- uint16: { signed: false, bits: 16 },
1826
- uint32: { signed: false, bits: 32 },
1827
- uint64: { signed: false, bits: 64 }
1828
- };
1829
- return typeof dataType === "string" ? types[dataType] || null : null;
1830
- }
1831
- function getFloatBits(dataType) {
1832
- const types = { float: 32, float16: 16, float32: 32, float64: 64 };
1833
- return typeof dataType === "string" ? types[dataType] || null : null;
1834
- }
1835
- function cloneSchema(schema) {
1836
- return convertArrowToSchema(convertSchemaToArrow(schema));
1837
- }
1838
- function areDataTypesEqual(left, right) {
1839
- return formatDataType(left) === formatDataType(right);
1840
- }
1841
- function formatDataType(dataType) {
1842
- return typeof dataType === "string" ? dataType : JSON.stringify(canonicalizeValue(dataType));
1843
- }
1844
- function canonicalizeValue(value) {
1845
- if (ArrayBuffer.isView(value)) {
1846
- return Array.from(value);
1847
- }
1848
- if (Array.isArray(value)) {
1849
- return value.map(canonicalizeValue);
1850
- }
1851
- if (value && typeof value === "object") {
1852
- return Object.fromEntries(Object.entries(value).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)).map(([key, child]) => [key, canonicalizeValue(child)]));
1853
- }
1854
- return value;
1855
- }
1856
- function resolveManagedSource(dataSourceManager, dataSourceId, consumerId, requestId, signal) {
1857
- let resolveDeferredSource;
1858
- let rejectDeferredSource;
1859
- const deferredSource = new Promise((resolve, reject) => {
1860
- resolveDeferredSource = resolve;
1861
- rejectDeferredSource = reject;
1862
- });
1863
- let sourceGeneration = 0;
1864
- const acceptSource = (source) => {
1865
- const generation = ++sourceGeneration;
1866
- if (source) {
1867
- void Promise.resolve(source).then((result) => {
1868
- if (generation === sourceGeneration)
1869
- resolveDeferredSource(result);
1870
- }, (error) => {
1871
- if (generation === sourceGeneration)
1872
- rejectDeferredSource(error);
1873
- });
1874
- }
1875
- };
1876
- const managedSource = dataSourceManager.subscribe({
1877
- dataSourceId,
1878
- consumerId,
1879
- requestId,
1880
- onChange: acceptSource
1881
- });
1882
- if (managedSource === void 0) {
1883
- throw new Error(`Federated table source is not registered: ${dataSourceId}`);
1884
- }
1885
- acceptSource(managedSource || null);
1886
- return waitForPromise(deferredSource, signal);
1887
- }
1888
- async function waitForPromise(promise, signal) {
1889
- if (!signal)
1890
- return await promise;
1891
- throwIfAborted2(signal);
1892
- return await new Promise((resolve, reject) => {
1893
- const abort = () => reject(getAbortReason(signal));
1894
- signal.addEventListener("abort", abort, { once: true });
1895
- void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
1896
- });
1897
- }
1898
- function throwIfAborted2(signal) {
1899
- if (signal == null ? void 0 : signal.aborted)
1900
- throw getAbortReason(signal);
1901
- }
1902
- function getAbortReason(signal) {
1903
- return signal.reason || new DOMException("Request aborted", "AbortError");
1904
- }
1905
- //# sourceMappingURL=federated-table-scan-source.cjs.map