@math.gl/geospatial 5.0.1 → 5.0.3

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 (88) hide show
  1. package/dist/coverage-simplification.d.ts +9 -0
  2. package/dist/coverage-simplification.d.ts.map +1 -0
  3. package/dist/coverage-simplification.js +167 -0
  4. package/dist/coverage-simplification.js.map +1 -0
  5. package/dist/line-network/build-line-network.d.ts +100 -0
  6. package/dist/line-network/build-line-network.d.ts.map +1 -0
  7. package/dist/line-network/build-line-network.js +766 -0
  8. package/dist/line-network/build-line-network.js.map +1 -0
  9. package/dist/line-network/line-network-routes.d.ts +53 -0
  10. package/dist/line-network/line-network-routes.d.ts.map +1 -0
  11. package/dist/line-network/line-network-routes.js +146 -0
  12. package/dist/line-network/line-network-routes.js.map +1 -0
  13. package/dist/line-network/line-network-weights.d.ts +11 -0
  14. package/dist/line-network/line-network-weights.d.ts.map +1 -0
  15. package/dist/line-network/line-network-weights.js +25 -0
  16. package/dist/line-network/line-network-weights.js.map +1 -0
  17. package/dist/line-network.cjs +850 -0
  18. package/dist/line-network.cjs.map +6 -0
  19. package/dist/line-network.d.ts +7 -0
  20. package/dist/line-network.d.ts.map +1 -0
  21. package/dist/line-network.js +7 -0
  22. package/dist/line-network.js.map +1 -0
  23. package/dist/linear-referencing.d.ts +2 -12
  24. package/dist/linear-referencing.d.ts.map +1 -1
  25. package/dist/linear-referencing.js +17 -49
  26. package/dist/linear-referencing.js.map +1 -1
  27. package/dist/polygon-simplification.d.ts.map +1 -1
  28. package/dist/polygon-simplification.js +3 -33
  29. package/dist/polygon-simplification.js.map +1 -1
  30. package/dist/route-editing.d.ts +10 -0
  31. package/dist/route-editing.d.ts.map +1 -0
  32. package/dist/route-editing.js +58 -0
  33. package/dist/route-editing.js.map +1 -0
  34. package/dist/spatial-line-polygon-intersection.d.ts.map +1 -1
  35. package/dist/spatial-line-polygon-intersection.js +2 -2
  36. package/dist/spatial-line-polygon-intersection.js.map +1 -1
  37. package/dist/spatial-planar-intersects.d.ts +1 -11
  38. package/dist/spatial-planar-intersects.d.ts.map +1 -1
  39. package/dist/spatial-planar-intersects.js +2 -42
  40. package/dist/spatial-planar-intersects.js.map +1 -1
  41. package/dist/spatial-sql.d.ts +6 -4
  42. package/dist/spatial-sql.d.ts.map +1 -1
  43. package/dist/spatial-sql.js +38 -4
  44. package/dist/spatial-sql.js.map +1 -1
  45. package/dist/spatial-touches.d.ts +0 -2
  46. package/dist/spatial-touches.d.ts.map +1 -1
  47. package/dist/spatial-touches.js +1 -15
  48. package/dist/spatial-touches.js.map +1 -1
  49. package/dist/st-coverage-functions.d.ts +11 -0
  50. package/dist/st-coverage-functions.d.ts.map +1 -0
  51. package/dist/st-coverage-functions.js +57 -0
  52. package/dist/st-coverage-functions.js.map +1 -0
  53. package/dist/st-functions.cjs +1201 -775
  54. package/dist/st-functions.cjs.map +3 -3
  55. package/dist/st-functions.d.ts +36 -3
  56. package/dist/st-functions.d.ts.map +1 -1
  57. package/dist/st-functions.js +53 -19
  58. package/dist/st-functions.js.map +1 -1
  59. package/dist/st-geodesic-functions.d.ts +10 -2
  60. package/dist/st-geodesic-functions.d.ts.map +1 -1
  61. package/dist/st-geodesic-functions.js +179 -25
  62. package/dist/st-geodesic-functions.js.map +1 -1
  63. package/dist/st-hull-functions.cjs.map +1 -1
  64. package/dist/st-overlay-functions.cjs +114 -67
  65. package/dist/st-overlay-functions.cjs.map +2 -2
  66. package/dist/st-overlay-functions.d.ts +11 -1
  67. package/dist/st-overlay-functions.d.ts.map +1 -1
  68. package/dist/st-overlay-functions.js +74 -9
  69. package/dist/st-overlay-functions.js.map +1 -1
  70. package/dist/st-viewport-functions.cjs.map +1 -1
  71. package/dist/turf-functions.cjs.map +1 -1
  72. package/package.json +12 -6
  73. package/src/coverage-simplification.ts +215 -0
  74. package/src/line-network/build-line-network.ts +990 -0
  75. package/src/line-network/line-network-routes.ts +213 -0
  76. package/src/line-network/line-network-weights.ts +40 -0
  77. package/src/line-network.ts +29 -0
  78. package/src/linear-referencing.ts +23 -64
  79. package/src/polygon-simplification.ts +3 -42
  80. package/src/route-editing.ts +107 -0
  81. package/src/spatial-line-polygon-intersection.ts +7 -2
  82. package/src/spatial-planar-intersects.ts +7 -54
  83. package/src/spatial-sql.ts +54 -5
  84. package/src/spatial-touches.ts +1 -15
  85. package/src/st-coverage-functions.ts +88 -0
  86. package/src/st-functions.ts +70 -19
  87. package/src/st-geodesic-functions.ts +218 -26
  88. package/src/st-overlay-functions.ts +79 -10
@@ -10,9 +10,9 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __copyProps = (to, from, except, desc) => {
12
12
  if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ for (let key2 of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
15
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
16
16
  }
17
17
  return to;
18
18
  };
@@ -49,13 +49,17 @@ __export(st_functions_exports, {
49
49
  ST_GEODESICDISTANCE: () => ST_GEODESICDISTANCE,
50
50
  ST_GEODESICDWITHIN: () => ST_GEODESICDWITHIN,
51
51
  ST_GEODESICLENGTH: () => ST_GEODESICLENGTH,
52
+ ST_GEODESICSEGMENTIZE: () => ST_GEODESICSEGMENTIZE,
52
53
  ST_GEOMETRYN: () => ST_GEOMETRYN,
53
54
  ST_GEOMETRYTYPE: () => ST_GEOMETRYTYPE,
54
55
  ST_INTERSECTS: () => ST_INTERSECTS,
55
56
  ST_ISEMPTY: () => ST_ISEMPTY,
57
+ ST_ISVALID: () => ST_ISVALID,
58
+ ST_ISVALIDREASON: () => ST_ISVALIDREASON,
56
59
  ST_LENGTH: () => ST_LENGTH,
57
60
  ST_LINEINTERPOLATEPOINT: () => ST_LINEINTERPOLATEPOINT,
58
61
  ST_LINELOCATEPOINT: () => ST_LINELOCATEPOINT,
62
+ ST_LINEMERGE: () => ST_LINEMERGE,
59
63
  ST_LINESUBSTRING: () => ST_LINESUBSTRING,
60
64
  ST_LOCATEALONG: () => ST_LOCATEALONG,
61
65
  ST_LOCATEBETWEEN: () => ST_LOCATEBETWEEN,
@@ -68,6 +72,7 @@ __export(st_functions_exports, {
68
72
  ST_POINTN: () => ST_POINTN,
69
73
  ST_POINTONSURFACE: () => ST_POINTONSURFACE,
70
74
  ST_REMOVEREPEATEDPOINTS: () => ST_REMOVEREPEATEDPOINTS,
75
+ ST_SEGMENTIZE: () => ST_SEGMENTIZE,
71
76
  ST_SETSRID: () => ST_SETSRID,
72
77
  ST_SHORTESTLINE: () => ST_SHORTESTLINE,
73
78
  ST_SIMPLIFY: () => ST_SIMPLIFY,
@@ -81,14 +86,17 @@ __export(st_functions_exports, {
81
86
  ST_X: () => ST_X,
82
87
  ST_Y: () => ST_Y,
83
88
  ST_Z: () => ST_Z,
89
+ createSTCoverageSimplify: () => createSTCoverageSimplify,
84
90
  createSTTransform: () => createSTTransform
85
91
  });
86
92
  module.exports = __toCommonJS(st_functions_exports);
87
- var import_apache_arrow3 = require("apache-arrow");
88
- var import_arrow4 = require("@math.gl/core/arrow");
93
+ var import_apache_arrow4 = require("apache-arrow");
94
+ var import_arrow7 = require("@math.gl/core/arrow");
95
+ var import_polygon5 = require("@math.gl/geometry/polygon");
89
96
 
90
97
  // dist/spatial-planar-intersects.js
91
- var import_robust_predicates = require("robust-predicates");
98
+ var import_polygon = require("@math.gl/geometry/polygon");
99
+ var import_polygon2 = require("@math.gl/geometry/polygon");
92
100
 
93
101
  // dist/spatial-planar.js
94
102
  function distanceToPlanarSegment(p, a, b) {
@@ -234,13 +242,13 @@ function planarBounds(geometry) {
234
242
  return minX <= maxX ? [minX, minY, maxX, maxY] : null;
235
243
  }
236
244
  function planarEnvelope(geometry) {
237
- const bounds = planarBounds(geometry);
238
- if (!bounds)
245
+ const bounds2 = planarBounds(geometry);
246
+ if (!bounds2)
239
247
  return geometry;
240
- return envelopeFromBounds(bounds);
248
+ return envelopeFromBounds(bounds2);
241
249
  }
242
- function envelopeFromBounds(bounds) {
243
- const [x0, y0, x1, y1] = bounds;
250
+ function envelopeFromBounds(bounds2) {
251
+ const [x0, y0, x1, y1] = bounds2;
244
252
  if (x0 === x1 && y0 === y1)
245
253
  return { type: "Point", coordinates: [x0, y0] };
246
254
  if (x0 === x1 || y0 === y1) {
@@ -337,17 +345,6 @@ function* primitives(geometry) {
337
345
  yield geometry;
338
346
  }
339
347
  }
340
- function side(a, b, c) {
341
- return Math.sign((0, import_robust_predicates.orient2d)(a[0], a[1], b[0], b[1], c[0], c[1]));
342
- }
343
- function inBounds(p, a, b) {
344
- return p[0] >= Math.min(a[0], b[0]) && p[0] <= Math.max(a[0], b[0]) && p[1] >= Math.min(a[1], b[1]) && p[1] <= Math.max(a[1], b[1]);
345
- }
346
- function segmentsMeet(a, b, c, d) {
347
- const cSide = side(a, b, c), dSide = side(a, b, d);
348
- const aSide = side(c, d, a), bSide = side(c, d, b);
349
- return cSide * dSide < 0 && aSide * bSide < 0 || !cSide && inBounds(c, a, b) || !dSide && inBounds(d, a, b) || !aSide && inBounds(a, c, d) || !bSide && inBounds(b, c, d);
350
- }
351
348
  function anyEdge(path, closed, match) {
352
349
  for (let i = closed ? 0 : 1; i < path.length; i++) {
353
350
  if (match(path[i ? i - 1 : path.length - 1], path[i]))
@@ -355,32 +352,14 @@ function anyEdge(path, closed, match) {
355
352
  }
356
353
  return false;
357
354
  }
358
- function pointOnSegment(point2, a, b) {
359
- return inBounds(point2, a, b) && side(a, b, point2) === 0;
360
- }
361
- function locatePointInPolygon(point2, rings) {
362
- let inside = false;
363
- for (const ring of rings) {
364
- if (anyEdge(ring, true, (a, b) => {
365
- const orientation = side(a, b, point2);
366
- if (!orientation && inBounds(point2, a, b))
367
- return true;
368
- if (a[1] > point2[1] !== b[1] > point2[1] && orientation < 0 === b[1] > a[1])
369
- inside = !inside;
370
- return false;
371
- }))
372
- return 0;
373
- }
374
- return inside ? 1 : -1;
375
- }
376
355
  function meetsPoint(point2, geometry) {
377
356
  if (!Number.isFinite(point2[0]) || !Number.isFinite(point2[1]))
378
357
  return false;
379
358
  if (geometry.type === "Point")
380
359
  return point2[0] === geometry.coordinates[0] && point2[1] === geometry.coordinates[1];
381
360
  if (geometry.type === "LineString")
382
- return anyEdge(geometry.coordinates, false, (a, b) => pointOnSegment(point2, a, b));
383
- return locatePointInPolygon(point2, geometry.coordinates) >= 0;
361
+ return anyEdge(geometry.coordinates, false, (a, b) => (0, import_polygon.pointOnSegment)(point2, a, b));
362
+ return (0, import_polygon.locatePointInPolygon)(point2, geometry.coordinates) >= 0;
384
363
  }
385
364
  function primitivesMeet(a, b) {
386
365
  if (a.type === "Point")
@@ -392,7 +371,7 @@ function primitivesMeet(a, b) {
392
371
  for (const path of pathsA) {
393
372
  if (b.type === "Polygon" && path[0] && meetsPoint(path[0], b))
394
373
  return true;
395
- if (anyEdge(path, a.type === "Polygon", (p, q) => pathsB.some((other) => anyEdge(other, b.type === "Polygon", (r, s) => segmentsMeet(p, q, r, s)))))
374
+ if (anyEdge(path, a.type === "Polygon", (p, q) => pathsB.some((other) => anyEdge(other, b.type === "Polygon", (r, s) => (0, import_polygon.segmentsMeet)(p, q, r, s)))))
396
375
  return true;
397
376
  }
398
377
  return a.type === "Polygon" && pathsB.some((path) => Boolean(path[0] && meetsPoint(path[0], a)));
@@ -465,29 +444,16 @@ function lineBoundary(components) {
465
444
  if (!component.length)
466
445
  continue;
467
446
  for (const point2 of [component[0], component[component.length - 1]]) {
468
- const key = pointKey(point2);
469
- if (!boundary.delete(key))
470
- boundary.set(key, point2);
447
+ const key2 = pointKey(point2);
448
+ if (!boundary.delete(key2))
449
+ boundary.set(key2, point2);
471
450
  }
472
451
  }
473
452
  return boundary;
474
453
  }
475
- function endpointContacts(a, b) {
476
- const contacts = [];
477
- for (const [endpoints, other] of [
478
- [a, b],
479
- [b, a]
480
- ]) {
481
- for (const point2 of endpoints) {
482
- if (pointOnSegment(point2, ...other) && !contacts.some((value) => samePoint(value, point2)))
483
- contacts.push(point2);
484
- }
485
- }
486
- return contacts;
487
- }
488
454
  function hasBoundaryCrossing(boundary, a, b) {
489
455
  for (const point2 of boundary.values()) {
490
- if (pointOnSegment(point2, ...a) && pointOnSegment(point2, ...b))
456
+ if ((0, import_polygon2.pointOnSegment)(point2, ...a) && (0, import_polygon2.pointOnSegment)(point2, ...b))
491
457
  return true;
492
458
  }
493
459
  return false;
@@ -500,14 +466,14 @@ function lineInteriorsMeet(a, b) {
500
466
  const bEdges = [...edges(bPaths)];
501
467
  for (const left of edges(aPaths)) {
502
468
  for (const right of bEdges) {
503
- if (!segmentsMeet(...left, ...right))
469
+ if (!(0, import_polygon2.segmentsMeet)(...left, ...right))
504
470
  continue;
505
- const contacts = endpointContacts(left, right);
471
+ const contacts = (0, import_polygon2.endpointContacts)(left, right);
506
472
  if (contacts.length > 1)
507
473
  return true;
508
474
  if (contacts.length) {
509
- const key = pointKey(contacts[0]);
510
- if (!aBoundary.has(key) && !bBoundary.has(key))
475
+ const key2 = pointKey(contacts[0]);
476
+ if (!aBoundary.has(key2) && !bBoundary.has(key2))
511
477
  return true;
512
478
  } else if (!hasBoundaryCrossing(aBoundary, left, right) && !hasBoundaryCrossing(bBoundary, left, right)) {
513
479
  return true;
@@ -517,7 +483,7 @@ function lineInteriorsMeet(a, b) {
517
483
  return false;
518
484
  }
519
485
  function insideArea(point2, areas) {
520
- return areas.some((rings) => locatePointInPolygon(point2, rings) === 1);
486
+ return areas.some((rings) => (0, import_polygon2.locatePointInPolygon)(point2, rings) === 1);
521
487
  }
522
488
  function parameter(point2, [a, b]) {
523
489
  const dx = b[0] - a[0];
@@ -531,9 +497,9 @@ function segmentEntersArea(edge, boundaries, areas) {
531
497
  const cuts = /* @__PURE__ */ new Set([0, 1]);
532
498
  const coincident = [];
533
499
  for (const boundary of boundaries) {
534
- if (!segmentsMeet(...edge, ...boundary))
500
+ if (!(0, import_polygon2.segmentsMeet)(...edge, ...boundary))
535
501
  continue;
536
- const contacts = endpointContacts(edge, boundary).map((point2) => parameter(point2, edge));
502
+ const contacts = (0, import_polygon2.endpointContacts)(edge, boundary).map((point2) => parameter(point2, edge));
537
503
  if (!contacts.length)
538
504
  return true;
539
505
  for (const contact of contacts)
@@ -571,7 +537,7 @@ function pointsMeetInterior(points2, other) {
571
537
  const linePaths = paths(other);
572
538
  const boundary = lineBoundary(linePaths);
573
539
  const segments = [...edges(linePaths)];
574
- return positions.some((point2) => !boundary.has(pointKey(point2)) && segments.some((edge) => pointOnSegment(point2, ...edge)));
540
+ return positions.some((point2) => !boundary.has(pointKey(point2)) && segments.some((edge) => (0, import_polygon2.pointOnSegment)(point2, ...edge)));
575
541
  }
576
542
  function planarTouches(a, b) {
577
543
  if (!isPointLike(a) && !isLinear(a) && !isAreal(a) || !isPointLike(b) && !isLinear(b) && !isAreal(b))
@@ -600,8 +566,8 @@ function pointWithinPolygonDistance(point2, polygon, radius) {
600
566
  const [x, y] = point2.coordinates;
601
567
  if (!Number.isFinite(x) || !Number.isFinite(y))
602
568
  return false;
603
- const bounds = planarBounds(polygon);
604
- if (!bounds || !boxesWithin([x, y, x, y], bounds, radius))
569
+ const bounds2 = planarBounds(polygon);
570
+ if (!bounds2 || !boxesWithin([x, y, x, y], bounds2, radius))
605
571
  return false;
606
572
  if (planarIntersects(point2, polygon))
607
573
  return true;
@@ -621,9 +587,9 @@ function pointWithinPolygonDistance(point2, polygon, radius) {
621
587
  return false;
622
588
  }
623
589
  function lineSegments(geometry) {
624
- const paths2 = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
590
+ const paths3 = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
625
591
  const segments = [];
626
- for (const path of paths2) {
592
+ for (const path of paths3) {
627
593
  if (path.some((point2) => !Number.isFinite(point2[0]) || !Number.isFinite(point2[1])))
628
594
  throw new Error("ST_DWithin requires finite line coordinates");
629
595
  if (!path.length)
@@ -653,7 +619,7 @@ function segmentsWithin(left, right, radius) {
653
619
  return false;
654
620
  const { a, b } = left;
655
621
  const { a: c, b: d } = right;
656
- return segmentsMeet(a, b, c, d) || radius > 0 && (distanceToPlanarSegment(a, c, d) <= radius || distanceToPlanarSegment(b, c, d) <= radius || distanceToPlanarSegment(c, a, b) <= radius || distanceToPlanarSegment(d, a, b) <= radius);
622
+ return (0, import_polygon2.segmentsMeet)(a, b, c, d) || radius > 0 && (distanceToPlanarSegment(a, c, d) <= radius || distanceToPlanarSegment(b, c, d) <= radius || distanceToPlanarSegment(c, a, b) <= radius || distanceToPlanarSegment(d, a, b) <= radius);
657
623
  }
658
624
  function expandBound(value, radius, direction) {
659
625
  const padding = Math.max(Math.abs(value), radius) * Number.EPSILON;
@@ -671,206 +637,636 @@ function linesWithinDistance(left, right, radius) {
671
637
  if (radius === Infinity)
672
638
  return true;
673
639
  if (a.length * b.length <= directPairLimit || Math.min(a.length, b.length) < 8) {
674
- return a.some((segment) => b.some((candidate) => segmentsWithin(segment, candidate, radius)));
640
+ return a.some((segment) => b.some((candidate2) => segmentsWithin(segment, candidate2, radius)));
675
641
  }
676
642
  const [indexed, queries] = a.length <= b.length ? [a, b] : [b, a];
677
643
  const index = new import_spatial_index.BoxIndex({ dimension: 2, bounds: indexed.flatMap((segment) => segment.bounds) });
678
644
  for (const segment of queries) {
679
645
  const [x0, y0, x1, y1] = segment.bounds;
680
- const { result: result2 } = index.searchQuery([expandBound(x0, radius, -1), expandBound(y0, radius, -1)], [expandBound(x1, radius, 1), expandBound(y1, radius, 1)], { filter: (candidate) => segmentsWithin(segment, indexed[candidate], radius), maxResults: 1 });
646
+ const { result: result2 } = index.searchQuery([expandBound(x0, radius, -1), expandBound(y0, radius, -1)], [expandBound(x1, radius, 1), expandBound(y1, radius, 1)], { filter: (candidate2) => segmentsWithin(segment, indexed[candidate2], radius), maxResults: 1 });
681
647
  if (result2.length)
682
648
  return true;
683
649
  }
684
650
  return false;
685
651
  }
686
652
 
687
- // dist/linear-referencing.js
688
- var import_robust_predicates2 = require("robust-predicates");
689
- function cumulativeDistances(path) {
690
- const distances = [0];
691
- for (let i = 1; i < path.length; i++) {
692
- const a = path[i - 1], b = path[i];
693
- distances.push(distances[i - 1] + Math.hypot(b[0] - a[0], b[1] - a[1]));
694
- }
695
- return distances;
653
+ // dist/route-editing.js
654
+ var import_arrow5 = require("@math.gl/core/arrow");
655
+ var import_polygon3 = require("@math.gl/geometry/polygon");
656
+
657
+ // dist/spatial-line-intersection-result.js
658
+ var import_arrow = require("@math.gl/core/arrow");
659
+ var concrete = [
660
+ { type: "Point", encoding: "geoarrow.point", id: 1 },
661
+ { type: "LineString", encoding: "geoarrow.linestring", id: 2 },
662
+ { type: "MultiPoint", encoding: "geoarrow.multipoint", id: 4 },
663
+ { type: "MultiLineString", encoding: "geoarrow.multilinestring", id: 5 }
664
+ ];
665
+ function lineIntersectionResult() {
666
+ const build = (rows2) => (0, import_arrow.makeArrowVectorFromGeoArrowColumn)({
667
+ encoding: "geoarrow.geometry",
668
+ dimension: "xy",
669
+ coordinateLayout: "interleaved",
670
+ chunks: [union(rows2, true)]
671
+ });
672
+ return { encoding: "geoarrow.geometry", type: build([]).type, build };
696
673
  }
697
- function coordinateAt(path, distances, target) {
698
- for (let i = 0; i < path.length; i++) {
699
- if (target === distances[i])
700
- return path[i];
701
- if (target < distances[i]) {
702
- const t = (target - distances[i - 1]) / (distances[i] - distances[i - 1]);
703
- const a = path[i - 1], b = path[i];
704
- return [(1 - t) * a[0] + t * b[0], (1 - t) * a[1] + t * b[1]];
674
+ function union(rows2, collections) {
675
+ const groups = concrete.map(() => []);
676
+ const mixed = [];
677
+ const typeIds = new Int8Array(rows2.length);
678
+ const valueOffsets = new Int32Array(rows2.length);
679
+ for (let row = 0; row < rows2.length; row++) {
680
+ const geometry = rows2[row] ?? null;
681
+ if (collections && (geometry == null ? void 0 : geometry.type) === "GeometryCollection") {
682
+ typeIds[row] = 7;
683
+ valueOffsets[row] = mixed.length;
684
+ mixed.push(geometry);
685
+ } else {
686
+ const index = geometry ? concrete.findIndex((child) => child.type === geometry.type) : 0;
687
+ const group = groups[index];
688
+ if (!group)
689
+ throw new Error("Unexpected line intersection result geometry");
690
+ typeIds[row] = concrete[index].id;
691
+ valueOffsets[row] = group.length;
692
+ group.push(geometry);
705
693
  }
706
694
  }
707
- return path[path.length - 1];
708
- }
709
- function lineSubstring(line, start, end) {
710
- if (!(start >= 0 && end <= 1 && start <= end))
711
- throw new Error("Expected ordered route fractions in [0, 1]");
712
- if (line.type !== "LineString" || !line.coordinates.length)
713
- return null;
714
- const path = line.coordinates;
715
- const distances = cumulativeDistances(path);
716
- const total = distances[distances.length - 1];
717
- const from = start * total, to = end * total;
718
- const first = coordinateAt(path, distances, from);
719
- if (from === to)
720
- return { type: "Point", coordinates: first };
721
- const coordinates = [first];
722
- for (let i = 1; i < path.length - 1; i++) {
723
- if (distances[i] > from && distances[i] < to && distances[i] !== distances[i - 1])
724
- coordinates.push(path[i]);
695
+ const children = concrete.map(({ type, encoding, id }, index) => ({
696
+ name: type,
697
+ encoding,
698
+ typeId: id,
699
+ dimension: "xy",
700
+ coordinateLayout: "interleaved",
701
+ data: import_arrow.GeoArrowBuilder.build(groups[index], { encoding, dimension: "xy" }).chunks[0]
702
+ }));
703
+ if (collections) {
704
+ children.push({
705
+ name: "GeometryCollection",
706
+ encoding: "geoarrow.geometrycollection",
707
+ typeId: 7,
708
+ dimension: "xy",
709
+ coordinateLayout: "interleaved",
710
+ data: collection(mixed)
711
+ });
725
712
  }
726
- coordinates.push(coordinateAt(path, distances, to));
727
- return { type: "LineString", coordinates };
713
+ return { kind: "dense-union", length: rows2.length, typeIds, valueOffsets, children };
728
714
  }
729
- function projectPointToLine(line, point2) {
730
- if (line.type !== "LineString" || !line.coordinates.length || point2.type !== "Point" || !Number.isFinite(point2.coordinates[0]) || !Number.isFinite(point2.coordinates[1]))
731
- return null;
732
- const path = line.coordinates;
733
- const x = point2.coordinates[0];
734
- const y = point2.coordinates[1];
735
- let coordinate = path[0];
736
- let nearest = Math.hypot(x - coordinate[0], y - coordinate[1]);
737
- let total = 0;
738
- let position = 0;
739
- for (let i = 1; i < path.length; i++) {
740
- const a = path[i - 1];
741
- const b = path[i];
742
- const dx = b[0] - a[0];
743
- const dy = b[1] - a[1];
744
- const length = Math.hypot(dx, dy);
745
- if (!length)
746
- continue;
747
- const ux = dx / length;
748
- const uy = dy / length;
749
- const along = Math.max(0, Math.min(length, (x - a[0]) * ux + (y - a[1]) * uy));
750
- let px = along === length ? b[0] : a[0] + along * ux;
751
- let py = along === length ? b[1] : a[1] + along * uy;
752
- if (along > 0 && along < length && (0, import_robust_predicates2.orient2d)(a[0], a[1], b[0], b[1], x, y) === 0) {
753
- px = x;
754
- py = y;
755
- }
756
- const distance = Math.hypot(x - px, y - py);
757
- if (distance < nearest) {
758
- nearest = distance;
759
- coordinate = [px, py];
760
- position = total + along;
761
- }
762
- total += length;
715
+ function collection(rows2) {
716
+ const members = [];
717
+ const offsets = new Int32Array(rows2.length + 1);
718
+ for (let row = 0; row < rows2.length; row++) {
719
+ const geometry = rows2[row];
720
+ if (geometry.type === "GeometryCollection")
721
+ for (const child of geometry.geometries)
722
+ members.push(child);
723
+ offsets[row + 1] = members.length;
763
724
  }
764
- return { coordinate, distance: nearest, fraction: total ? position / total : 0 };
765
- }
766
- function lineLocatePoint(line, point2) {
767
- var _a;
768
- return ((_a = projectPointToLine(line, point2)) == null ? void 0 : _a.fraction) ?? null;
725
+ return { kind: "list", length: rows2.length, offsets, child: union(members, false) };
769
726
  }
770
727
 
771
- // dist/measure-referencing.js
772
- function pathsOf(geometry) {
773
- if (geometry.type === "LineString")
774
- return [geometry.coordinates];
775
- if (geometry.type === "MultiLineString")
776
- return geometry.coordinates;
777
- throw new Error("Measured routes require a LineString or MultiLineString");
728
+ // dist/spatial-sql.js
729
+ var import_apache_arrow = require("apache-arrow");
730
+ var import_arrow4 = require("@math.gl/core/arrow");
731
+
732
+ // dist/turf.js
733
+ var import_arrow2 = require("@math.gl/core/arrow");
734
+ var import_arrow3 = require("@math.gl/core/arrow");
735
+ var RAD = Math.PI / 180;
736
+ var depths = {
737
+ "geoarrow.point": 0,
738
+ "geoarrow.multipoint": 1,
739
+ "geoarrow.linestring": 1,
740
+ "geoarrow.multilinestring": 2,
741
+ "geoarrow.polygon": 2,
742
+ "geoarrow.multipolygon": 3
743
+ };
744
+ function rows(column2, allowed) {
745
+ if (!allowed.includes(column2.encoding))
746
+ throw new Error(`Unsupported GeoArrow encoding ${column2.encoding}; expected ${allowed.join(", ")}`);
747
+ const result2 = [];
748
+ for (const array of column2.chunks)
749
+ for (let index = 0; index < array.length; index++)
750
+ result2.push({ array, index, valid: (0, import_arrow2.isGeoArrowValueValid)(array.validity, index) });
751
+ return result2;
778
752
  }
779
- function measuredDimension(dimension) {
780
- if (dimension === "xym" || dimension === "xyzm")
781
- return dimension;
782
- throw new Error("Input geometry requires a measure (M) ordinate");
753
+ function range(array, index) {
754
+ if (array.kind !== "list")
755
+ throw new Error("Invalid GeoArrow list storage");
756
+ const i = (array.offset || 0) + index;
757
+ const base = Number(array.offsetBase ?? 0);
758
+ const a = Number(array.offsets[i]) - base, b = Number(array.offsets[i + 1]) - base;
759
+ if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b))
760
+ throw new Error("Invalid GeoArrow list offsets");
761
+ return [a, b];
783
762
  }
784
- function addMeasure(geometry, dimension, start, end) {
785
- if (!Number.isFinite(start) || !Number.isFinite(end))
786
- throw new Error("Expected finite measures");
787
- const paths2 = pathsOf(geometry);
788
- let total = 0;
789
- const distances = paths2.map((path) => path.map((point2, i) => {
790
- if (i > 0) {
791
- const previous = path[i - 1];
792
- total += Math.hypot(point2[0] - previous[0], point2[1] - previous[1]);
793
- }
794
- return total;
795
- }));
796
- if (!Number.isFinite(total))
797
- throw new Error("Expected finite route length");
798
- const spatialSize = dimension.includes("z") ? 3 : 2;
799
- const coordinates = paths2.map((path, part) => path.map((point2, i) => {
800
- const fraction = total ? distances[part][i] / total : 0;
801
- return [...point2.slice(0, spatialSize), (1 - fraction) * start + fraction * end];
802
- }));
763
+ function scalar(array, index) {
764
+ if (array.kind !== "primitive")
765
+ throw new Error("Invalid GeoArrow coordinate");
766
+ if (!(0, import_arrow2.isGeoArrowValueValid)(array.validity, index))
767
+ return NaN;
768
+ return Number(array.values[(array.offset || 0) + index * (array.stride || 1)]);
769
+ }
770
+ function point(array, index) {
771
+ if (!(0, import_arrow2.isGeoArrowValueValid)(array.validity, index))
772
+ return null;
773
+ if (array.kind === "fixed-size-list") {
774
+ const i = ((array.offset || 0) + index) * array.size;
775
+ const x = scalar(array.child, i), y = scalar(array.child, i + 1);
776
+ return !Number.isFinite(x) || !Number.isFinite(y) ? null : [x, y];
777
+ }
778
+ if (array.kind === "struct") {
779
+ const i = (array.offset || 0) + index;
780
+ const x = scalar(array.children["x"], i), y = scalar(array.children["y"], i);
781
+ return !Number.isFinite(x) || !Number.isFinite(y) ? null : [x, y];
782
+ }
783
+ throw new Error("Invalid GeoArrow coordinate storage");
784
+ }
785
+ function valid(bitmap, i) {
786
+ bitmap[i >> 3] |= 1 << (i & 7);
787
+ }
788
+ function result(n, boolean = false) {
803
789
  return {
804
- geometry: geometry.type === "LineString" ? { type: "LineString", coordinates: coordinates[0] } : { type: "MultiLineString", coordinates },
805
- dimension: spatialSize === 3 ? "xyzm" : "xym"
790
+ values: boolean ? new Uint8Array(n) : new Float64Array(n),
791
+ validity: new Uint8Array(Math.ceil(n / 8))
806
792
  };
807
793
  }
808
- function samePosition(a, b) {
809
- return a.every((value, i) => value === b[i]);
794
+ function paired(a, b) {
795
+ if (a.length === b.length)
796
+ return a.length;
797
+ if (a.length === 1)
798
+ return b.length;
799
+ if (b.length === 1)
800
+ return a.length;
801
+ throw new Error("GeoArrow batch lengths must match or one input must contain one row");
810
802
  }
811
- function atMeasure(a, b, index, measure) {
812
- const from = a[index];
813
- const to = b[index];
814
- if (from !== to) {
815
- if (measure === from)
816
- return a;
817
- if (measure === to)
818
- return b;
803
+ var native = Object.keys(depths);
804
+ var points = ["geoarrow.point"];
805
+ var polygons2 = ["geoarrow.polygon", "geoarrow.multipolygon"];
806
+ function ringContains(array, a, b, p) {
807
+ let inside = false;
808
+ for (let i = a, j = b - 1; i < b; j = i++) {
809
+ const u = point(array, i), v = point(array, j);
810
+ if (!u || !v)
811
+ continue;
812
+ const cross = (p[0] - u[0]) * (v[1] - u[1]) - (p[1] - u[1]) * (v[0] - u[0]);
813
+ if (cross === 0 && p[0] >= Math.min(u[0], v[0]) && p[0] <= Math.max(u[0], v[0]) && p[1] >= Math.min(u[1], v[1]) && p[1] <= Math.max(u[1], v[1]))
814
+ return 0;
815
+ if (u[1] > p[1] !== v[1] > p[1] && p[0] < (v[0] - u[0]) * (p[1] - u[1]) / (v[1] - u[1]) + u[0])
816
+ inside = !inside;
819
817
  }
820
- const span = to - from;
821
- const fraction = span === 0 ? 0.5 : Number.isFinite(span) ? (measure - from) / span : (measure / 2 - from / 2) / (to / 2 - from / 2);
822
- return a.map((value, i) => i === index ? measure : (1 - fraction) * value + fraction * b[i]);
823
- }
824
- function measureAt(position, index) {
825
- const value = position[index];
826
- if (!Number.isFinite(value))
827
- throw new Error("Expected finite route measures");
828
- return value;
818
+ return inside ? 1 : -1;
829
819
  }
830
- function locateAlong(geometry, dimension, measure) {
831
- if (!Number.isFinite(measure))
832
- throw new Error("Expected a finite measure");
833
- const index = dimension.indexOf("m");
834
- const coordinates = [];
835
- for (const path of pathsOf(geometry)) {
836
- let previousEndsAtVertex = false;
837
- for (let i = 1; i < path.length; i++) {
838
- const a = path[i - 1];
839
- const b = path[i];
840
- const from = measureAt(a, index);
841
- const to = measureAt(b, index);
842
- if (measure < Math.min(from, to) || measure > Math.max(from, to)) {
843
- previousEndsAtVertex = false;
844
- continue;
845
- }
846
- const startsAtVertex = from !== to && measure === from;
847
- if (!previousEndsAtVertex || !startsAtVertex) {
848
- coordinates.push(atMeasure(a, b, index, measure));
849
- }
850
- previousEndsAtVertex = from !== to && measure === to;
851
- }
820
+ function polygonContains(array, index, p) {
821
+ const [a, b] = range(array, index);
822
+ if (array.kind !== "list")
823
+ throw new Error("Invalid polygon");
824
+ if (a === b || !(0, import_arrow2.isGeoArrowValueValid)(array.child.validity, a))
825
+ return -1;
826
+ for (let i = a; i < b; i++) {
827
+ if (!(0, import_arrow2.isGeoArrowValueValid)(array.child.validity, i))
828
+ continue;
829
+ const [x, y] = range(array.child, i);
830
+ if (array.child.kind !== "list")
831
+ throw new Error("Invalid polygon ring");
832
+ const c = ringContains(array.child.child, x, y, p);
833
+ if (c === 0)
834
+ return 0;
835
+ if (i === a && c < 0 || i > a && c > 0)
836
+ return -1;
852
837
  }
853
- return { type: "MultiPoint", coordinates };
854
- }
855
- function appendPortion(parts, path) {
856
- if (path.length === 1)
857
- parts.push({ type: "Point", coordinates: path[0] });
858
- else if (path.length > 1)
859
- parts.push({ type: "LineString", coordinates: path });
838
+ return a === b ? -1 : 1;
860
839
  }
861
- function locateBetween(geometry, dimension, start, end) {
862
- if (!Number.isFinite(start) || !Number.isFinite(end))
863
- throw new Error("Expected finite measures");
864
- const low = Math.min(start, end);
865
- const high = Math.max(start, end);
866
- const index = dimension.indexOf("m");
867
- const parts = [];
868
- for (const path of pathsOf(geometry)) {
869
- let portion = [];
870
- for (let i = 1; i < path.length; i++) {
871
- const a = path[i - 1];
872
- const b = path[i];
873
- const from = measureAt(a, index);
840
+ function booleanPointInPolygon(pointColumn, polygonColumn, options = {}) {
841
+ const a = rows(pointColumn, points), b = rows(polygonColumn, polygons2), n = paired(a, b), out = result(n, true);
842
+ for (let i = 0; i < n; i++) {
843
+ const x = a[a.length === 1 ? 0 : i], y = b[b.length === 1 ? 0 : i];
844
+ if (!x.valid || !y.valid)
845
+ continue;
846
+ const p = point(x.array, x.index);
847
+ if (!p)
848
+ continue;
849
+ let hit = false;
850
+ if (polygonColumn.encoding === "geoarrow.polygon") {
851
+ const c = polygonContains(y.array, y.index, p);
852
+ hit = c > 0 || c === 0 && !options.ignoreBoundary;
853
+ } else {
854
+ const [start, end] = range(y.array, y.index);
855
+ if (y.array.kind !== "list")
856
+ throw new Error("Invalid multipolygon");
857
+ for (let j = start; j < end; j++) {
858
+ if (!(0, import_arrow2.isGeoArrowValueValid)(y.array.child.validity, j))
859
+ continue;
860
+ const c = polygonContains(y.array.child, j, p);
861
+ if (c > 0 || c === 0 && !options.ignoreBoundary) {
862
+ hit = true;
863
+ break;
864
+ }
865
+ }
866
+ }
867
+ out.values[i] = Number(hit);
868
+ valid(out.validity, i);
869
+ }
870
+ return out;
871
+ }
872
+ var lineFamilies = ["geoarrow.linestring", "geoarrow.multilinestring", ...polygons2];
873
+
874
+ // dist/spatial-sql.js
875
+ var EXTENSION_NAME = "ARROW:extension:name";
876
+ var EXTENSION_METADATA = "ARROW:extension:metadata";
877
+ var geometryTypes = [
878
+ "Point",
879
+ "MultiPoint",
880
+ "LineString",
881
+ "MultiLineString",
882
+ "Polygon",
883
+ "MultiPolygon"
884
+ ];
885
+ var pointKinds = ["Point"];
886
+ var lineKinds = ["LineString", "MultiLineString"];
887
+ var polygonKinds = ["Polygon", "MultiPolygon"];
888
+ function nativePointVector(type, data, nullBitmap, nullCount) {
889
+ const child = (0, import_apache_arrow.makeData)({ type: type.valueType, data, length: data.length });
890
+ return (0, import_apache_arrow.makeVector)((0, import_apache_arrow.makeData)({ type, length: data.length / type.listSize, nullCount, nullBitmap, child }));
891
+ }
892
+ function nativeXYPointResult() {
893
+ const type = new import_apache_arrow.FixedSizeList(2, new import_apache_arrow.Field("xy", new import_apache_arrow.Float64(), true));
894
+ return {
895
+ encoding: "geoarrow.point",
896
+ type,
897
+ /** Writes empty points as NaN coordinates and uses a bitmap for null rows. */
898
+ build(rows2) {
899
+ const values = new Float64Array(rows2.length * 2);
900
+ const validity = new Uint8Array(Math.ceil(rows2.length / 8));
901
+ let nullCount = 0;
902
+ for (let row = 0; row < rows2.length; row++) {
903
+ const point2 = rows2[row];
904
+ if (!point2) {
905
+ nullCount++;
906
+ continue;
907
+ }
908
+ if (point2.type !== "Point")
909
+ throw new Error("Expected a Point result");
910
+ validity[row >> 3] |= 1 << (row & 7);
911
+ values[2 * row] = point2.coordinates[0] ?? NaN;
912
+ values[2 * row + 1] = point2.coordinates[1] ?? NaN;
913
+ }
914
+ return nativePointVector(type, values, validity, nullCount);
915
+ }
916
+ };
917
+ }
918
+ function nativeGeometryResult(encoding) {
919
+ if (encoding === "geoarrow.point")
920
+ return nativeXYPointResult();
921
+ const options = { encoding, dimension: "xy", coordinateLayout: "interleaved" };
922
+ const build = (rows2) => (0, import_arrow4.makeArrowVectorFromGeoArrowColumn)(import_arrow4.GeoArrowBuilder.build(rows2, options));
923
+ return { encoding, type: build([]).type, build };
924
+ }
925
+ function readGeometryValue(vector, field, active, value, captureMembers = false) {
926
+ if (import_apache_arrow.DataType.isBinary(field.type) || import_apache_arrow.DataType.isLargeBinary(field.type)) {
927
+ return (row) => {
928
+ const { geometry, dimension, srid, members } = (0, import_arrow4.parseWKB)(vector.get(row), {
929
+ captureMembers
930
+ });
931
+ if (srid)
932
+ throw new Error("Use GeoArrow field metadata for CRS information instead of EWKB SRIDs");
933
+ return value(geometry.type === "Point" && geometry.coordinates.every(Number.isNaN) ? { type: "Point", coordinates: [] } : geometry, dimension, members);
934
+ };
935
+ }
936
+ const column2 = readActiveGeoArrowColumn(vector, field, active);
937
+ const geometries = (0, import_arrow4.materializeGeoArrowRows)(column2);
938
+ return (row) => value(geometries[row], column2.dimension);
939
+ }
940
+ function readActiveGeoArrowColumn(vector, field, active) {
941
+ const column2 = (0, import_arrow4.makeGeoArrowColumnFromArrowVector)(vector, { field });
942
+ let offset = 0;
943
+ const chunks = column2.chunks.map((chunk) => {
944
+ const start = offset;
945
+ offset += chunk.length;
946
+ let needsMask = false;
947
+ for (let row = 0; row < chunk.length; row++) {
948
+ if (!active[start + row] && (0, import_arrow4.isGeoArrowValueValid)(chunk.validity, row)) {
949
+ needsMask = true;
950
+ break;
951
+ }
952
+ }
953
+ if (!needsMask)
954
+ return chunk;
955
+ const values = new Uint8Array(Math.ceil(chunk.length / 8));
956
+ for (let row = 0; row < chunk.length; row++) {
957
+ if (active[start + row] && (0, import_arrow4.isGeoArrowValueValid)(chunk.validity, row)) {
958
+ values[row >> 3] |= 1 << (row & 7);
959
+ }
960
+ }
961
+ return { ...chunk, validity: { values } };
962
+ });
963
+ return { ...column2, chunks };
964
+ }
965
+ function planarGeometry(geometry, dimension) {
966
+ if (dimension !== "xy")
967
+ throw new Error("Spatial SQL functions require 2D geometry");
968
+ return geometry;
969
+ }
970
+ function spatialFunction(name, signatures, output, evaluate, numericArguments = 0, allDimensions = false, skipNullGeometries = false, validateCRS) {
971
+ const type = "encoding" in output ? output.type : output;
972
+ return {
973
+ kind: "scalar",
974
+ name,
975
+ prototypes: [],
976
+ /** Binds the allowed geometry types and result metadata to a call. */
977
+ resolvePrototype(fields) {
978
+ var _a;
979
+ if (fields.length !== signatures.length + numericArguments)
980
+ return void 0;
981
+ const geometryFields = fields.slice(0, signatures.length);
982
+ const numberFields = fields.slice(signatures.length).map((field) => {
983
+ if (field && !import_apache_arrow.DataType.isInt(field.type) && !import_apache_arrow.DataType.isFloat(field.type))
984
+ throw new Error(`${name} requires numeric arguments`);
985
+ return field ?? new import_apache_arrow.Field("number", new import_apache_arrow.Float64(), true);
986
+ });
987
+ const extensions = geometryFields.map((field, index) => {
988
+ if (!field)
989
+ return void 0;
990
+ const extension = (0, import_arrow4.getGeoArrowFieldInfo)(field);
991
+ const encoding = extension == null ? void 0 : extension.encoding;
992
+ const kinds = signatures[index];
993
+ if (encoding === "geoarrow.wkb" && (import_apache_arrow.DataType.isBinary(field.type) || import_apache_arrow.DataType.isLargeBinary(field.type))) {
994
+ } else if (encoding === "geoarrow.geometry" && extension.dimension === "xy") {
995
+ } else if (kinds.some((kind) => encoding === "geoarrow." + kind.toLowerCase())) {
996
+ if (!allDimensions && (extension == null ? void 0 : extension.dimension) !== "xy")
997
+ throw new Error(`${name} requires 2D geometry`);
998
+ } else {
999
+ throw new Error(`${name} argument ${index + 1} requires GeoArrow ${kinds.join(" or ")}`);
1000
+ }
1001
+ validateCRS == null ? void 0 : validateCRS(extension == null ? void 0 : extension.metadata["crs"], name);
1002
+ if (!validateCRS && name.startsWith("ST_") && name !== "ST_SRID" && name !== "ST_SetSRID" && (extension == null ? void 0 : extension.metadata["edges"]) === "spherical")
1003
+ throw new Error(`${name} requires planar geometry`);
1004
+ return extension;
1005
+ });
1006
+ const crsValues = extensions.map((extension) => extension == null ? void 0 : extension.metadata["crs"]).filter((crs) => crs !== void 0 && crs !== null);
1007
+ if (!validateCRS && name.startsWith("ST_") && crsValues.some((crs) => JSON.stringify(crs) !== JSON.stringify(crsValues[0]))) {
1008
+ throw new Error(`${name} requires arguments in the same CRS`);
1009
+ }
1010
+ const metadata = /* @__PURE__ */ new Map();
1011
+ if ("encoding" in output || import_apache_arrow.DataType.isBinary(type)) {
1012
+ metadata.set(EXTENSION_NAME, "encoding" in output ? output.encoding : "geoarrow.wkb");
1013
+ const inputMetadata = (_a = extensions[0]) == null ? void 0 : _a.metadata;
1014
+ const crs = inputMetadata == null ? void 0 : inputMetadata["crs"];
1015
+ const crsType = crs === void 0 ? void 0 : inputMetadata == null ? void 0 : inputMetadata["crs_type"];
1016
+ const edges2 = inputMetadata == null ? void 0 : inputMetadata["edges"];
1017
+ if (crs !== void 0 || edges2 !== void 0) {
1018
+ metadata.set(EXTENSION_METADATA, JSON.stringify({ crs, crs_type: crsType, edges: edges2 }));
1019
+ }
1020
+ }
1021
+ const arguments_ = [
1022
+ ...geometryFields.map((field) => field ?? new import_apache_arrow.Field("geometry", new import_apache_arrow.Binary(), true)),
1023
+ ...numberFields
1024
+ ];
1025
+ return {
1026
+ arguments: arguments_,
1027
+ nullHandling: skipNullGeometries ? "call" : "propagate",
1028
+ result: new import_apache_arrow.Field(name, type, true, metadata),
1029
+ /** Evaluates active rows and retains their positions in the output batch. */
1030
+ evaluate(vectors, { activeRows, length: rowCount }) {
1031
+ const numbers = vectors.slice(signatures.length);
1032
+ const readers = vectors.slice(0, signatures.length).map((vector, index) => readGeometryValue(vector, arguments_[index], activeRows, allDimensions ? (g, dimension, members) => ({ ...g, dimension, members }) : planarGeometry, name === "ST_GeometryN"));
1033
+ const values = new Array(rowCount).fill(null);
1034
+ for (let row = 0; row < rowCount; row++) {
1035
+ if (!activeRows[row])
1036
+ continue;
1037
+ const geometries = [];
1038
+ for (let index = 0; index < readers.length; index++) {
1039
+ if (skipNullGeometries && !vectors[index].isValid(row))
1040
+ continue;
1041
+ const geometry = readers[index](row);
1042
+ if (!signatures[index].includes(geometry.type))
1043
+ throw new Error(`${name} argument ${index + 1} does not support ${geometry.type} at row ${row}`);
1044
+ geometries.push(geometry);
1045
+ }
1046
+ values[row] = evaluate(geometries, ...numbers.map((vector) => Number(vector.get(row))));
1047
+ }
1048
+ return "encoding" in output ? output.build(values) : (0, import_apache_arrow.vectorFromArray)(values, output);
1049
+ }
1050
+ };
1051
+ }
1052
+ };
1053
+ }
1054
+ function pointCoordinates(geometry) {
1055
+ return geometry.type === "Point" && Number.isFinite(geometry.coordinates[0]) && Number.isFinite(geometry.coordinates[1]) ? geometry.coordinates : null;
1056
+ }
1057
+ function column(geometry) {
1058
+ return (0, import_arrow4.makeGeoArrowColumnFromGeometryRows)([geometry], { dimension: "xy" });
1059
+ }
1060
+ function scalar2(result2) {
1061
+ return result2.validity[0] & 1 ? result2.values[0] : null;
1062
+ }
1063
+ function pointInPolygon(point2, polygon, ignoreBoundary = false) {
1064
+ if (!pointCoordinates(point2))
1065
+ return null;
1066
+ const value = scalar2(booleanPointInPolygon(column(point2), column(polygon), { ignoreBoundary }));
1067
+ return value === null ? null : value === 1;
1068
+ }
1069
+
1070
+ // dist/route-editing.js
1071
+ function mergeRoute(geometry) {
1072
+ if (geometry.type === "LineString")
1073
+ return geometry;
1074
+ if (geometry.type !== "MultiLineString")
1075
+ throw new Error("ST_LineMerge requires linear geometry");
1076
+ const merged = (0, import_polygon3.mergePolylinePaths)(geometry.coordinates);
1077
+ return merged.length === 1 ? { type: "LineString", coordinates: merged[0] } : { type: "MultiLineString", coordinates: merged };
1078
+ }
1079
+ var MAX_ADDED_VERTICES = 1e6;
1080
+ function segmentizeRoute(geometry, step, name, segmentFor) {
1081
+ if (!Number.isFinite(step) || step <= 0)
1082
+ throw new Error(name + " requires a finite positive maximum segment length");
1083
+ if (geometry.type === "LineString") {
1084
+ const [coordinates] = (0, import_polygon3.segmentizePolylinePaths)([geometry.coordinates], step, MAX_ADDED_VERTICES, segmentFor);
1085
+ return { type: "LineString", coordinates };
1086
+ }
1087
+ if (geometry.type === "MultiLineString") {
1088
+ return {
1089
+ type: "MultiLineString",
1090
+ coordinates: (0, import_polygon3.segmentizePolylinePaths)(geometry.coordinates, step, MAX_ADDED_VERTICES, segmentFor)
1091
+ };
1092
+ }
1093
+ throw new Error(name + " requires linear geometry");
1094
+ }
1095
+ function routeEditingFunction(name, preservesLineKind, evaluate, numericArguments = 0, validateCRS) {
1096
+ return {
1097
+ kind: "scalar",
1098
+ name,
1099
+ prototypes: [],
1100
+ /** Binds a stable native output for specialized, WKB, and mixed inputs. */
1101
+ resolvePrototype(fields) {
1102
+ var _a;
1103
+ const encoding = fields[0] && ((_a = (0, import_arrow5.getGeoArrowFieldInfo)(fields[0])) == null ? void 0 : _a.encoding);
1104
+ const output = encoding === "geoarrow.linestring" || preservesLineKind && encoding === "geoarrow.multilinestring" ? nativeGeometryResult(encoding) : lineIntersectionResult();
1105
+ return spatialFunction(name, [lineKinds], output, ([geometry], ...numbers) => evaluate(geometry, ...numbers), numericArguments, false, false, validateCRS).resolvePrototype(fields);
1106
+ }
1107
+ };
1108
+ }
1109
+ function segmentizeFunction(name, segmentFor, validateCRS) {
1110
+ return routeEditingFunction(name, true, (geometry, step) => segmentizeRoute(geometry, step, name, segmentFor), 1, validateCRS);
1111
+ }
1112
+
1113
+ // dist/linear-referencing.js
1114
+ var import_polygon4 = require("@math.gl/geometry/polygon");
1115
+ function cumulativeDistances(path) {
1116
+ const distances = [0];
1117
+ for (let i = 1; i < path.length; i++) {
1118
+ const a = path[i - 1], b = path[i];
1119
+ distances.push(distances[i - 1] + Math.hypot(b[0] - a[0], b[1] - a[1]));
1120
+ }
1121
+ return distances;
1122
+ }
1123
+ function coordinateAt(path, distances, target) {
1124
+ for (let i = 0; i < path.length; i++) {
1125
+ if (target === distances[i])
1126
+ return path[i];
1127
+ if (target < distances[i]) {
1128
+ const t = (target - distances[i - 1]) / (distances[i] - distances[i - 1]);
1129
+ const a = path[i - 1], b = path[i];
1130
+ return [(1 - t) * a[0] + t * b[0], (1 - t) * a[1] + t * b[1]];
1131
+ }
1132
+ }
1133
+ return path[path.length - 1];
1134
+ }
1135
+ function lineSubstring(line, start, end) {
1136
+ if (!(start >= 0 && end <= 1 && start <= end))
1137
+ throw new Error("Expected ordered route fractions in [0, 1]");
1138
+ if (line.type !== "LineString" || !line.coordinates.length)
1139
+ return null;
1140
+ const path = line.coordinates;
1141
+ const distances = cumulativeDistances(path);
1142
+ const total = distances[distances.length - 1];
1143
+ const from = start * total, to = end * total;
1144
+ if (from === to)
1145
+ return { type: "Point", coordinates: coordinateAt(path, distances, from) };
1146
+ const coordinates = [];
1147
+ let startSegment = 0;
1148
+ while (distances[startSegment + 1] <= from)
1149
+ startSegment++;
1150
+ let endSegment = startSegment;
1151
+ while (distances[endSegment + 1] < to)
1152
+ endSegment++;
1153
+ (0, import_polygon4.visitPolylineSpan)((vertex, ordinate) => path[vertex][ordinate], startSegment, (from - distances[startSegment]) / (distances[startSegment + 1] - distances[startSegment]), endSegment, (to - distances[endSegment]) / (distances[endSegment + 1] - distances[endSegment]), (x, y, vertex) => {
1154
+ if (vertex === void 0 || distances[vertex] !== distances[vertex - 1])
1155
+ coordinates.push([x, y]);
1156
+ });
1157
+ return { type: "LineString", coordinates };
1158
+ }
1159
+ function projectPointToLine(line, point2) {
1160
+ return line.type === "LineString" && point2.type === "Point" ? (0, import_polygon4.projectPointToPolyline)(line.coordinates, point2.coordinates) : null;
1161
+ }
1162
+ function lineLocatePoint(line, point2) {
1163
+ var _a;
1164
+ return ((_a = projectPointToLine(line, point2)) == null ? void 0 : _a.fraction) ?? null;
1165
+ }
1166
+
1167
+ // dist/measure-referencing.js
1168
+ function pathsOf(geometry) {
1169
+ if (geometry.type === "LineString")
1170
+ return [geometry.coordinates];
1171
+ if (geometry.type === "MultiLineString")
1172
+ return geometry.coordinates;
1173
+ throw new Error("Measured routes require a LineString or MultiLineString");
1174
+ }
1175
+ function measuredDimension(dimension) {
1176
+ if (dimension === "xym" || dimension === "xyzm")
1177
+ return dimension;
1178
+ throw new Error("Input geometry requires a measure (M) ordinate");
1179
+ }
1180
+ function addMeasure(geometry, dimension, start, end) {
1181
+ if (!Number.isFinite(start) || !Number.isFinite(end))
1182
+ throw new Error("Expected finite measures");
1183
+ const paths3 = pathsOf(geometry);
1184
+ let total = 0;
1185
+ const distances = paths3.map((path) => path.map((point2, i) => {
1186
+ if (i > 0) {
1187
+ const previous = path[i - 1];
1188
+ total += Math.hypot(point2[0] - previous[0], point2[1] - previous[1]);
1189
+ }
1190
+ return total;
1191
+ }));
1192
+ if (!Number.isFinite(total))
1193
+ throw new Error("Expected finite route length");
1194
+ const spatialSize = dimension.includes("z") ? 3 : 2;
1195
+ const coordinates = paths3.map((path, part) => path.map((point2, i) => {
1196
+ const fraction = total ? distances[part][i] / total : 0;
1197
+ return [...point2.slice(0, spatialSize), (1 - fraction) * start + fraction * end];
1198
+ }));
1199
+ return {
1200
+ geometry: geometry.type === "LineString" ? { type: "LineString", coordinates: coordinates[0] } : { type: "MultiLineString", coordinates },
1201
+ dimension: spatialSize === 3 ? "xyzm" : "xym"
1202
+ };
1203
+ }
1204
+ function samePosition(a, b) {
1205
+ return a.every((value, i) => value === b[i]);
1206
+ }
1207
+ function atMeasure(a, b, index, measure) {
1208
+ const from = a[index];
1209
+ const to = b[index];
1210
+ if (from !== to) {
1211
+ if (measure === from)
1212
+ return a;
1213
+ if (measure === to)
1214
+ return b;
1215
+ }
1216
+ const span = to - from;
1217
+ const fraction = span === 0 ? 0.5 : Number.isFinite(span) ? (measure - from) / span : (measure / 2 - from / 2) / (to / 2 - from / 2);
1218
+ return a.map((value, i) => i === index ? measure : (1 - fraction) * value + fraction * b[i]);
1219
+ }
1220
+ function measureAt(position, index) {
1221
+ const value = position[index];
1222
+ if (!Number.isFinite(value))
1223
+ throw new Error("Expected finite route measures");
1224
+ return value;
1225
+ }
1226
+ function locateAlong(geometry, dimension, measure) {
1227
+ if (!Number.isFinite(measure))
1228
+ throw new Error("Expected a finite measure");
1229
+ const index = dimension.indexOf("m");
1230
+ const coordinates = [];
1231
+ for (const path of pathsOf(geometry)) {
1232
+ let previousEndsAtVertex = false;
1233
+ for (let i = 1; i < path.length; i++) {
1234
+ const a = path[i - 1];
1235
+ const b = path[i];
1236
+ const from = measureAt(a, index);
1237
+ const to = measureAt(b, index);
1238
+ if (measure < Math.min(from, to) || measure > Math.max(from, to)) {
1239
+ previousEndsAtVertex = false;
1240
+ continue;
1241
+ }
1242
+ const startsAtVertex = from !== to && measure === from;
1243
+ if (!previousEndsAtVertex || !startsAtVertex) {
1244
+ coordinates.push(atMeasure(a, b, index, measure));
1245
+ }
1246
+ previousEndsAtVertex = from !== to && measure === to;
1247
+ }
1248
+ }
1249
+ return { type: "MultiPoint", coordinates };
1250
+ }
1251
+ function appendPortion(parts, path) {
1252
+ if (path.length === 1)
1253
+ parts.push({ type: "Point", coordinates: path[0] });
1254
+ else if (path.length > 1)
1255
+ parts.push({ type: "LineString", coordinates: path });
1256
+ }
1257
+ function locateBetween(geometry, dimension, start, end) {
1258
+ if (!Number.isFinite(start) || !Number.isFinite(end))
1259
+ throw new Error("Expected finite measures");
1260
+ const low = Math.min(start, end);
1261
+ const high = Math.max(start, end);
1262
+ const index = dimension.indexOf("m");
1263
+ const parts = [];
1264
+ for (const path of pathsOf(geometry)) {
1265
+ let portion = [];
1266
+ for (let i = 1; i < path.length; i++) {
1267
+ const a = path[i - 1];
1268
+ const b = path[i];
1269
+ const from = measureAt(a, index);
874
1270
  const to = measureAt(b, index);
875
1271
  const begin = Math.max(low, Math.min(from, to));
876
1272
  const finish = Math.min(high, Math.max(from, to));
@@ -1097,34 +1493,8 @@ function reduceLineVertices(geometry, tolerance, mode) {
1097
1493
  }
1098
1494
 
1099
1495
  // dist/polygon-simplification.js
1100
- var import_robust_predicates3 = require("robust-predicates");
1101
- function intervalDensity(items, axis) {
1102
- let minimum = Infinity;
1103
- let maximum = -Infinity;
1104
- let length = 0;
1105
- for (const { bounds } of items) {
1106
- const low = bounds[axis];
1107
- const high = bounds[axis + 2];
1108
- minimum = Math.min(minimum, low);
1109
- maximum = Math.max(maximum, high);
1110
- length += high - low;
1111
- }
1112
- return maximum > minimum ? length / (maximum - minimum) : Infinity;
1113
- }
1114
- function anyOverlap(items, reject) {
1115
- const axis = intervalDensity(items, 0) > intervalDensity(items, 1) ? 1 : 0;
1116
- const other = 1 - axis;
1117
- items.sort((a, b) => a.bounds[axis] - b.bounds[axis]);
1118
- for (let i = 0; i < items.length; i++) {
1119
- const a = items[i];
1120
- for (let j = i + 1; j < items.length && items[j].bounds[axis] <= a.bounds[axis + 2]; j++) {
1121
- const b = items[j];
1122
- if (b.bounds[other] <= a.bounds[other + 2] && a.bounds[other] <= b.bounds[other + 2] && reject(a, b))
1123
- return true;
1124
- }
1125
- }
1126
- return false;
1127
- }
1496
+ var import_robust_predicates = require("robust-predicates");
1497
+ var import_processing = require("@math.gl/geometry/processing");
1128
1498
  function samePoint2(a, b) {
1129
1499
  return a[0] === b[0] && a[1] === b[1];
1130
1500
  }
@@ -1150,7 +1520,7 @@ function separatedBoundaries(rings) {
1150
1520
  const c = ring[(i + 2) % size];
1151
1521
  if (!Number.isFinite(a[0]) || !Number.isFinite(a[1]) || samePoint2(a, b))
1152
1522
  return false;
1153
- if ((0, import_robust_predicates3.orient2d)(a[0], a[1], b[0], b[1], c[0], c[1]) === 0 && (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1]) > 0)
1523
+ if ((0, import_robust_predicates.orient2d)(a[0], a[1], b[0], b[1], c[0], c[1]) === 0 && (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1]) > 0)
1154
1524
  return false;
1155
1525
  edges2.push({
1156
1526
  a,
@@ -1166,389 +1536,79 @@ function separatedBoundaries(rings) {
1166
1536
  });
1167
1537
  }
1168
1538
  }
1169
- return !anyOverlap(edges2, (a, b) => {
1539
+ return !(0, import_processing.anyBoundsOverlap)(edges2, (a, b) => {
1170
1540
  if (a.ring === b.ring) {
1171
1541
  const gap = Math.abs(a.index - b.index);
1172
1542
  if (gap === 1 || gap === a.ring.length - 2)
1173
- return false;
1174
- }
1175
- return segmentsMeet(a.a, a.b, b.a, b.b);
1176
- });
1177
- }
1178
- function contains(outer, inner) {
1179
- return planarIntersects({ type: "Polygon", coordinates: [outer] }, { type: "Point", coordinates: inner[0] });
1180
- }
1181
- function preservesNesting(before, after) {
1182
- const rings = before.map((original, index) => ({
1183
- original,
1184
- simplified: after[index],
1185
- bounds: planarBounds({ type: "LineString", coordinates: original })
1186
- }));
1187
- return !anyOverlap(rings, (a, b) => contains(a.original, b.original) !== contains(a.simplified, b.simplified) || contains(b.original, a.original) !== contains(b.simplified, a.simplified));
1188
- }
1189
- function simplifyRing(ring, tolerance) {
1190
- const reduced = simplifyLine(ring, tolerance);
1191
- if (reduced.length < 4 || reduced.length === ring.length)
1192
- return ring;
1193
- const before = signedArea(ring);
1194
- const after = signedArea(reduced);
1195
- return Number.isFinite(before) && Number.isFinite(after) && after && Math.sign(before) === Math.sign(after) ? reduced : ring;
1196
- }
1197
- function simplifyPolygonTopology(geometry, tolerance) {
1198
- if (!Number.isFinite(tolerance) || tolerance < 0)
1199
- throw new Error("Expected a finite nonnegative tolerance");
1200
- if (!tolerance)
1201
- return geometry;
1202
- const polygons3 = geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
1203
- const before = polygons3.flat();
1204
- const reduced = polygons3.map((polygon) => polygon.map((ring) => simplifyRing(ring, tolerance)));
1205
- const after = reduced.flat();
1206
- if (before.every((ring, index) => ring === after[index]))
1207
- return geometry;
1208
- if (!separatedBoundaries(before) || !separatedBoundaries(after) || !preservesNesting(before, after))
1209
- return geometry;
1210
- return geometry.type === "Polygon" ? { type: "Polygon", coordinates: reduced[0] } : { type: "MultiPolygon", coordinates: reduced };
1211
- }
1212
-
1213
- // dist/geometry-constructors.js
1214
- function collectPair(a, b) {
1215
- if (a.type === "Point" && b.type === "Point")
1216
- return { type: "MultiPoint", coordinates: [a.coordinates, b.coordinates] };
1217
- if (a.type === "LineString" && b.type === "LineString")
1218
- return { type: "MultiLineString", coordinates: [a.coordinates, b.coordinates] };
1219
- if (a.type === "Polygon" && b.type === "Polygon")
1220
- return { type: "MultiPolygon", coordinates: [a.coordinates, b.coordinates] };
1221
- return { type: "GeometryCollection", geometries: [a, b] };
1222
- }
1223
- function makeLine(parts) {
1224
- const coordinates = [];
1225
- for (const part of parts) {
1226
- if (part.type === "Point") {
1227
- if (part.coordinates.length)
1228
- coordinates.push(part.coordinates);
1229
- } else if (part.type === "MultiPoint") {
1230
- for (const point2 of part.coordinates)
1231
- if (point2.length && !point2.every(Number.isNaN))
1232
- coordinates.push(point2);
1233
- } else if (part.type === "LineString") {
1234
- const previous = coordinates[coordinates.length - 1];
1235
- const first = part.coordinates[0];
1236
- const shared = previous && first && previous[0] === first[0] && previous[1] === first[1];
1237
- for (let i = shared ? 1 : 0; i < part.coordinates.length; i++)
1238
- coordinates.push(part.coordinates[i]);
1239
- }
1240
- }
1241
- return { type: "LineString", coordinates };
1242
- }
1243
-
1244
- // dist/spatial-sql.js
1245
- var import_apache_arrow = require("apache-arrow");
1246
- var import_arrow3 = require("@math.gl/core/arrow");
1247
-
1248
- // dist/turf.js
1249
- var import_arrow = require("@math.gl/core/arrow");
1250
- var import_arrow2 = require("@math.gl/core/arrow");
1251
- var RAD = Math.PI / 180;
1252
- var depths = {
1253
- "geoarrow.point": 0,
1254
- "geoarrow.multipoint": 1,
1255
- "geoarrow.linestring": 1,
1256
- "geoarrow.multilinestring": 2,
1257
- "geoarrow.polygon": 2,
1258
- "geoarrow.multipolygon": 3
1259
- };
1260
- function rows(column2, allowed) {
1261
- if (!allowed.includes(column2.encoding))
1262
- throw new Error(`Unsupported GeoArrow encoding ${column2.encoding}; expected ${allowed.join(", ")}`);
1263
- const result2 = [];
1264
- for (const array of column2.chunks)
1265
- for (let index = 0; index < array.length; index++)
1266
- result2.push({ array, index, valid: (0, import_arrow.isGeoArrowValueValid)(array.validity, index) });
1267
- return result2;
1268
- }
1269
- function range(array, index) {
1270
- if (array.kind !== "list")
1271
- throw new Error("Invalid GeoArrow list storage");
1272
- const i = (array.offset || 0) + index;
1273
- const base = Number(array.offsetBase ?? 0);
1274
- const a = Number(array.offsets[i]) - base, b = Number(array.offsets[i + 1]) - base;
1275
- if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b))
1276
- throw new Error("Invalid GeoArrow list offsets");
1277
- return [a, b];
1278
- }
1279
- function scalar(array, index) {
1280
- if (array.kind !== "primitive")
1281
- throw new Error("Invalid GeoArrow coordinate");
1282
- if (!(0, import_arrow.isGeoArrowValueValid)(array.validity, index))
1283
- return NaN;
1284
- return Number(array.values[(array.offset || 0) + index * (array.stride || 1)]);
1285
- }
1286
- function point(array, index) {
1287
- if (!(0, import_arrow.isGeoArrowValueValid)(array.validity, index))
1288
- return null;
1289
- if (array.kind === "fixed-size-list") {
1290
- const i = ((array.offset || 0) + index) * array.size;
1291
- const x = scalar(array.child, i), y = scalar(array.child, i + 1);
1292
- return !Number.isFinite(x) || !Number.isFinite(y) ? null : [x, y];
1293
- }
1294
- if (array.kind === "struct") {
1295
- const i = (array.offset || 0) + index;
1296
- const x = scalar(array.children["x"], i), y = scalar(array.children["y"], i);
1297
- return !Number.isFinite(x) || !Number.isFinite(y) ? null : [x, y];
1298
- }
1299
- throw new Error("Invalid GeoArrow coordinate storage");
1300
- }
1301
- function valid(bitmap, i) {
1302
- bitmap[i >> 3] |= 1 << (i & 7);
1303
- }
1304
- function result(n, boolean = false) {
1305
- return {
1306
- values: boolean ? new Uint8Array(n) : new Float64Array(n),
1307
- validity: new Uint8Array(Math.ceil(n / 8))
1308
- };
1309
- }
1310
- function paired(a, b) {
1311
- if (a.length === b.length)
1312
- return a.length;
1313
- if (a.length === 1)
1314
- return b.length;
1315
- if (b.length === 1)
1316
- return a.length;
1317
- throw new Error("GeoArrow batch lengths must match or one input must contain one row");
1318
- }
1319
- var native = Object.keys(depths);
1320
- var points = ["geoarrow.point"];
1321
- var polygons2 = ["geoarrow.polygon", "geoarrow.multipolygon"];
1322
- function ringContains(array, a, b, p) {
1323
- let inside = false;
1324
- for (let i = a, j = b - 1; i < b; j = i++) {
1325
- const u = point(array, i), v = point(array, j);
1326
- if (!u || !v)
1327
- continue;
1328
- const cross = (p[0] - u[0]) * (v[1] - u[1]) - (p[1] - u[1]) * (v[0] - u[0]);
1329
- if (cross === 0 && p[0] >= Math.min(u[0], v[0]) && p[0] <= Math.max(u[0], v[0]) && p[1] >= Math.min(u[1], v[1]) && p[1] <= Math.max(u[1], v[1]))
1330
- return 0;
1331
- if (u[1] > p[1] !== v[1] > p[1] && p[0] < (v[0] - u[0]) * (p[1] - u[1]) / (v[1] - u[1]) + u[0])
1332
- inside = !inside;
1333
- }
1334
- return inside ? 1 : -1;
1335
- }
1336
- function polygonContains(array, index, p) {
1337
- const [a, b] = range(array, index);
1338
- if (array.kind !== "list")
1339
- throw new Error("Invalid polygon");
1340
- if (a === b || !(0, import_arrow.isGeoArrowValueValid)(array.child.validity, a))
1341
- return -1;
1342
- for (let i = a; i < b; i++) {
1343
- if (!(0, import_arrow.isGeoArrowValueValid)(array.child.validity, i))
1344
- continue;
1345
- const [x, y] = range(array.child, i);
1346
- if (array.child.kind !== "list")
1347
- throw new Error("Invalid polygon ring");
1348
- const c = ringContains(array.child.child, x, y, p);
1349
- if (c === 0)
1350
- return 0;
1351
- if (i === a && c < 0 || i > a && c > 0)
1352
- return -1;
1353
- }
1354
- return a === b ? -1 : 1;
1355
- }
1356
- function booleanPointInPolygon(pointColumn, polygonColumn, options = {}) {
1357
- const a = rows(pointColumn, points), b = rows(polygonColumn, polygons2), n = paired(a, b), out = result(n, true);
1358
- for (let i = 0; i < n; i++) {
1359
- const x = a[a.length === 1 ? 0 : i], y = b[b.length === 1 ? 0 : i];
1360
- if (!x.valid || !y.valid)
1361
- continue;
1362
- const p = point(x.array, x.index);
1363
- if (!p)
1364
- continue;
1365
- let hit = false;
1366
- if (polygonColumn.encoding === "geoarrow.polygon") {
1367
- const c = polygonContains(y.array, y.index, p);
1368
- hit = c > 0 || c === 0 && !options.ignoreBoundary;
1369
- } else {
1370
- const [start, end] = range(y.array, y.index);
1371
- if (y.array.kind !== "list")
1372
- throw new Error("Invalid multipolygon");
1373
- for (let j = start; j < end; j++) {
1374
- if (!(0, import_arrow.isGeoArrowValueValid)(y.array.child.validity, j))
1375
- continue;
1376
- const c = polygonContains(y.array.child, j, p);
1377
- if (c > 0 || c === 0 && !options.ignoreBoundary) {
1378
- hit = true;
1379
- break;
1380
- }
1381
- }
1382
- }
1383
- out.values[i] = Number(hit);
1384
- valid(out.validity, i);
1385
- }
1386
- return out;
1387
- }
1388
- var lineFamilies = ["geoarrow.linestring", "geoarrow.multilinestring", ...polygons2];
1389
-
1390
- // dist/spatial-sql.js
1391
- var EXTENSION_NAME = "ARROW:extension:name";
1392
- var EXTENSION_METADATA = "ARROW:extension:metadata";
1393
- var geometryTypes = [
1394
- "Point",
1395
- "MultiPoint",
1396
- "LineString",
1397
- "MultiLineString",
1398
- "Polygon",
1399
- "MultiPolygon"
1400
- ];
1401
- var pointKinds = ["Point"];
1402
- var lineKinds = ["LineString", "MultiLineString"];
1403
- var polygonKinds = ["Polygon", "MultiPolygon"];
1404
- function nativePolygonResult(encoding) {
1405
- const options = { encoding, dimension: "xy", coordinateLayout: "interleaved" };
1406
- const build = (rows2) => (0, import_arrow3.makeArrowVectorFromGeoArrowColumn)(import_arrow3.GeoArrowBuilder.build(rows2, options));
1407
- return { encoding, type: build([]).type, build };
1408
- }
1409
- function readGeometryValue(vector, field, active, value, captureMembers = false) {
1410
- if (import_apache_arrow.DataType.isBinary(field.type) || import_apache_arrow.DataType.isLargeBinary(field.type)) {
1411
- return (row) => {
1412
- const { geometry, dimension, srid, members } = (0, import_arrow3.parseWKB)(vector.get(row), {
1413
- captureMembers
1414
- });
1415
- if (srid)
1416
- throw new Error("Use GeoArrow field metadata for CRS information instead of EWKB SRIDs");
1417
- return value(geometry.type === "Point" && geometry.coordinates.every(Number.isNaN) ? { type: "Point", coordinates: [] } : geometry, dimension, members);
1418
- };
1419
- }
1420
- const column2 = readActiveGeoArrowColumn(vector, field, active);
1421
- const geometries = (0, import_arrow3.materializeGeoArrowRows)(column2);
1422
- return (row) => value(geometries[row], column2.dimension);
1423
- }
1424
- function readActiveGeoArrowColumn(vector, field, active) {
1425
- const column2 = (0, import_arrow3.makeGeoArrowColumnFromArrowVector)(vector, { field });
1426
- let offset = 0;
1427
- const chunks = column2.chunks.map((chunk) => {
1428
- const start = offset;
1429
- offset += chunk.length;
1430
- let needsMask = false;
1431
- for (let row = 0; row < chunk.length; row++) {
1432
- if (!active[start + row] && (0, import_arrow3.isGeoArrowValueValid)(chunk.validity, row)) {
1433
- needsMask = true;
1434
- break;
1435
- }
1436
- }
1437
- if (!needsMask)
1438
- return chunk;
1439
- const values = new Uint8Array(Math.ceil(chunk.length / 8));
1440
- for (let row = 0; row < chunk.length; row++) {
1441
- if (active[start + row] && (0, import_arrow3.isGeoArrowValueValid)(chunk.validity, row)) {
1442
- values[row >> 3] |= 1 << (row & 7);
1443
- }
1543
+ return false;
1444
1544
  }
1445
- return { ...chunk, validity: { values } };
1545
+ return (0, import_polygon2.segmentsMeet)(a.a, a.b, b.a, b.b);
1446
1546
  });
1447
- return { ...column2, chunks };
1448
1547
  }
1449
- function planarGeometry(geometry, dimension) {
1450
- if (dimension !== "xy")
1451
- throw new Error("Spatial SQL functions require 2D geometry");
1452
- return geometry;
1548
+ function contains(outer, inner) {
1549
+ return planarIntersects({ type: "Polygon", coordinates: [outer] }, { type: "Point", coordinates: inner[0] });
1453
1550
  }
1454
- function spatialFunction(name, signatures, output, evaluate, numericArguments = 0, allDimensions = false, skipNullGeometries = false, validateCRS) {
1455
- const type = "encoding" in output ? output.type : output;
1456
- return {
1457
- kind: "scalar",
1458
- name,
1459
- prototypes: [],
1460
- /** Binds the allowed geometry types and result metadata to a call. */
1461
- resolvePrototype(fields) {
1462
- var _a;
1463
- if (fields.length !== signatures.length + numericArguments)
1464
- return void 0;
1465
- const geometryFields = fields.slice(0, signatures.length);
1466
- const numberFields = fields.slice(signatures.length).map((field) => {
1467
- if (field && !import_apache_arrow.DataType.isInt(field.type) && !import_apache_arrow.DataType.isFloat(field.type))
1468
- throw new Error(`${name} requires numeric arguments`);
1469
- return field ?? new import_apache_arrow.Field("number", new import_apache_arrow.Float64(), true);
1470
- });
1471
- const extensions = geometryFields.map((field, index) => {
1472
- if (!field)
1473
- return void 0;
1474
- const extension = (0, import_arrow3.getGeoArrowFieldInfo)(field);
1475
- const encoding = extension == null ? void 0 : extension.encoding;
1476
- const kinds = signatures[index];
1477
- if (encoding === "geoarrow.wkb" && (import_apache_arrow.DataType.isBinary(field.type) || import_apache_arrow.DataType.isLargeBinary(field.type))) {
1478
- } else if (encoding === "geoarrow.geometry" && extension.dimension === "xy") {
1479
- } else if (kinds.some((kind) => encoding === "geoarrow." + kind.toLowerCase())) {
1480
- if (!allDimensions && (extension == null ? void 0 : extension.dimension) !== "xy")
1481
- throw new Error(`${name} requires 2D geometry`);
1482
- } else {
1483
- throw new Error(`${name} argument ${index + 1} requires GeoArrow ${kinds.join(" or ")}`);
1484
- }
1485
- validateCRS == null ? void 0 : validateCRS(extension == null ? void 0 : extension.metadata["crs"], name);
1486
- if (!validateCRS && name.startsWith("ST_") && name !== "ST_SRID" && name !== "ST_SetSRID" && (extension == null ? void 0 : extension.metadata["edges"]) === "spherical")
1487
- throw new Error(`${name} requires planar geometry`);
1488
- return extension;
1489
- });
1490
- const crsValues = extensions.map((extension) => extension == null ? void 0 : extension.metadata["crs"]).filter((crs) => crs !== void 0 && crs !== null);
1491
- if (!validateCRS && name.startsWith("ST_") && crsValues.some((crs) => JSON.stringify(crs) !== JSON.stringify(crsValues[0]))) {
1492
- throw new Error(`${name} requires arguments in the same CRS`);
1493
- }
1494
- const metadata = /* @__PURE__ */ new Map();
1495
- if ("encoding" in output || import_apache_arrow.DataType.isBinary(type)) {
1496
- metadata.set(EXTENSION_NAME, "encoding" in output ? output.encoding : "geoarrow.wkb");
1497
- const inputMetadata = (_a = extensions[0]) == null ? void 0 : _a.metadata;
1498
- const crs = inputMetadata == null ? void 0 : inputMetadata["crs"];
1499
- const crsType = crs === void 0 ? void 0 : inputMetadata == null ? void 0 : inputMetadata["crs_type"];
1500
- const edges2 = inputMetadata == null ? void 0 : inputMetadata["edges"];
1501
- if (crs !== void 0 || edges2 !== void 0) {
1502
- metadata.set(EXTENSION_METADATA, JSON.stringify({ crs, crs_type: crsType, edges: edges2 }));
1503
- }
1504
- }
1505
- const arguments_ = [
1506
- ...geometryFields.map((field) => field ?? new import_apache_arrow.Field("geometry", new import_apache_arrow.Binary(), true)),
1507
- ...numberFields
1508
- ];
1509
- return {
1510
- arguments: arguments_,
1511
- nullHandling: skipNullGeometries ? "call" : "propagate",
1512
- result: new import_apache_arrow.Field(name, type, true, metadata),
1513
- /** Evaluates active rows and retains their positions in the output batch. */
1514
- evaluate(vectors, { activeRows, length: rowCount }) {
1515
- const numbers = vectors.slice(signatures.length);
1516
- const readers = vectors.slice(0, signatures.length).map((vector, index) => readGeometryValue(vector, arguments_[index], activeRows, allDimensions ? (g, dimension, members) => ({ ...g, dimension, members }) : planarGeometry, name === "ST_GeometryN"));
1517
- const values = new Array(rowCount).fill(null);
1518
- for (let row = 0; row < rowCount; row++) {
1519
- if (!activeRows[row])
1520
- continue;
1521
- const geometries = [];
1522
- for (let index = 0; index < readers.length; index++) {
1523
- if (skipNullGeometries && !vectors[index].isValid(row))
1524
- continue;
1525
- const geometry = readers[index](row);
1526
- if (!signatures[index].includes(geometry.type))
1527
- throw new Error(`${name} argument ${index + 1} does not support ${geometry.type} at row ${row}`);
1528
- geometries.push(geometry);
1529
- }
1530
- values[row] = evaluate(geometries, ...numbers.map((vector) => Number(vector.get(row))));
1531
- }
1532
- return "encoding" in output ? output.build(values) : (0, import_apache_arrow.vectorFromArray)(values, output);
1533
- }
1534
- };
1535
- }
1536
- };
1551
+ function preservesNesting(before, after) {
1552
+ const rings = before.map((original, index) => ({
1553
+ original,
1554
+ simplified: after[index],
1555
+ bounds: planarBounds({ type: "LineString", coordinates: original })
1556
+ }));
1557
+ return !(0, import_processing.anyBoundsOverlap)(rings, (a, b) => contains(a.original, b.original) !== contains(a.simplified, b.simplified) || contains(b.original, a.original) !== contains(b.simplified, a.simplified));
1537
1558
  }
1538
- function pointCoordinates(geometry) {
1539
- return geometry.type === "Point" && Number.isFinite(geometry.coordinates[0]) && Number.isFinite(geometry.coordinates[1]) ? geometry.coordinates : null;
1559
+ function simplifyRing(ring, tolerance) {
1560
+ const reduced = simplifyLine(ring, tolerance);
1561
+ if (reduced.length < 4 || reduced.length === ring.length)
1562
+ return ring;
1563
+ const before = signedArea(ring);
1564
+ const after = signedArea(reduced);
1565
+ return Number.isFinite(before) && Number.isFinite(after) && after && Math.sign(before) === Math.sign(after) ? reduced : ring;
1540
1566
  }
1541
- function column(geometry) {
1542
- return (0, import_arrow3.makeGeoArrowColumnFromGeometryRows)([geometry], { dimension: "xy" });
1567
+ function simplifyPolygonTopology(geometry, tolerance) {
1568
+ if (!Number.isFinite(tolerance) || tolerance < 0)
1569
+ throw new Error("Expected a finite nonnegative tolerance");
1570
+ if (!tolerance)
1571
+ return geometry;
1572
+ const polygons3 = geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
1573
+ const before = polygons3.flat();
1574
+ const reduced = polygons3.map((polygon) => polygon.map((ring) => simplifyRing(ring, tolerance)));
1575
+ const after = reduced.flat();
1576
+ if (before.every((ring, index) => ring === after[index]))
1577
+ return geometry;
1578
+ if (!separatedBoundaries(before) || !separatedBoundaries(after) || !preservesNesting(before, after))
1579
+ return geometry;
1580
+ return geometry.type === "Polygon" ? { type: "Polygon", coordinates: reduced[0] } : { type: "MultiPolygon", coordinates: reduced };
1543
1581
  }
1544
- function scalar2(result2) {
1545
- return result2.validity[0] & 1 ? result2.values[0] : null;
1582
+
1583
+ // dist/geometry-constructors.js
1584
+ function collectPair(a, b) {
1585
+ if (a.type === "Point" && b.type === "Point")
1586
+ return { type: "MultiPoint", coordinates: [a.coordinates, b.coordinates] };
1587
+ if (a.type === "LineString" && b.type === "LineString")
1588
+ return { type: "MultiLineString", coordinates: [a.coordinates, b.coordinates] };
1589
+ if (a.type === "Polygon" && b.type === "Polygon")
1590
+ return { type: "MultiPolygon", coordinates: [a.coordinates, b.coordinates] };
1591
+ return { type: "GeometryCollection", geometries: [a, b] };
1546
1592
  }
1547
- function pointInPolygon(point2, polygon, ignoreBoundary = false) {
1548
- if (!pointCoordinates(point2))
1549
- return null;
1550
- const value = scalar2(booleanPointInPolygon(column(point2), column(polygon), { ignoreBoundary }));
1551
- return value === null ? null : value === 1;
1593
+ function makeLine(parts) {
1594
+ const coordinates = [];
1595
+ for (const part of parts) {
1596
+ if (part.type === "Point") {
1597
+ if (part.coordinates.length)
1598
+ coordinates.push(part.coordinates);
1599
+ } else if (part.type === "MultiPoint") {
1600
+ for (const point2 of part.coordinates)
1601
+ if (point2.length && !point2.every(Number.isNaN))
1602
+ coordinates.push(point2);
1603
+ } else if (part.type === "LineString") {
1604
+ const previous = coordinates[coordinates.length - 1];
1605
+ const first = part.coordinates[0];
1606
+ const shared = previous && first && previous[0] === first[0] && previous[1] === first[1];
1607
+ for (let i = shared ? 1 : 0; i < part.coordinates.length; i++)
1608
+ coordinates.push(part.coordinates[i]);
1609
+ }
1610
+ }
1611
+ return { type: "LineString", coordinates };
1552
1612
  }
1553
1613
 
1554
1614
  // dist/st-geodesic-functions.js
@@ -3014,29 +3074,152 @@ function createGeodesicEngine({ semiMajorAxis: a, semiMinorAxis: b }) {
3014
3074
 
3015
3075
  // dist/st-geodesic-functions.js
3016
3076
  var kernel;
3017
- function meters(a, b) {
3077
+ function getKernel() {
3018
3078
  kernel ?? (kernel = new EllipsoidGeodesic({
3019
3079
  semiMajorAxis: WGS84_RADIUS_X,
3020
3080
  semiMinorAxis: WGS84_RADIUS_Z
3021
3081
  }));
3022
- return kernel.inverse(a[1], a[0], b[1], b[0]).s12;
3082
+ return kernel;
3083
+ }
3084
+ function meters(a, b) {
3085
+ return getKernel().inverse(a[1], a[0], b[1], b[0]).s12;
3023
3086
  }
3024
3087
  function emptyPoint(coordinate) {
3025
3088
  return !coordinate.length || coordinate.every(Number.isNaN);
3026
3089
  }
3027
- function pointDistance(a, b) {
3028
- if (a.type !== "Point" || b.type !== "Point")
3029
- throw new Error("Expected geodesic point pair");
3030
- return emptyPoint(a.coordinates) || emptyPoint(b.coordinates) ? null : meters(a.coordinates, b.coordinates);
3090
+ var pointSetKinds = ["Point", "MultiPoint"];
3091
+ function pointSet(geometry) {
3092
+ if (geometry.type === "Point")
3093
+ return [geometry.coordinates];
3094
+ if (geometry.type === "MultiPoint")
3095
+ return geometry.coordinates;
3096
+ throw new Error("Expected Point or MultiPoint");
3097
+ }
3098
+ function pointSetDistance(a, b, stopAt = 0) {
3099
+ const left = pointSet(a);
3100
+ const points2 = pointSet(b);
3101
+ const right = points2.some(emptyPoint) ? points2.filter((point2) => !emptyPoint(point2)) : points2;
3102
+ let minimum = Infinity;
3103
+ for (const x of left) {
3104
+ if (emptyPoint(x))
3105
+ continue;
3106
+ for (const y of right) {
3107
+ const distance = meters(x, y);
3108
+ if (distance <= stopAt)
3109
+ return distance;
3110
+ minimum = Math.min(minimum, distance);
3111
+ }
3112
+ }
3113
+ return minimum === Infinity ? null : minimum;
3114
+ }
3115
+ function isPointSet(geometry) {
3116
+ return geometry.type === "Point" || geometry.type === "MultiPoint";
3117
+ }
3118
+ function paths2(geometry) {
3119
+ if (geometry.type === "LineString")
3120
+ return [geometry.coordinates];
3121
+ if (geometry.type === "MultiLineString")
3122
+ return geometry.coordinates;
3123
+ throw new Error("Expected geodesic line geometry");
3031
3124
  }
3032
3125
  function lineLength(geometry) {
3033
- const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.type === "MultiLineString" ? geometry.coordinates : [];
3034
3126
  let length = 0;
3035
- for (const path of lines)
3127
+ for (const path of paths2(geometry))
3036
3128
  for (let index = 1; index < path.length; index++)
3037
3129
  length += meters(path[index - 1], path[index]);
3038
3130
  return length;
3039
3131
  }
3132
+ var MAX_SEARCH_INTERVAL = 1e6;
3133
+ var SEARCH_TOLERANCE = 1e-7;
3134
+ var GOLDEN_RATIO = (Math.sqrt(5) - 1) / 2;
3135
+ function distanceAt(line, offset, point2) {
3136
+ const position = line.position(offset);
3137
+ return getKernel().inverse(position.lat2, position.lon2, point2[1], point2[0]).s12;
3138
+ }
3139
+ function minimizeDistance(line, point2, lo, hi, threshold) {
3140
+ let a = hi - GOLDEN_RATIO * (hi - lo);
3141
+ let b = lo + GOLDEN_RATIO * (hi - lo);
3142
+ let da = distanceAt(line, a, point2);
3143
+ let db = distanceAt(line, b, point2);
3144
+ while (hi - lo > SEARCH_TOLERANCE && Math.min(da, db) > threshold) {
3145
+ if (da <= db) {
3146
+ hi = b;
3147
+ b = a;
3148
+ db = da;
3149
+ a = hi - GOLDEN_RATIO * (hi - lo);
3150
+ da = distanceAt(line, a, point2);
3151
+ } else {
3152
+ lo = a;
3153
+ a = b;
3154
+ da = db;
3155
+ b = lo + GOLDEN_RATIO * (hi - lo);
3156
+ db = distanceAt(line, b, point2);
3157
+ }
3158
+ }
3159
+ return Math.min(da, db);
3160
+ }
3161
+ function intervalLowerBound(start, end, length) {
3162
+ return (start + end - length) / 2;
3163
+ }
3164
+ function segmentDistance(a, b, point2, startDistance, endDistance, best, threshold) {
3165
+ const limit = threshold >= 0 ? threshold : best;
3166
+ const solver = getKernel();
3167
+ const { s12: length, azi1 } = solver.inverse(a[1], a[0], b[1], b[0]);
3168
+ if (length === 0 || intervalLowerBound(startDistance, endDistance, length) > limit)
3169
+ return best;
3170
+ const line = solver.line(a[1], a[0], azi1);
3171
+ const count = Math.ceil(length / MAX_SEARCH_INTERVAL);
3172
+ let start = 0;
3173
+ for (let interval = 1; interval <= count; interval++) {
3174
+ const end = interval * length / count;
3175
+ const distance = interval === count ? endDistance : distanceAt(line, end, point2);
3176
+ best = Math.min(best, distance);
3177
+ if (intervalLowerBound(startDistance, distance, end - start) <= Math.min(limit, best)) {
3178
+ best = Math.min(best, minimizeDistance(line, point2, start, end, threshold));
3179
+ }
3180
+ if (best <= threshold)
3181
+ break;
3182
+ start = end;
3183
+ startDistance = distance;
3184
+ }
3185
+ return best;
3186
+ }
3187
+ function routeDistance(route, point2, threshold) {
3188
+ let best = Infinity;
3189
+ for (const path of paths2(route)) {
3190
+ if (!path.length)
3191
+ continue;
3192
+ let previous = meters(path[0], point2);
3193
+ best = Math.min(previous, best);
3194
+ if (best <= threshold)
3195
+ return best;
3196
+ for (let vertex = 1; vertex < path.length; vertex++) {
3197
+ const distance = meters(path[vertex], point2);
3198
+ best = Math.min(distance, best);
3199
+ if (best <= threshold)
3200
+ return best;
3201
+ best = segmentDistance(path[vertex - 1], path[vertex], point2, previous, distance, best, threshold);
3202
+ if (best <= threshold)
3203
+ return best;
3204
+ previous = distance;
3205
+ }
3206
+ }
3207
+ return Number.isFinite(best) ? best : null;
3208
+ }
3209
+ function proximityDistance(a, b, threshold = -1) {
3210
+ if (isPointSet(a) && isPointSet(b)) {
3211
+ return pointSetDistance(a, b, Math.max(0, threshold));
3212
+ }
3213
+ const point2 = a.type === "Point" ? a : b;
3214
+ if (point2.type !== "Point")
3215
+ throw new Error("Geodesic proximity requires at least one Point");
3216
+ const other = a.type === "Point" ? b : a;
3217
+ if (emptyPoint(point2.coordinates))
3218
+ return null;
3219
+ if (other.type !== "LineString" && other.type !== "MultiLineString")
3220
+ throw new Error("Expected a Point or MultiPoint pair, or a Point paired with a route");
3221
+ return routeDistance(other, point2.coordinates, threshold);
3222
+ }
3040
3223
  function isWGS84(crs) {
3041
3224
  if (typeof crs === "string") {
3042
3225
  const identifier = normalizeCRSIdentifier(crs);
@@ -3051,11 +3234,12 @@ function validateWGS84(crs, name) {
3051
3234
  if (!isWGS84(crs))
3052
3235
  throw new Error(`${name} requires WGS84 CRS metadata (EPSG:4326 or OGC:CRS84)`);
3053
3236
  }
3237
+ var proximityKinds = [...pointSetKinds, ...lineKinds];
3054
3238
  var ST_GEODESICDISTANCE = /* @__PURE__ */ spatialFunction(
3055
3239
  "ST_GeodesicDistance",
3056
- [pointKinds, pointKinds],
3240
+ [proximityKinds, proximityKinds],
3057
3241
  /* @__PURE__ */ new import_apache_arrow2.Float64(),
3058
- ([a, b]) => pointDistance(a, b),
3242
+ ([a, b]) => proximityDistance(a, b),
3059
3243
  0,
3060
3244
  true,
3061
3245
  false,
@@ -3073,58 +3257,271 @@ var ST_GEODESICLENGTH = /* @__PURE__ */ spatialFunction(
3073
3257
  );
3074
3258
  var ST_GEODESICDWITHIN = /* @__PURE__ */ spatialFunction(
3075
3259
  "ST_GeodesicDWithin",
3076
- [pointKinds, pointKinds],
3260
+ [proximityKinds, proximityKinds],
3077
3261
  /* @__PURE__ */ new import_apache_arrow2.Bool(),
3078
3262
  ([a, b], radius) => {
3079
3263
  if (!Number.isFinite(radius) || radius < 0)
3080
3264
  throw new Error("ST_GeodesicDWithin requires a finite nonnegative radius in meters");
3081
- const distance = pointDistance(a, b);
3082
- return distance !== null && distance <= radius;
3265
+ const limit = isPointSet(a) && isPointSet(b) ? radius : radius + SEARCH_TOLERANCE;
3266
+ const distance = proximityDistance(a, b, limit);
3267
+ return distance !== null && distance <= limit;
3083
3268
  },
3084
3269
  1,
3085
3270
  true,
3086
3271
  false,
3087
3272
  validateWGS84
3088
3273
  );
3274
+ function ellipsoidalRouteSegment(a, b) {
3275
+ const solver = getKernel();
3276
+ const { s12: length, azi1 } = solver.inverse(a[1], a[0], b[1], b[0]);
3277
+ let line;
3278
+ return {
3279
+ length,
3280
+ /** Samples the geodesic at a fraction of its total length. */
3281
+ interpolate(fraction) {
3282
+ line ?? (line = solver.line(a[1], a[0], azi1));
3283
+ const { lon2, lat2 } = line.position(length * fraction);
3284
+ return [lon2, lat2];
3285
+ }
3286
+ };
3287
+ }
3288
+ var ST_GEODESICSEGMENTIZE = /* @__PURE__ */ segmentizeFunction("ST_GeodesicSegmentize", ellipsoidalRouteSegment, validateWGS84);
3089
3289
  var GEODESIC_SPATIAL_FUNCTIONS = /* @__PURE__ */ Object.freeze([
3090
3290
  ST_GEODESICDISTANCE,
3091
3291
  ST_GEODESICLENGTH,
3092
- ST_GEODESICDWITHIN
3292
+ ST_GEODESICDWITHIN,
3293
+ ST_GEODESICSEGMENTIZE
3093
3294
  ]);
3094
3295
 
3296
+ // dist/st-coverage-functions.js
3297
+ var import_apache_arrow3 = require("apache-arrow");
3298
+ var import_arrow6 = require("@math.gl/core/arrow");
3299
+
3300
+ // dist/coverage-simplification.js
3301
+ var import_spatial_index2 = require("@math.gl/geometry/spatial-index");
3302
+ var import_robust_predicates2 = require("robust-predicates");
3303
+ function key(point2) {
3304
+ return `${point2[0]}/${point2[1]}`;
3305
+ }
3306
+ function same(a, b) {
3307
+ return a[0] === b[0] && a[1] === b[1];
3308
+ }
3309
+ function bounds(points2) {
3310
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
3311
+ for (const [x, y] of points2) {
3312
+ x0 = Math.min(x0, x);
3313
+ y0 = Math.min(y0, y);
3314
+ x1 = Math.max(x1, x);
3315
+ y1 = Math.max(y1, y);
3316
+ }
3317
+ return [x0, y0, x1, y1];
3318
+ }
3319
+ function search(index, points2) {
3320
+ const [x0, y0, x1, y1] = bounds(points2);
3321
+ return index.search([x0, y0], [x1, y1]);
3322
+ }
3323
+ function side(a, b, c) {
3324
+ return Math.sign((0, import_robust_predicates2.orient2d)(a[0], a[1], b[0], b[1], c[0], c[1]));
3325
+ }
3326
+ function strictlyInside(p, [a, b, c]) {
3327
+ const x = side(a, b, p);
3328
+ return x !== 0 && x === side(b, c, p) && x === side(c, a, p);
3329
+ }
3330
+ function conflicts([a, b], [c, d]) {
3331
+ if (!(0, import_polygon2.segmentsMeet)(a, b, c, d))
3332
+ return false;
3333
+ if (!(same(a, c) || same(a, d) || same(b, c) || same(b, d)))
3334
+ return true;
3335
+ return !same(a, c) && !same(a, d) && (0, import_polygon2.pointOnSegment)(a, c, d) || !same(b, c) && !same(b, d) && (0, import_polygon2.pointOnSegment)(b, c, d) || !same(c, a) && !same(c, b) && (0, import_polygon2.pointOnSegment)(c, a, b) || !same(d, a) && !same(d, b) && (0, import_polygon2.pointOnSegment)(d, a, b) || same(a, c) && same(b, d) || same(a, d) && same(b, c);
3336
+ }
3337
+ function obstructs(edge, triangle) {
3338
+ const [a, b, c] = triangle;
3339
+ const [x, y] = edge;
3340
+ if (same(x, b) && (same(y, a) || same(y, c)) || same(y, b) && (same(x, a) || same(x, c)))
3341
+ return false;
3342
+ return strictlyInside(x, triangle) || strictlyInside(y, triangle) || conflicts(edge, [a, b]) || conflicts(edge, [b, c]) || conflicts(edge, [a, c]);
3343
+ }
3344
+ function neighbor({ ring, index }, delta) {
3345
+ return ring.points[(index + delta + ring.points.length) % ring.points.length];
3346
+ }
3347
+ function candidate(owners, tolerance) {
3348
+ if (owners.length !== 2)
3349
+ return void 0;
3350
+ const [left, right] = owners;
3351
+ if (left.ring.row === right.ring.row || left.ring.points.length <= 3 || right.ring.points.length <= 3)
3352
+ return void 0;
3353
+ const a = neighbor(left, -1);
3354
+ const b = neighbor(left, 0);
3355
+ const c = neighbor(left, 1);
3356
+ const x = neighbor(right, -1);
3357
+ const y = neighbor(right, 1);
3358
+ if (same(a, c) || !(same(a, x) && same(c, y) || same(a, y) && same(c, x)))
3359
+ return void 0;
3360
+ if (!(distanceToPlanarSegment(b, a, c) <= tolerance))
3361
+ return void 0;
3362
+ return { triangle: [a, b, c], pair: [left, right] };
3363
+ }
3364
+ function simplifyCoverage(rows2, tolerance, signal) {
3365
+ if (!tolerance)
3366
+ return rows2;
3367
+ const occurrences = /* @__PURE__ */ new Map();
3368
+ const boundaries = [];
3369
+ const shapes = rows2.map((geometry, row) => {
3370
+ signal == null ? void 0 : signal.throwIfAborted();
3371
+ if (!geometry)
3372
+ return null;
3373
+ const polygons3 = geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
3374
+ return polygons3.map((polygon) => polygon.map((closed) => {
3375
+ if (closed.length < 4 || !same(closed[0], closed[closed.length - 1]))
3376
+ throw new Error("ST_CoverageSimplify requires closed polygon rings");
3377
+ const points2 = closed.slice(0, -1);
3378
+ const ring = { row, points: points2, removed: /* @__PURE__ */ new Set() };
3379
+ points2.forEach((point2, index) => {
3380
+ if (!Number.isFinite(point2[0]) || !Number.isFinite(point2[1]))
3381
+ throw new Error("ST_CoverageSimplify requires finite coordinates");
3382
+ const id = key(point2);
3383
+ const previous = occurrences.get(id);
3384
+ const owner = { ring, index };
3385
+ if (previous)
3386
+ previous.push(owner);
3387
+ else
3388
+ occurrences.set(id, [owner]);
3389
+ boundaries.push([point2, points2[(index + 1) % points2.length]]);
3390
+ });
3391
+ return ring;
3392
+ }));
3393
+ });
3394
+ const candidates = [...occurrences.values()].flatMap((owners) => {
3395
+ const edit = candidate(owners, tolerance);
3396
+ return edit ? [edit] : [];
3397
+ });
3398
+ if (!candidates.length)
3399
+ return rows2;
3400
+ const original = new import_spatial_index2.BoxIndex({ dimension: 2, bounds: boundaries.flatMap(bounds) });
3401
+ const edits = new import_spatial_index2.BoxIndex({
3402
+ dimension: 2,
3403
+ bounds: candidates.flatMap((edit) => bounds(edit.triangle))
3404
+ });
3405
+ const accepted = /* @__PURE__ */ new Set();
3406
+ const protectedVertices = /* @__PURE__ */ new Set();
3407
+ candidates.forEach(({ triangle, pair }, index) => {
3408
+ signal == null ? void 0 : signal.throwIfAborted();
3409
+ const [a, b, c] = triangle;
3410
+ if (protectedVertices.has(key(b)) || pair.some(({ ring }) => ring.points.length - ring.removed.size <= 3))
3411
+ return;
3412
+ if (search(original, triangle).some((hit) => obstructs(boundaries[hit], triangle)))
3413
+ return;
3414
+ if (search(edits, triangle).some((hit) => accepted.has(hit)))
3415
+ return;
3416
+ accepted.add(index);
3417
+ protectedVertices.add(key(a));
3418
+ protectedVertices.add(key(c));
3419
+ for (const { ring, index: position } of pair)
3420
+ ring.removed.add(position);
3421
+ });
3422
+ if (!accepted.size)
3423
+ return rows2;
3424
+ return shapes.map((shape, row) => {
3425
+ const geometry = rows2[row];
3426
+ if (!geometry || !shape)
3427
+ return null;
3428
+ const coordinates = shape.map((polygon) => polygon.map(({ points: points2, removed }) => {
3429
+ const path = points2.filter((_, index) => !removed.has(index));
3430
+ return [...path, path[0]];
3431
+ }));
3432
+ return geometry.type === "Polygon" ? { type: "Polygon", coordinates: coordinates[0] } : { type: "MultiPolygon", coordinates };
3433
+ });
3434
+ }
3435
+
3436
+ // dist/st-coverage-functions.js
3437
+ function createSTCoverageSimplify({ geometry, tolerance }) {
3438
+ if (!Number.isFinite(tolerance) || tolerance < 0)
3439
+ throw new Error("ST_CoverageSimplify requires a finite nonnegative tolerance");
3440
+ return {
3441
+ kind: "table",
3442
+ name: "ST_CoverageSimplify",
3443
+ /** Binds one native 2D polygon field and a stable output schema. */
3444
+ bind(inputSchema) {
3445
+ const index = inputSchema.fields.findIndex((field2) => field2.name === geometry);
3446
+ const field = inputSchema.fields[index];
3447
+ const info = field && (0, import_arrow6.getGeoArrowFieldInfo)(field);
3448
+ const encoding = info == null ? void 0 : info.encoding;
3449
+ if (!field || encoding !== "geoarrow.polygon" && encoding !== "geoarrow.multipolygon" || info.dimension !== "xy" || info.metadata["edges"] === "spherical")
3450
+ throw new Error("ST_CoverageSimplify requires a native planar XY Polygon or MultiPolygon column");
3451
+ const output = nativeGeometryResult(encoding);
3452
+ const fields = inputSchema.fields.slice();
3453
+ fields[index] = field.clone({ type: output.type });
3454
+ const outputSchema = new import_apache_arrow3.Schema(fields, inputSchema.metadata, void 0, inputSchema.metadataVersion);
3455
+ return {
3456
+ outputSchema,
3457
+ /** Simplifies shared boundaries across batches while preserving row alignment. */
3458
+ evaluate(input, { signal }) {
3459
+ signal == null ? void 0 : signal.throwIfAborted();
3460
+ if (!input.numRows)
3461
+ return new import_apache_arrow3.Table(outputSchema, []);
3462
+ const vector = input.getChildAt(index);
3463
+ const column2 = (0, import_arrow6.makeGeoArrowColumnFromArrowVector)(vector, { field });
3464
+ const rows2 = (0, import_arrow6.materializeGeoArrowRows)(column2);
3465
+ const result2 = simplifyCoverage(rows2, tolerance, signal);
3466
+ let first = 0;
3467
+ const type = new import_apache_arrow3.Struct(fields);
3468
+ const batches = input.batches.map((batch) => {
3469
+ signal == null ? void 0 : signal.throwIfAborted();
3470
+ const children = batch.data.children.slice();
3471
+ children[index] = output.build(result2.slice(first, first + batch.numRows)).data[0];
3472
+ first += batch.numRows;
3473
+ const data = new import_apache_arrow3.Data(type, 0, batch.numRows, 0, void 0, children);
3474
+ return (0, import_arrow6.createRecordBatchWithMetadata)(outputSchema, data, (0, import_arrow6.getRecordBatchMetadata)(batch));
3475
+ });
3476
+ return new import_apache_arrow3.Table(outputSchema, batches);
3477
+ }
3478
+ };
3479
+ }
3480
+ };
3481
+ }
3482
+
3095
3483
  // dist/st-functions.js
3096
3484
  var ST_MAKEPOINT = {
3097
3485
  kind: "scalar",
3098
3486
  name: "ST_MakePoint",
3099
3487
  prototypes: [],
3100
- /** Binds two to four numeric ordinate fields and declares a WKB result. */
3488
+ /** Binds two to four numeric ordinates to a native GeoArrow point. */
3101
3489
  resolvePrototype(fields) {
3102
3490
  if (fields.length < 2 || fields.length > 4)
3103
3491
  return void 0;
3104
3492
  const arguments_ = fields.map((field) => {
3105
- if (field && !import_apache_arrow3.DataType.isInt(field.type) && !import_apache_arrow3.DataType.isFloat(field.type))
3493
+ if (field && !import_apache_arrow4.DataType.isInt(field.type) && !import_apache_arrow4.DataType.isFloat(field.type))
3106
3494
  throw new Error("ST_MakePoint requires numeric coordinates");
3107
- return field ?? new import_apache_arrow3.Field("coordinate", new import_apache_arrow3.Float64(), true);
3495
+ return field ?? new import_apache_arrow4.Field("coordinate", new import_apache_arrow4.Float64(), true);
3108
3496
  });
3109
- const type = new import_apache_arrow3.Binary();
3497
+ const dimension = fields.length === 2 ? "xy" : fields.length === 3 ? "xyz" : "xyzm";
3498
+ const coordinateType = new import_apache_arrow4.Float64();
3499
+ const size = fields.length;
3500
+ const type = new import_apache_arrow4.FixedSizeList(size, new import_apache_arrow4.Field(dimension, coordinateType, true));
3110
3501
  return {
3111
3502
  arguments: arguments_,
3112
- result: new import_apache_arrow3.Field("ST_MakePoint", type, true, /* @__PURE__ */ new Map([[EXTENSION_NAME, "geoarrow.wkb"]])),
3113
- /** Writes one point per active row, retaining nulls in all other rows. */
3503
+ result: new import_apache_arrow4.Field("ST_MakePoint", type, true, /* @__PURE__ */ new Map([[EXTENSION_NAME, "geoarrow.point"]])),
3504
+ /** Writes active rows directly to the interleaved coordinate buffer. */
3114
3505
  evaluate(vectors, { activeRows, length }) {
3115
- const values = new Array(length).fill(null);
3506
+ const data = new Float64Array(length * size);
3507
+ const nullBitmap = new Uint8Array(Math.ceil(length / 8));
3508
+ let nullCount = 0;
3116
3509
  for (let row = 0; row < length; row++) {
3117
- if (activeRows[row]) {
3118
- const coordinates = vectors.map((vector) => Number(vector.get(row)));
3119
- values[row] = (0, import_arrow4.writeWKB)({ type: "Point", coordinates });
3510
+ if (!activeRows[row]) {
3511
+ nullCount++;
3512
+ continue;
3513
+ }
3514
+ nullBitmap[row >> 3] |= 1 << (row & 7);
3515
+ for (let coordinate = 0; coordinate < size; coordinate++) {
3516
+ data[row * size + coordinate] = Number(vectors[coordinate].get(row));
3120
3517
  }
3121
3518
  }
3122
- return (0, import_apache_arrow3.vectorFromArray)(values, type);
3519
+ return nativePointVector(type, data, nullBitmap, nullCount);
3123
3520
  }
3124
3521
  };
3125
3522
  }
3126
3523
  };
3127
- function tileEnvelope(zoom, x, y, bounds, margin) {
3524
+ function tileEnvelope(zoom, x, y, bounds2, margin) {
3128
3525
  if (!Number.isInteger(zoom) || zoom < 0 || zoom > 31)
3129
3526
  throw new Error("ST_TileEnvelope zoom must be an integer in [0,31]");
3130
3527
  const count = 2 ** zoom;
@@ -3132,7 +3529,7 @@ function tileEnvelope(zoom, x, y, bounds, margin) {
3132
3529
  throw new Error("ST_TileEnvelope tile index outside zoom level");
3133
3530
  if (!Number.isFinite(margin) || margin < -0.5)
3134
3531
  throw new Error("Invalid ST_TileEnvelope margin");
3135
- const [west, south, east, north] = bounds;
3532
+ const [west, south, east, north] = bounds2;
3136
3533
  const width = (east - west) / count, height = (north - south) / count;
3137
3534
  if (!(width > 0 && height > 0 && Number.isFinite(width) && Number.isFinite(height)))
3138
3535
  throw new Error("ST_TileEnvelope requires nondegenerate bounds");
@@ -3141,7 +3538,7 @@ function tileEnvelope(zoom, x, y, bounds, margin) {
3141
3538
  const right = fullWidth ? east : Math.min(east, west + (x + 1 + margin) * width);
3142
3539
  const bottom = Math.max(south, north - (y + 1 + margin) * height);
3143
3540
  const top = Math.min(north, north - (y - margin) * height);
3144
- return (0, import_arrow4.writeWKB)({
3541
+ return (0, import_arrow7.writeWKB)({
3145
3542
  type: "Polygon",
3146
3543
  coordinates: [
3147
3544
  [
@@ -3168,21 +3565,21 @@ var ST_TILEENVELOPE = {
3168
3565
  ST_ENVELOPE.resolvePrototype([root]);
3169
3566
  const args = fields.map((field, i) => {
3170
3567
  if (i === 3)
3171
- return field ?? new import_apache_arrow3.Field("bounds", new import_apache_arrow3.Binary(), true);
3172
- if (field && !import_apache_arrow3.DataType.isInt(field.type) && !import_apache_arrow3.DataType.isFloat(field.type))
3568
+ return field ?? new import_apache_arrow4.Field("bounds", new import_apache_arrow4.Binary(), true);
3569
+ if (field && !import_apache_arrow4.DataType.isInt(field.type) && !import_apache_arrow4.DataType.isFloat(field.type))
3173
3570
  throw new Error("ST_TileEnvelope requires numeric indices and margin");
3174
- return field ?? new import_apache_arrow3.Field("number", new import_apache_arrow3.Float64(), true);
3571
+ return field ?? new import_apache_arrow4.Field("number", new import_apache_arrow4.Float64(), true);
3175
3572
  });
3176
3573
  const metadata = /* @__PURE__ */ new Map([[EXTENSION_NAME, "geoarrow.wkb"]]);
3177
3574
  const crs = custom ? root == null ? void 0 : root.metadata.get(EXTENSION_METADATA) : '{"crs_type":"authority_code","crs":"EPSG:3857"}';
3178
3575
  if (crs)
3179
3576
  metadata.set(EXTENSION_METADATA, crs);
3180
- const type = new import_apache_arrow3.Binary();
3577
+ const type = new import_apache_arrow4.Binary();
3181
3578
  const r = EPSG3857_HALF_CIRCUMFERENCE;
3182
3579
  const world = [-r, -r, r, r];
3183
3580
  return {
3184
3581
  arguments: args,
3185
- result: new import_apache_arrow3.Field("ST_TileEnvelope", type, true, metadata),
3582
+ result: new import_apache_arrow4.Field("ST_TileEnvelope", type, true, metadata),
3186
3583
  /** Computes bounds for active rows using the top-left XYZ origin. */
3187
3584
  evaluate(vectors, { activeRows, length }) {
3188
3585
  const values = new Array(length).fill(null);
@@ -3190,12 +3587,12 @@ var ST_TILEENVELOPE = {
3190
3587
  for (let row = 0; row < length; row++) {
3191
3588
  if (!activeRows[row])
3192
3589
  continue;
3193
- const bounds = read ? planarBounds(read(row)) : world;
3194
- if (!bounds)
3590
+ const bounds2 = read ? planarBounds(read(row)) : world;
3591
+ if (!bounds2)
3195
3592
  throw new Error("ST_TileEnvelope requires nonempty bounds");
3196
- values[row] = tileEnvelope(Number(vectors[0].get(row)), Number(vectors[1].get(row)), Number(vectors[2].get(row)), bounds, vectors[4] ? Number(vectors[4].get(row)) : 0);
3593
+ values[row] = tileEnvelope(Number(vectors[0].get(row)), Number(vectors[1].get(row)), Number(vectors[2].get(row)), bounds2, vectors[4] ? Number(vectors[4].get(row)) : 0);
3197
3594
  }
3198
- return (0, import_apache_arrow3.vectorFromArray)(values, type);
3595
+ return (0, import_apache_arrow4.vectorFromArray)(values, type);
3199
3596
  }
3200
3597
  };
3201
3598
  }
@@ -3210,17 +3607,17 @@ function pointOrdinate(ordinate) {
3210
3607
  resolvePrototype(fields) {
3211
3608
  if (fields.length !== 1)
3212
3609
  return void 0;
3213
- const field = fields[0] ?? new import_apache_arrow3.Field("point", new import_apache_arrow3.Binary(), true, /* @__PURE__ */ new Map([[EXTENSION_NAME, "geoarrow.wkb"]]));
3214
- const extension = (0, import_arrow4.getGeoArrowFieldInfo)(field);
3610
+ const field = fields[0] ?? new import_apache_arrow4.Field("point", new import_apache_arrow4.Binary(), true, /* @__PURE__ */ new Map([[EXTENSION_NAME, "geoarrow.wkb"]]));
3611
+ const extension = (0, import_arrow7.getGeoArrowFieldInfo)(field);
3215
3612
  if ((extension == null ? void 0 : extension.metadata["edges"]) === "spherical")
3216
3613
  throw new Error(`${name} requires planar geometry`);
3217
3614
  const encoding = extension == null ? void 0 : extension.encoding;
3218
- if (encoding !== "geoarrow.point" && !(encoding === "geoarrow.wkb" && (import_apache_arrow3.DataType.isBinary(field.type) || import_apache_arrow3.DataType.isLargeBinary(field.type))))
3615
+ if (encoding !== "geoarrow.point" && !(encoding === "geoarrow.wkb" && (import_apache_arrow4.DataType.isBinary(field.type) || import_apache_arrow4.DataType.isLargeBinary(field.type))))
3219
3616
  throw new Error(`${name} requires a GeoArrow Point`);
3220
- const type = new import_apache_arrow3.Float64();
3617
+ const type = new import_apache_arrow4.Float64();
3221
3618
  return {
3222
3619
  arguments: [field],
3223
- result: new import_apache_arrow3.Field(name, type, true),
3620
+ result: new import_apache_arrow4.Field(name, type, true),
3224
3621
  /** Extracts ordinates using the WKB row or native field dimension. */
3225
3622
  evaluate([vector], { length, activeRows }) {
3226
3623
  if (encoding === "geoarrow.point") {
@@ -3228,14 +3625,14 @@ function pointOrdinate(ordinate) {
3228
3625
  const result2 = new Array(length).fill(null);
3229
3626
  const index = column2.dimension.indexOf(ordinate);
3230
3627
  if (index >= 0) {
3231
- (0, import_arrow4.visitGeoArrowCoordinates)(column2, (coordinate, row) => {
3628
+ (0, import_arrow7.visitGeoArrowCoordinates)(column2, (coordinate, row) => {
3232
3629
  if (Number.isFinite(coordinate[0]) && Number.isFinite(coordinate[1])) {
3233
3630
  result2[row] = coordinate[index] ?? null;
3234
3631
  }
3235
3632
  return coordinate;
3236
3633
  });
3237
3634
  }
3238
- return (0, import_apache_arrow3.vectorFromArray)(result2, type);
3635
+ return (0, import_apache_arrow4.vectorFromArray)(result2, type);
3239
3636
  }
3240
3637
  const read = readGeometryValue(vector, field, activeRows, (geometry, dimension) => {
3241
3638
  var _a;
@@ -3243,7 +3640,7 @@ function pointOrdinate(ordinate) {
3243
3640
  throw new Error(`${name} requires a Point`);
3244
3641
  return ((_a = pointCoordinates(geometry)) == null ? void 0 : _a[dimension.indexOf(ordinate)]) ?? null;
3245
3642
  });
3246
- return (0, import_apache_arrow3.vectorFromArray)(Array.from({ length }, (_, i) => activeRows[i] ? read(i) : null), type);
3643
+ return (0, import_apache_arrow4.vectorFromArray)(Array.from({ length }, (_, i) => activeRows[i] ? read(i) : null), type);
3247
3644
  }
3248
3645
  };
3249
3646
  }
@@ -3256,51 +3653,51 @@ var ST_M = /* @__PURE__ */ pointOrdinate("m");
3256
3653
  var ST_STARTPOINT = /* @__PURE__ */ spatialFunction(
3257
3654
  "ST_StartPoint",
3258
3655
  [["LineString"]],
3259
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3656
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3260
3657
  ([line]) => {
3261
3658
  if ((line == null ? void 0 : line.type) !== "LineString" || !line.coordinates.length)
3262
3659
  return null;
3263
- return (0, import_arrow4.writeWKB)({ type: "Point", coordinates: line.coordinates[0] }, "xy");
3660
+ return (0, import_arrow7.writeWKB)({ type: "Point", coordinates: line.coordinates[0] }, "xy");
3264
3661
  }
3265
3662
  );
3266
3663
  var ST_ENDPOINT = /* @__PURE__ */ spatialFunction(
3267
3664
  "ST_EndPoint",
3268
3665
  [["LineString"]],
3269
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3666
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3270
3667
  ([line]) => {
3271
3668
  if ((line == null ? void 0 : line.type) !== "LineString" || !line.coordinates.length)
3272
3669
  return null;
3273
- return (0, import_arrow4.writeWKB)({ type: "Point", coordinates: line.coordinates[line.coordinates.length - 1] }, "xy");
3670
+ return (0, import_arrow7.writeWKB)({ type: "Point", coordinates: line.coordinates[line.coordinates.length - 1] }, "xy");
3274
3671
  }
3275
3672
  );
3276
3673
  var ST_CONTAINS = /* @__PURE__ */ spatialFunction(
3277
3674
  "ST_Contains",
3278
3675
  [polygonKinds, pointKinds],
3279
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3676
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3280
3677
  ([polygon, point2]) => pointInPolygon(point2, polygon, true) ?? false
3281
3678
  );
3282
3679
  var ST_COVERS = /* @__PURE__ */ spatialFunction(
3283
3680
  "ST_Covers",
3284
3681
  [polygonKinds, pointKinds],
3285
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3682
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3286
3683
  ([polygon, point2]) => pointInPolygon(point2, polygon) ?? false
3287
3684
  );
3288
3685
  var ST_WITHIN = /* @__PURE__ */ spatialFunction(
3289
3686
  "ST_Within",
3290
3687
  [pointKinds, polygonKinds],
3291
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3688
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3292
3689
  ([p, polygon]) => pointInPolygon(p, polygon, true) ?? false
3293
3690
  );
3294
3691
  var ST_COVEREDBY = /* @__PURE__ */ spatialFunction(
3295
3692
  "ST_CoveredBy",
3296
3693
  [pointKinds, polygonKinds],
3297
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3694
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3298
3695
  ([p, polygon]) => pointInPolygon(p, polygon) ?? false
3299
3696
  );
3300
3697
  var ST_POINTN = /* @__PURE__ */ spatialFunction(
3301
3698
  "ST_PointN",
3302
3699
  [["LineString"]],
3303
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3700
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3304
3701
  ([line], position) => {
3305
3702
  if (!Number.isInteger(position))
3306
3703
  throw new Error("ST_PointN requires an integer position");
@@ -3308,15 +3705,15 @@ var ST_POINTN = /* @__PURE__ */ spatialFunction(
3308
3705
  return null;
3309
3706
  const index = position > 0 ? position - 1 : line.coordinates.length + position;
3310
3707
  const coordinates = line.coordinates[index];
3311
- return coordinates ? (0, import_arrow4.writeWKB)({ type: "Point", coordinates }, "xy") : null;
3708
+ return coordinates ? (0, import_arrow7.writeWKB)({ type: "Point", coordinates }, "xy") : null;
3312
3709
  },
3313
3710
  1
3314
3711
  );
3315
3712
  var ST_MAKEENVELOPE = /* @__PURE__ */ spatialFunction(
3316
3713
  "ST_MakeEnvelope",
3317
3714
  [],
3318
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3319
- (_, xmin, ymin, xmax, ymax) => (0, import_arrow4.writeWKB)({
3715
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3716
+ (_, xmin, ymin, xmax, ymax) => (0, import_arrow7.writeWKB)({
3320
3717
  type: "Polygon",
3321
3718
  coordinates: [
3322
3719
  [
@@ -3333,7 +3730,7 @@ var ST_MAKEENVELOPE = /* @__PURE__ */ spatialFunction(
3333
3730
  var ST_DISTANCE = /* @__PURE__ */ spatialFunction(
3334
3731
  "ST_Distance",
3335
3732
  [pointKinds, pointKinds],
3336
- /* @__PURE__ */ new import_apache_arrow3.Float64(),
3733
+ /* @__PURE__ */ new import_apache_arrow4.Float64(),
3337
3734
  ([a, b]) => {
3338
3735
  const p = pointCoordinates(a);
3339
3736
  const q = pointCoordinates(b);
@@ -3362,22 +3759,22 @@ function closestPair(a, b) {
3362
3759
  var ST_CLOSESTPOINT = /* @__PURE__ */ spatialFunction(
3363
3760
  "ST_ClosestPoint",
3364
3761
  [routePointKinds, routePointKinds],
3365
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3762
+ /* @__PURE__ */ nativeGeometryResult("geoarrow.point"),
3366
3763
  ([a, b]) => {
3367
3764
  const pair = closestPair(a, b);
3368
- return pair ? (0, import_arrow4.writeWKB)({ type: "Point", coordinates: pair.start }, "xy") : null;
3765
+ return pair ? { type: "Point", coordinates: pair.start } : null;
3369
3766
  }
3370
3767
  );
3371
3768
  var ST_SHORTESTLINE = /* @__PURE__ */ spatialFunction(
3372
3769
  "ST_ShortestLine",
3373
3770
  [routePointKinds, routePointKinds],
3374
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3771
+ /* @__PURE__ */ nativeGeometryResult("geoarrow.linestring"),
3375
3772
  ([a, b]) => {
3376
3773
  const pair = closestPair(a, b);
3377
- return pair ? (0, import_arrow4.writeWKB)({ type: "LineString", coordinates: [pair.start, pair.end] }, "xy") : null;
3774
+ return pair ? { type: "LineString", coordinates: [pair.start, pair.end] } : null;
3378
3775
  }
3379
3776
  );
3380
- var proximityKinds = [...pointKinds, ...lineKinds, ...polygonKinds];
3777
+ var proximityKinds2 = [...pointKinds, ...lineKinds, ...polygonKinds];
3381
3778
  function withinDistance(a, b, radius) {
3382
3779
  if (radius < 0)
3383
3780
  throw new Error("ST_DWithin distance must be nonnegative");
@@ -3396,7 +3793,7 @@ function withinDistance(a, b, radius) {
3396
3793
  throw new Error(`ST_DWithin does not support ${a.type} and ${b.type}`);
3397
3794
  }
3398
3795
  function makeDWithin() {
3399
- const spatial = spatialFunction("ST_DWithin", [proximityKinds, proximityKinds], new import_apache_arrow3.Bool(), ([a, b], radius) => withinDistance(a, b, radius), 1);
3796
+ const spatial = spatialFunction("ST_DWithin", [proximityKinds2, proximityKinds2], new import_apache_arrow4.Bool(), ([a, b], radius) => withinDistance(a, b, radius), 1);
3400
3797
  return {
3401
3798
  ...spatial,
3402
3799
  /** Checks concrete native pairs at binding; WKB pairs are checked per row. */
@@ -3422,45 +3819,47 @@ var ST_INTERSECTS = /* @__PURE__ */ spatialFunction(
3422
3819
  [...geometryTypes, "GeometryCollection"],
3423
3820
  [...geometryTypes, "GeometryCollection"]
3424
3821
  ],
3425
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3822
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3426
3823
  ([a, b]) => planarIntersects(a, b)
3427
3824
  );
3428
3825
  var ST_TOUCHES = /* @__PURE__ */ spatialFunction(
3429
3826
  "ST_Touches",
3430
3827
  [geometryTypes, geometryTypes],
3431
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
3828
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3432
3829
  ([a, b]) => planarTouches(a, b)
3433
3830
  );
3831
+ var ST_LINEMERGE = /* @__PURE__ */ routeEditingFunction("ST_LineMerge", false, mergeRoute);
3832
+ var ST_SEGMENTIZE = /* @__PURE__ */ segmentizeFunction("ST_Segmentize");
3434
3833
  var ST_LINEINTERPOLATEPOINT = /* @__PURE__ */ spatialFunction(
3435
3834
  "ST_LineInterpolatePoint",
3436
3835
  [["LineString"]],
3437
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3438
- ([line], fraction) => (0, import_arrow4.writeWKB)(lineSubstring(line, fraction, fraction) ?? { type: "Point", coordinates: [] }, "xy"),
3836
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3837
+ ([line], fraction) => (0, import_arrow7.writeWKB)(lineSubstring(line, fraction, fraction) ?? { type: "Point", coordinates: [] }, "xy"),
3439
3838
  1
3440
3839
  );
3441
3840
  var ST_LINELOCATEPOINT = /* @__PURE__ */ spatialFunction(
3442
3841
  "ST_LineLocatePoint",
3443
3842
  [["LineString"], pointKinds],
3444
- /* @__PURE__ */ new import_apache_arrow3.Float64(),
3843
+ /* @__PURE__ */ new import_apache_arrow4.Float64(),
3445
3844
  ([line, point2]) => lineLocatePoint(line, point2)
3446
3845
  );
3447
3846
  var ST_LINESUBSTRING = /* @__PURE__ */ spatialFunction(
3448
3847
  "ST_LineSubstring",
3449
3848
  [["LineString"]],
3450
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3849
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3451
3850
  ([line], start, end) => {
3452
3851
  const result2 = lineSubstring(line, start, end);
3453
- return result2 ? (0, import_arrow4.writeWKB)(result2, "xy") : null;
3852
+ return result2 ? (0, import_arrow7.writeWKB)(result2, "xy") : null;
3454
3853
  },
3455
3854
  2
3456
3855
  );
3457
3856
  var ST_ADDMEASURE = /* @__PURE__ */ spatialFunction(
3458
3857
  "ST_AddMeasure",
3459
3858
  [lineKinds],
3460
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3859
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3461
3860
  ([line], start, end) => {
3462
3861
  const result2 = addMeasure(line, line.dimension, start, end);
3463
- return (0, import_arrow4.writeWKB)(result2.geometry, result2.dimension);
3862
+ return (0, import_arrow7.writeWKB)(result2.geometry, result2.dimension);
3464
3863
  },
3465
3864
  2,
3466
3865
  true
@@ -3468,10 +3867,10 @@ var ST_ADDMEASURE = /* @__PURE__ */ spatialFunction(
3468
3867
  var ST_LOCATEALONG = /* @__PURE__ */ spatialFunction(
3469
3868
  "ST_LocateAlong",
3470
3869
  [lineKinds],
3471
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3870
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3472
3871
  ([line], measure) => {
3473
3872
  const dimension = measuredDimension(line.dimension);
3474
- return (0, import_arrow4.writeWKB)(locateAlong(line, dimension, measure), dimension);
3873
+ return (0, import_arrow7.writeWKB)(locateAlong(line, dimension, measure), dimension);
3475
3874
  },
3476
3875
  1,
3477
3876
  true
@@ -3479,10 +3878,10 @@ var ST_LOCATEALONG = /* @__PURE__ */ spatialFunction(
3479
3878
  var ST_LOCATEBETWEEN = /* @__PURE__ */ spatialFunction(
3480
3879
  "ST_LocateBetween",
3481
3880
  [lineKinds],
3482
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3881
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3483
3882
  ([line], start, end) => {
3484
3883
  const dimension = measuredDimension(line.dimension);
3485
- return (0, import_arrow4.writeWKB)(locateBetween(line, dimension, start, end), dimension);
3884
+ return (0, import_arrow7.writeWKB)(locateBetween(line, dimension, start, end), dimension);
3486
3885
  },
3487
3886
  2,
3488
3887
  true
@@ -3534,18 +3933,18 @@ function crsFunction(name) {
3534
3933
  var _a;
3535
3934
  if (fields.length !== (read ? 1 : 2))
3536
3935
  return void 0;
3537
- const metadata = fields[0] && ((_a = (0, import_arrow4.getGeoArrowFieldInfo)(fields[0])) == null ? void 0 : _a.metadata);
3936
+ const metadata = fields[0] && ((_a = (0, import_arrow7.getGeoArrowFieldInfo)(fields[0])) == null ? void 0 : _a.metadata);
3538
3937
  const source = geometrySRID(metadata == null ? void 0 : metadata["crs"]);
3539
3938
  const target = (literals == null ? void 0 : literals[1]) ?? 0;
3540
3939
  if (!read && ((literals == null ? void 0 : literals[1]) === void 0 || !Number.isSafeInteger(target) || target < 0 || target > 998999))
3541
3940
  throw new Error(name + " requires a constant integer SRID between 0 and 998999");
3542
3941
  if (name === "ST_Transform" && (![4326, 3857].includes(source) || ![4326, 3857].includes(target)))
3543
3942
  throw new Error("ST_Transform supports EPSG:4326 and EPSG:3857 source and target CRS");
3544
- const implementation = spatialFunction(name, [[...geometryTypes, "GeometryCollection"]], read ? new import_apache_arrow3.Int32() : new import_apache_arrow3.Binary(), ([geometry]) => {
3943
+ const implementation = spatialFunction(name, [[...geometryTypes, "GeometryCollection"]], read ? new import_apache_arrow4.Int32() : new import_apache_arrow4.Binary(), ([geometry]) => {
3545
3944
  if (read)
3546
3945
  return source;
3547
3946
  const output = name === "ST_Transform" && source !== target ? projectGeometry(geometry, (p) => target === 3857 ? EPSG4326ToEPSG3857([...p], { clampLatitude: false }) : EPSG3857ToLngLat([...p])) : geometry;
3548
- return (0, import_arrow4.writeWKB)(output, "xy");
3947
+ return (0, import_arrow7.writeWKB)(output, "xy");
3549
3948
  }, read ? 0 : 1).resolvePrototype(fields);
3550
3949
  if (!read) {
3551
3950
  const crsMetadata = { ...metadata };
@@ -3572,7 +3971,7 @@ function createSTTransform(engine) {
3572
3971
  const target = literals == null ? void 0 : literals[1];
3573
3972
  if (target === void 0 || !Number.isSafeInteger(target) || target <= 0 || target > 998999)
3574
3973
  throw new Error("ST_Transform requires a constant positive integer EPSG code");
3575
- const info = (0, import_arrow4.getGeoArrowFieldInfo)(field);
3974
+ const info = (0, import_arrow7.getGeoArrowFieldInfo)(field);
3576
3975
  if (!info)
3577
3976
  throw new Error("ST_Transform requires a GeoArrow geometry column");
3578
3977
  if (info.metadata["edges"] === "spherical")
@@ -3587,8 +3986,8 @@ function createSTTransform(engine) {
3587
3986
  enforceAxis: false
3588
3987
  });
3589
3988
  const metadata = JSON.stringify({ ...info.metadata, crs: to, crs_type: "authority_code" });
3590
- const targetField = fields[1] ?? new import_apache_arrow3.Field("srid", new import_apache_arrow3.Int32(), false);
3591
- if (!import_apache_arrow3.DataType.isInt(targetField.type) && !import_apache_arrow3.DataType.isFloat(targetField.type))
3989
+ const targetField = fields[1] ?? new import_apache_arrow4.Field("srid", new import_apache_arrow4.Int32(), false);
3990
+ if (!import_apache_arrow4.DataType.isInt(targetField.type) && !import_apache_arrow4.DataType.isFloat(targetField.type))
3592
3991
  throw new Error("ST_Transform requires a numeric SRID");
3593
3992
  const project = (coordinate) => {
3594
3993
  if (coordinate.every(Number.isNaN))
@@ -3599,7 +3998,7 @@ function createSTTransform(engine) {
3599
3998
  return [x, y, ...coordinate.slice(2)];
3600
3999
  };
3601
4000
  if (info.encoding === "geoarrow.wkb") {
3602
- const prototype = spatialFunction("ST_Transform", [[...geometryTypes, "GeometryCollection"]], new import_apache_arrow3.Binary(), ([geometry]) => (0, import_arrow4.writeWKB)(projectGeometry(geometry, project), "xy"), 1).resolvePrototype(fields);
4001
+ const prototype = spatialFunction("ST_Transform", [[...geometryTypes, "GeometryCollection"]], new import_apache_arrow4.Binary(), ([geometry]) => (0, import_arrow7.writeWKB)(projectGeometry(geometry, project), "xy"), 1).resolvePrototype(fields);
3603
4002
  prototype.result.metadata.set(EXTENSION_METADATA, metadata);
3604
4003
  return prototype;
3605
4004
  }
@@ -3609,10 +4008,10 @@ function createSTTransform(engine) {
3609
4008
  outputMetadata.set(EXTENSION_METADATA, metadata);
3610
4009
  return {
3611
4010
  arguments: [field, targetField],
3612
- result: new import_apache_arrow3.Field("ST_Transform", field.type, field.nullable, outputMetadata),
4011
+ result: new import_apache_arrow4.Field("ST_Transform", field.type, field.nullable, outputMetadata),
3613
4012
  /** Maps native coordinate buffers directly, retaining topology and null rows. */
3614
4013
  evaluate([vector], { activeRows }) {
3615
- return (0, import_arrow4.mapGeoArrowVectorCoordinates)(vector, (coordinate, row) => activeRows[row] ? project(coordinate) : coordinate, { field });
4014
+ return (0, import_arrow7.mapGeoArrowVectorCoordinates)(vector, (coordinate, row) => activeRows[row] ? project(coordinate) : coordinate, { field });
3616
4015
  }
3617
4016
  };
3618
4017
  }
@@ -3629,9 +4028,9 @@ function lineReduction(name, mode) {
3629
4028
  /** Binds the geometry and any supplied numeric tolerance. */
3630
4029
  resolvePrototype(fields) {
3631
4030
  const numericArguments = mode === "removeRepeated" && fields.length === 1 ? 0 : 1;
3632
- return spatialFunction(name, [lineKinds], new import_apache_arrow3.Binary(), ([line], tolerance = 0) => {
4031
+ return spatialFunction(name, [lineKinds], new import_apache_arrow4.Binary(), ([line], tolerance = 0) => {
3633
4032
  const result2 = reduceLineVertices(line, tolerance, mode);
3634
- return result2 ? (0, import_arrow4.writeWKB)(result2, "xy") : null;
4033
+ return result2 ? (0, import_arrow7.writeWKB)(result2, "xy") : null;
3635
4034
  }, numericArguments).resolvePrototype(fields);
3636
4035
  }
3637
4036
  };
@@ -3647,16 +4046,16 @@ var ST_SIMPLIFYPRESERVETOPOLOGY = {
3647
4046
  var _a;
3648
4047
  const encoding = (_a = fields[0]) == null ? void 0 : _a.metadata.get(EXTENSION_NAME);
3649
4048
  const native2 = encoding === "geoarrow.polygon" || encoding === "geoarrow.multipolygon";
3650
- return spatialFunction("ST_SimplifyPreserveTopology", [polygonKinds], native2 ? nativePolygonResult(encoding) : new import_apache_arrow3.Binary(), ([geometry], tolerance) => {
4049
+ return spatialFunction("ST_SimplifyPreserveTopology", [polygonKinds], native2 ? nativeGeometryResult(encoding) : new import_apache_arrow4.Binary(), ([geometry], tolerance) => {
3651
4050
  const result2 = simplifyPolygonTopology(geometry, tolerance);
3652
- return native2 ? result2 : (0, import_arrow4.writeWKB)(result2, "xy");
4051
+ return native2 ? result2 : (0, import_arrow7.writeWKB)(result2, "xy");
3653
4052
  }, 1).resolvePrototype(fields);
3654
4053
  }
3655
4054
  };
3656
4055
  var ST_AZIMUTH = /* @__PURE__ */ spatialFunction(
3657
4056
  "ST_Azimuth",
3658
4057
  [pointKinds, pointKinds],
3659
- /* @__PURE__ */ new import_apache_arrow3.Float64(),
4058
+ /* @__PURE__ */ new import_apache_arrow4.Float64(),
3660
4059
  ([a, b]) => {
3661
4060
  const p = pointCoordinates(a);
3662
4061
  const q = pointCoordinates(b);
@@ -3673,26 +4072,26 @@ var ST_AZIMUTH = /* @__PURE__ */ spatialFunction(
3673
4072
  var ST_AREA = /* @__PURE__ */ spatialFunction(
3674
4073
  "ST_Area",
3675
4074
  [geometryTypes],
3676
- /* @__PURE__ */ new import_apache_arrow3.Float64(),
4075
+ /* @__PURE__ */ new import_apache_arrow4.Float64(),
3677
4076
  ([geometry]) => planarArea(geometry)
3678
4077
  );
3679
4078
  var ST_LENGTH = /* @__PURE__ */ spatialFunction(
3680
4079
  "ST_Length",
3681
4080
  [[...geometryTypes, "GeometryCollection"]],
3682
- /* @__PURE__ */ new import_apache_arrow3.Float64(),
4081
+ /* @__PURE__ */ new import_apache_arrow4.Float64(),
3683
4082
  ([geometry]) => planarLength(geometry)
3684
4083
  );
3685
4084
  var ST_CENTROID = /* @__PURE__ */ spatialFunction(
3686
4085
  "ST_Centroid",
3687
4086
  [geometryTypes],
3688
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3689
- ([geometry]) => (0, import_arrow4.writeWKB)(planarCentroid(geometry), "xy")
4087
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
4088
+ ([geometry]) => (0, import_arrow7.writeWKB)(planarCentroid(geometry), "xy")
3690
4089
  );
3691
4090
  var inspectionKinds = [[...geometryTypes, "GeometryCollection"]];
3692
4091
  var ST_NPOINTS = /* @__PURE__ */ spatialFunction(
3693
4092
  "ST_NPoints",
3694
4093
  inspectionKinds,
3695
- /* @__PURE__ */ new import_apache_arrow3.Int32(),
4094
+ /* @__PURE__ */ new import_apache_arrow4.Int32(),
3696
4095
  ([g]) => vertexCount(g),
3697
4096
  0,
3698
4097
  true
@@ -3700,7 +4099,7 @@ var ST_NPOINTS = /* @__PURE__ */ spatialFunction(
3700
4099
  var ST_NUMGEOMETRIES = /* @__PURE__ */ spatialFunction(
3701
4100
  "ST_NumGeometries",
3702
4101
  inspectionKinds,
3703
- /* @__PURE__ */ new import_apache_arrow3.Int32(),
4102
+ /* @__PURE__ */ new import_apache_arrow4.Int32(),
3704
4103
  ([g]) => memberCount(g),
3705
4104
  0,
3706
4105
  true
@@ -3708,7 +4107,7 @@ var ST_NUMGEOMETRIES = /* @__PURE__ */ spatialFunction(
3708
4107
  var ST_ISEMPTY = /* @__PURE__ */ spatialFunction(
3709
4108
  "ST_IsEmpty",
3710
4109
  inspectionKinds,
3711
- /* @__PURE__ */ new import_apache_arrow3.Bool(),
4110
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
3712
4111
  ([g]) => !vertexCount(g),
3713
4112
  0,
3714
4113
  true
@@ -3716,7 +4115,7 @@ var ST_ISEMPTY = /* @__PURE__ */ spatialFunction(
3716
4115
  var ST_GEOMETRYTYPE = /* @__PURE__ */ spatialFunction(
3717
4116
  "ST_GeometryType",
3718
4117
  inspectionKinds,
3719
- /* @__PURE__ */ new import_apache_arrow3.Utf8(),
4118
+ /* @__PURE__ */ new import_apache_arrow4.Utf8(),
3720
4119
  ([g]) => "ST_" + g.type,
3721
4120
  0,
3722
4121
  true
@@ -3724,19 +4123,19 @@ var ST_GEOMETRYTYPE = /* @__PURE__ */ spatialFunction(
3724
4123
  var ST_FORCE2D = /* @__PURE__ */ spatialFunction(
3725
4124
  "ST_Force2D",
3726
4125
  inspectionKinds,
3727
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3728
- ([g]) => (0, import_arrow4.writeWKB)(g, "xy"),
4126
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
4127
+ ([g]) => (0, import_arrow7.writeWKB)(g, "xy"),
3729
4128
  0,
3730
4129
  true
3731
4130
  );
3732
4131
  var ST_GEOMETRYN = /* @__PURE__ */ spatialFunction(
3733
4132
  "ST_GeometryN",
3734
4133
  inspectionKinds,
3735
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
4134
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
3736
4135
  ([g], position) => {
3737
4136
  var _a;
3738
4137
  const part = geometryMember(g, position);
3739
- return part ? ((_a = g.members) == null ? void 0 : _a[position - 1]) ?? (0, import_arrow4.writeWKB)(part, g.dimension ?? "xy") : null;
4138
+ return part ? ((_a = g.members) == null ? void 0 : _a[position - 1]) ?? (0, import_arrow7.writeWKB)(part, g.dimension ?? "xy") : null;
3740
4139
  },
3741
4140
  1,
3742
4141
  true
@@ -3747,8 +4146,8 @@ var ST_MAKELINE = /* @__PURE__ */ spatialFunction(
3747
4146
  ["Point", "MultiPoint", "LineString"],
3748
4147
  ["Point", "MultiPoint", "LineString"]
3749
4148
  ],
3750
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3751
- (geometries) => (0, import_arrow4.writeWKB)(makeLine(geometries), "xy")
4149
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
4150
+ (geometries) => (0, import_arrow7.writeWKB)(makeLine(geometries), "xy")
3752
4151
  );
3753
4152
  var ST_COLLECT = /* @__PURE__ */ spatialFunction(
3754
4153
  "ST_Collect",
@@ -3756,24 +4155,47 @@ var ST_COLLECT = /* @__PURE__ */ spatialFunction(
3756
4155
  [...geometryTypes, "GeometryCollection"],
3757
4156
  [...geometryTypes, "GeometryCollection"]
3758
4157
  ],
3759
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3760
- ([a, b]) => a ? (0, import_arrow4.writeWKB)(b ? collectPair(a, b) : a, "xy") : null,
4158
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
4159
+ ([a, b]) => a ? (0, import_arrow7.writeWKB)(b ? collectPair(a, b) : a, "xy") : null,
3761
4160
  0,
3762
4161
  false,
3763
4162
  true
3764
4163
  );
4164
+ function polygonValidityReason(geometry) {
4165
+ if (geometry.type === "Polygon")
4166
+ return (0, import_polygon5.getPolygonValidityReason)([geometry.coordinates]);
4167
+ if (geometry.type === "MultiPolygon")
4168
+ return (0, import_polygon5.getPolygonValidityReason)(geometry.coordinates);
4169
+ throw new Error("Expected polygonal geometry");
4170
+ }
4171
+ var ST_ISVALID = /* @__PURE__ */ spatialFunction(
4172
+ "ST_IsValid",
4173
+ [polygonKinds],
4174
+ /* @__PURE__ */ new import_apache_arrow4.Bool(),
4175
+ ([polygon]) => polygonValidityReason(polygon) === void 0,
4176
+ 0,
4177
+ true
4178
+ );
4179
+ var ST_ISVALIDREASON = /* @__PURE__ */ spatialFunction(
4180
+ "ST_IsValidReason",
4181
+ [polygonKinds],
4182
+ /* @__PURE__ */ new import_apache_arrow4.Utf8(),
4183
+ ([polygon]) => polygonValidityReason(polygon) ?? "Valid Geometry",
4184
+ 0,
4185
+ true
4186
+ );
3765
4187
  var ST_POINTONSURFACE = /* @__PURE__ */ spatialFunction(
3766
4188
  "ST_PointOnSurface",
3767
4189
  [polygonKinds],
3768
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3769
- ([polygon]) => (0, import_arrow4.writeWKB)(planarPolygonPointOnSurface(polygon), "xy")
4190
+ /* @__PURE__ */ nativeGeometryResult("geoarrow.point"),
4191
+ ([polygon]) => planarPolygonPointOnSurface(polygon)
3770
4192
  );
3771
4193
  function makeEnvelopeFunction() {
3772
4194
  const envelopeFunction = spatialFunction(
3773
4195
  "ST_Envelope",
3774
4196
  [[...geometryTypes, "GeometryCollection"]],
3775
- /* @__PURE__ */ new import_apache_arrow3.Binary(),
3776
- ([geometry]) => (0, import_arrow4.writeWKB)(planarEnvelope(geometry), "xy")
4197
+ /* @__PURE__ */ new import_apache_arrow4.Binary(),
4198
+ ([geometry]) => (0, import_arrow7.writeWKB)(planarEnvelope(geometry), "xy")
3777
4199
  );
3778
4200
  return {
3779
4201
  ...envelopeFunction,
@@ -3781,7 +4203,7 @@ function makeEnvelopeFunction() {
3781
4203
  resolvePrototype(fields) {
3782
4204
  const prototype = envelopeFunction.resolvePrototype(fields);
3783
4205
  const field = fields[0];
3784
- if (!prototype || !field || import_apache_arrow3.DataType.isBinary(field.type) || import_apache_arrow3.DataType.isLargeBinary(field.type)) {
4206
+ if (!prototype || !field || import_apache_arrow4.DataType.isBinary(field.type) || import_apache_arrow4.DataType.isLargeBinary(field.type)) {
3785
4207
  return prototype;
3786
4208
  }
3787
4209
  return {
@@ -3789,17 +4211,17 @@ function makeEnvelopeFunction() {
3789
4211
  /** Evaluates active rows and preserves the type of empty geometries. */
3790
4212
  evaluate([vector], { activeRows, length }) {
3791
4213
  const column2 = readActiveGeoArrowColumn(vector, field, activeRows);
3792
- const bounds = (0, import_arrow4.getGeoArrowRowBounds)(column2);
4214
+ const bounds2 = (0, import_arrow7.getGeoArrowRowBounds)(column2);
3793
4215
  const values = Array.from({ length }, (_, row) => {
3794
4216
  if (!activeRows[row])
3795
4217
  return null;
3796
- const box = bounds[row];
4218
+ const box = bounds2[row];
3797
4219
  if (box)
3798
- return (0, import_arrow4.writeWKB)(envelopeFromBounds(box), "xy");
3799
- const [geometry] = (0, import_arrow4.materializeGeoArrowRows)((0, import_arrow4.getGeoArrowColumnView)(column2, row, row + 1));
3800
- return geometry ? (0, import_arrow4.writeWKB)(geometry, "xy") : null;
4220
+ return (0, import_arrow7.writeWKB)(envelopeFromBounds(box), "xy");
4221
+ const [geometry] = (0, import_arrow7.materializeGeoArrowRows)((0, import_arrow7.getGeoArrowColumnView)(column2, row, row + 1));
4222
+ return geometry ? (0, import_arrow7.writeWKB)(geometry, "xy") : null;
3801
4223
  });
3802
- return (0, import_apache_arrow3.vectorFromArray)(values, new import_apache_arrow3.Binary());
4224
+ return (0, import_apache_arrow4.vectorFromArray)(values, new import_apache_arrow4.Binary());
3803
4225
  }
3804
4226
  };
3805
4227
  }
@@ -3816,26 +4238,26 @@ var ST_EXTENT = {
3816
4238
  throw new Error("ST_Extent requires one geometry column");
3817
4239
  ST_ENVELOPE.resolvePrototype([field]);
3818
4240
  return {
3819
- outputField: new import_apache_arrow3.Field("ST_Extent", new import_apache_arrow3.FixedSizeList(4, new import_apache_arrow3.Field("value", new import_apache_arrow3.Float64(), false)), true),
4241
+ outputField: new import_apache_arrow4.Field("ST_Extent", new import_apache_arrow4.FixedSizeList(4, new import_apache_arrow4.Field("value", new import_apache_arrow4.Float64(), false)), true),
3820
4242
  /** Creates independent bounds for this group. */
3821
4243
  createAccumulator() {
3822
- let bounds = null;
4244
+ let bounds2 = null;
3823
4245
  function include(box) {
3824
- if (!bounds)
3825
- bounds = [...box];
4246
+ if (!bounds2)
4247
+ bounds2 = [...box];
3826
4248
  else {
3827
- bounds[0] = Math.min(bounds[0], box[0]);
3828
- bounds[1] = Math.min(bounds[1], box[1]);
3829
- bounds[2] = Math.max(bounds[2], box[2]);
3830
- bounds[3] = Math.max(bounds[3], box[3]);
4249
+ bounds2[0] = Math.min(bounds2[0], box[0]);
4250
+ bounds2[1] = Math.min(bounds2[1], box[1]);
4251
+ bounds2[2] = Math.max(bounds2[2], box[2]);
4252
+ bounds2[3] = Math.max(bounds2[3], box[3]);
3831
4253
  }
3832
4254
  }
3833
4255
  return {
3834
4256
  /** Accumulates nonempty geometry bounds from one record batch. */
3835
4257
  update([vector], { length }) {
3836
- if (!import_apache_arrow3.DataType.isBinary(field.type) && !import_apache_arrow3.DataType.isLargeBinary(field.type)) {
3837
- const column2 = (0, import_arrow4.makeGeoArrowColumnFromArrowVector)(vector, { field });
3838
- const box = (0, import_arrow4.getGeoArrowBounds)(column2);
4258
+ if (!import_apache_arrow4.DataType.isBinary(field.type) && !import_apache_arrow4.DataType.isLargeBinary(field.type)) {
4259
+ const column2 = (0, import_arrow7.makeGeoArrowColumnFromArrowVector)(vector, { field });
4260
+ const box = (0, import_arrow7.getGeoArrowBounds)(column2);
3839
4261
  if (box)
3840
4262
  include(box);
3841
4263
  return;
@@ -3857,7 +4279,7 @@ var ST_EXTENT = {
3857
4279
  include(box);
3858
4280
  },
3859
4281
  /** Returns a detached snapshot, or null for a group without coordinates. */
3860
- finalize: () => bounds && [...bounds]
4282
+ finalize: () => bounds2 && [...bounds2]
3861
4283
  };
3862
4284
  }
3863
4285
  };
@@ -3893,6 +4315,8 @@ var POSTGIS_SPATIAL_FUNCTIONS = /* @__PURE__ */ Object.freeze([
3893
4315
  ST_TILEENVELOPE,
3894
4316
  ST_AREA,
3895
4317
  ST_LENGTH,
4318
+ ST_LINEMERGE,
4319
+ ST_SEGMENTIZE,
3896
4320
  ST_LINEINTERPOLATEPOINT,
3897
4321
  ST_LINELOCATEPOINT,
3898
4322
  ST_LINESUBSTRING,
@@ -3900,6 +4324,8 @@ var POSTGIS_SPATIAL_FUNCTIONS = /* @__PURE__ */ Object.freeze([
3900
4324
  ST_LOCATEALONG,
3901
4325
  ST_LOCATEBETWEEN,
3902
4326
  ST_POINTONSURFACE,
4327
+ ST_ISVALID,
4328
+ ST_ISVALIDREASON,
3903
4329
  ST_CENTROID,
3904
4330
  ST_NPOINTS,
3905
4331
  ST_NUMGEOMETRIES,