From 6f7e819aca57e934d19385356a547ba79e590129 Mon Sep 17 00:00:00 2001 From: taDuc Date: Mon, 13 Apr 2026 21:33:12 +0700 Subject: [PATCH] chore: init backend and ignore local artifacts --- .gitignore | 3 + db/polygons.js | 242 ++++++++ index.js | 35 ++ package-lock.json | 1319 +++++++++++++++++++++++++++++++++++++++++ package.json | 20 + routes/entities.js | 345 +++++++++++ routes/geometries.js | 829 ++++++++++++++++++++++++++ routes/rasterTiles.js | 57 ++ routes/tiles.js | 79 +++ swagger.js | 729 +++++++++++++++++++++++ utils/bbox.js | 45 ++ 11 files changed, 3703 insertions(+) create mode 100644 .gitignore create mode 100644 db/polygons.js create mode 100644 index.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 routes/entities.js create mode 100644 routes/geometries.js create mode 100644 routes/rasterTiles.js create mode 100644 routes/tiles.js create mode 100644 swagger.js create mode 100644 utils/bbox.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5d000a7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/data +.idea/ +node_modules/ diff --git a/db/polygons.js b/db/polygons.js new file mode 100644 index 0000000..fb4085d --- /dev/null +++ b/db/polygons.js @@ -0,0 +1,242 @@ +const Database = require("better-sqlite3"); +const path = require("path"); + +const dbPath = path.join(__dirname, "..", "data", "polygons.db"); +const db = new Database(dbPath); +db.pragma("foreign_keys = ON"); + +db.prepare(` + CREATE TABLE IF NOT EXISTS geometries ( + id TEXT PRIMARY KEY, + type TEXT, + is_deleted INTEGER NOT NULL DEFAULT 0, + draw_geometry TEXT NOT NULL, + binding TEXT, + time_start INTEGER, + time_end INTEGER, + bbox_min_lng REAL, + bbox_min_lat REAL, + bbox_max_lng REAL, + bbox_max_lat REAL, + created_at TEXT, + updated_at TEXT + ) +`).run(); + +db.prepare(` + CREATE TABLE IF NOT EXISTS entities ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + slug TEXT UNIQUE, + description TEXT, + type_id TEXT NOT NULL DEFAULT 'country', + kind TEXT, + status INTEGER DEFAULT 1, + is_deleted INTEGER NOT NULL DEFAULT 0, + created_at TEXT, + updated_at TEXT + ) +`).run(); + +db.prepare(` + CREATE TABLE IF NOT EXISTS entity_geometries ( + entity_id TEXT NOT NULL, + geometry_id TEXT NOT NULL, + created_at TEXT, + PRIMARY KEY (entity_id, geometry_id), + FOREIGN KEY (entity_id) REFERENCES entities(id) ON DELETE CASCADE, + FOREIGN KEY (geometry_id) REFERENCES geometries(id) ON DELETE CASCADE + ) +`).run(); + +ensureColumn("entities", "status", "INTEGER DEFAULT 1"); +ensureColumn("entities", "is_deleted", "INTEGER NOT NULL DEFAULT 0"); +ensureColumn("entities", "type_id", "TEXT NOT NULL DEFAULT 'country'"); +ensureColumn("geometries", "is_deleted", "INTEGER NOT NULL DEFAULT 0"); +ensureColumn("geometries", "binding", "TEXT"); +dropGeometryDeprecatedColumnsIfExists(); +migrateLegacyGeometryTypeTokens(); + +db.prepare(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_entities_slug + ON entities(slug) +`).run(); + +db.prepare(` + CREATE INDEX IF NOT EXISTS idx_entities_name + ON entities(name) +`).run(); + +db.prepare(`DROP INDEX IF EXISTS idx_entity_geometries_geometry_id`).run(); + +db.prepare(` + CREATE INDEX IF NOT EXISTS idx_entity_geometries_geometry_id + ON entity_geometries(geometry_id) +`).run(); + +db.prepare(` + CREATE INDEX IF NOT EXISTS idx_entity_geometries_entity_id + ON entity_geometries(entity_id) +`).run(); + +module.exports = db; + +function ensureColumn(tableName, columnName, columnDefinition) { + const columns = db.prepare(`PRAGMA table_info(${tableName})`).all(); + const hasColumn = columns.some((column) => column.name === columnName); + if (hasColumn) return; + db.prepare(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnDefinition}`).run(); +} + +function dropGeometryDeprecatedColumnsIfExists() { + db.prepare(`DROP INDEX IF EXISTS idx_geometries_kind`).run(); + + const columns = db.prepare(`PRAGMA table_info(geometries)`).all(); + const hasKind = columns.some((column) => column.name === "kind"); + const hasLineMode = columns.some((column) => column.name === "line_mode"); + if (!hasKind && !hasLineMode) return; + rebuildGeometriesTableToCurrentSchema(columns); +} + +function rebuildGeometriesTableToCurrentSchema(existingColumns = null) { + const foreignKeysEnabled = Number(db.pragma("foreign_keys", { simple: true })) === 1; + const columns = existingColumns || db.prepare(`PRAGMA table_info(geometries)`).all(); + const hasType = columns.some((column) => column.name === "type"); + const hasIsDeleted = columns.some((column) => column.name === "is_deleted"); + const hasBinding = columns.some((column) => column.name === "binding"); + const hasTimeStart = columns.some((column) => column.name === "time_start"); + const hasTimeEnd = columns.some((column) => column.name === "time_end"); + const hasBBoxMinLng = columns.some((column) => column.name === "bbox_min_lng"); + const hasBBoxMinLat = columns.some((column) => column.name === "bbox_min_lat"); + const hasBBoxMaxLng = columns.some((column) => column.name === "bbox_max_lng"); + const hasBBoxMaxLat = columns.some((column) => column.name === "bbox_max_lat"); + const hasCreatedAt = columns.some((column) => column.name === "created_at"); + const hasUpdatedAt = columns.some((column) => column.name === "updated_at"); + + const typeSelect = hasType ? "type" : "NULL"; + const isDeletedSelect = hasIsDeleted ? "is_deleted" : "0"; + const bindingSelect = hasBinding ? "binding" : "NULL"; + const timeStartSelect = hasTimeStart ? "time_start" : "NULL"; + const timeEndSelect = hasTimeEnd ? "time_end" : "NULL"; + const bboxMinLngSelect = hasBBoxMinLng ? "bbox_min_lng" : "NULL"; + const bboxMinLatSelect = hasBBoxMinLat ? "bbox_min_lat" : "NULL"; + const bboxMaxLngSelect = hasBBoxMaxLng ? "bbox_max_lng" : "NULL"; + const bboxMaxLatSelect = hasBBoxMaxLat ? "bbox_max_lat" : "NULL"; + const createdAtSelect = hasCreatedAt ? "created_at" : "NULL"; + const updatedAtSelect = hasUpdatedAt ? "updated_at" : "NULL"; + if (foreignKeysEnabled) { + db.pragma("foreign_keys = OFF"); + } + + try { + const tx = db.transaction(() => { + db.prepare(`DROP TABLE IF EXISTS geometries_new`).run(); + + db.prepare(` + CREATE TABLE geometries_new ( + id TEXT PRIMARY KEY, + type TEXT, + is_deleted INTEGER NOT NULL DEFAULT 0, + draw_geometry TEXT NOT NULL, + binding TEXT, + time_start INTEGER, + time_end INTEGER, + bbox_min_lng REAL, + bbox_min_lat REAL, + bbox_max_lng REAL, + bbox_max_lat REAL, + created_at TEXT, + updated_at TEXT + ) + `).run(); + + db.prepare(` + INSERT INTO geometries_new ( + id, + type, + is_deleted, + draw_geometry, + binding, + time_start, + time_end, + bbox_min_lng, + bbox_min_lat, + bbox_max_lng, + bbox_max_lat, + created_at, + updated_at + ) + SELECT + id, + ${typeSelect}, + ${isDeletedSelect}, + draw_geometry, + ${bindingSelect}, + ${timeStartSelect}, + ${timeEndSelect}, + ${bboxMinLngSelect}, + ${bboxMinLatSelect}, + ${bboxMaxLngSelect}, + ${bboxMaxLatSelect}, + ${createdAtSelect}, + ${updatedAtSelect} + FROM geometries + `).run(); + + db.prepare(`DROP TABLE geometries`).run(); + db.prepare(`ALTER TABLE geometries_new RENAME TO geometries`).run(); + }); + + tx(); + } finally { + if (foreignKeysEnabled) { + db.pragma("foreign_keys = ON"); + } + } +} + +function migrateLegacyGeometryTypeTokens() { + const geometryColumns = db.prepare(`PRAGMA table_info(geometries)`).all(); + const hasType = geometryColumns.some((column) => column.name === "type"); + if (!hasType) return; + + const tx = db.transaction(() => { + const legacyRows = db.prepare(` + SELECT + g.id, + ( + SELECT e.type_id + FROM entity_geometries eg + JOIN entities e + ON e.id = eg.entity_id + AND e.is_deleted = 0 + WHERE eg.geometry_id = g.id + ORDER BY eg.rowid ASC + LIMIT 1 + ) AS primary_entity_type + FROM geometries g + WHERE g.type IS NULL + OR TRIM(g.type) = '' + OR LOWER(TRIM(g.type)) IN ('line', 'path') + `).all(); + + const updateTypeStmt = db.prepare(` + UPDATE geometries + SET type = ? + WHERE id = ? + `); + + for (const row of legacyRows) { + const semanticType = normalizeText(row.primary_entity_type); + updateTypeStmt.run(semanticType, row.id); + } + }); + + tx(); +} + +function normalizeText(value) { + if (value === undefined || value === null) return null; + const normalized = String(value).trim().toLowerCase(); + return normalized.length ? normalized : null; +} diff --git a/index.js b/index.js new file mode 100644 index 0000000..065b045 --- /dev/null +++ b/index.js @@ -0,0 +1,35 @@ +const express = require("express"); +const cors = require("cors"); +const swaggerUi = require("swagger-ui-express"); + +const tileRoutes = require("./routes/tiles"); +const rasterTileRoutes = require("./routes/rasterTiles"); +const geoRoutes = require("./routes/geometries"); +const entityRoutes = require("./routes/entities"); +const { openApiSpec } = require("./swagger"); + +const app = express(); + +app.use(cors()); +app.use(express.json()); + +// serve MBTiles and geometry CRUD +app.use("/tiles", tileRoutes); +app.use("/raster-tiles", rasterTileRoutes); +app.use("/geometries", geoRoutes); +app.use("/entities", entityRoutes); +app.use("/docs", swaggerUi.serve, swaggerUi.setup(openApiSpec, { + explorer: true, +})); +app.get("/docs.json", (req, res) => { + res.json(openApiSpec); +}); + +app.get("/", (req, res) => { + res.send("GIS server running"); +}); + +app.listen(3000, () => { + console.log("๐Ÿš€ http://localhost:3000"); + console.log("๐Ÿ“˜ Swagger UI: http://localhost:3000/docs"); +}); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..7bad512 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1319 @@ +{ + "name": "be-map", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "be-map", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "better-sqlite3": "^12.8.0", + "cors": "^2.8.6", + "express": "^5.2.1", + "swagger-ui-express": "^5.0.1" + } + }, + "node_modules/@scarf/scarf": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz", + "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==", + "hasInstallScript": true, + "license": "Apache-2.0" + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "12.8.0", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.8.0.tgz", + "integrity": "sha512-RxD2Vd96sQDjQr20kdP+F+dK/1OUNiVOl200vKBZY8u0vTwysfolF6Hq+3ZK2+h8My9YvZhHsF+RSGZW2VYrPQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": "20.x || 22.x || 23.x || 24.x || 25.x" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/body-parser": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.3", + "http-errors": "^2.0.0", + "iconv-lite": "^0.7.0", + "on-finished": "^2.4.1", + "qs": "^6.14.1", + "raw-body": "^3.0.1", + "type-is": "^2.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "peer": true, + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.89.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz", + "integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/swagger-ui-dist": { + "version": "5.32.2", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.2.tgz", + "integrity": "sha512-t6Ns52nS8LU2hqi0+rezMjFO1ZrCsCrnommXrU7Nfrg2va2dWahdvM6TuSwzdHpG29v6BHJyU1c/UWFhgVZzVQ==", + "license": "Apache-2.0", + "dependencies": { + "@scarf/scarf": "=1.4.0" + } + }, + "node_modules/swagger-ui-express": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/swagger-ui-express/-/swagger-ui-express-5.0.1.tgz", + "integrity": "sha512-SrNU3RiBGTLLmFU8GIJdOdanJTl4TOmT27tt3bWWHppqYmAZ6IDuEuBvMU6nZq0zLEe6b/1rACXCgLZqO6ZfrA==", + "license": "MIT", + "dependencies": { + "swagger-ui-dist": ">=5.0.0" + }, + "engines": { + "node": ">= v0.10.32" + }, + "peerDependencies": { + "express": ">=4.0.0 || >=5.0.0-beta" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..4244663 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "be-map", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "dev": "node index.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "type": "commonjs", + "dependencies": { + "better-sqlite3": "^12.8.0", + "cors": "^2.8.6", + "express": "^5.2.1", + "swagger-ui-express": "^5.0.1" + } +} diff --git a/routes/entities.js b/routes/entities.js new file mode 100644 index 0000000..2f1426c --- /dev/null +++ b/routes/entities.js @@ -0,0 +1,345 @@ +const express = require("express"); +const crypto = require("crypto"); +const db = require("../db/polygons"); + +const router = express.Router(); + +router.get("/", (req, res) => { + const search = typeof req.query.q === "string" ? req.query.q.trim() : ""; + + let sql = ` + SELECT + e.*, + COUNT(eg.geometry_id) AS geometry_count + FROM entities e + LEFT JOIN entity_geometries eg + ON eg.entity_id = e.id + WHERE e.is_deleted = 0 + `; + const params = []; + + if (search) { + sql += " AND (e.name LIKE ? OR e.slug LIKE ?)"; + const pattern = `%${search}%`; + params.push(pattern, pattern); + } + + sql += ` + GROUP BY e.id + ORDER BY e.name COLLATE NOCASE ASC + `; + + const rows = db.prepare(sql).all(...params); + res.json(rows.map(normalizeEntityRow)); +}); + +router.get("/search", (req, res) => { + const name = typeof req.query.name === "string" ? req.query.name.trim() : ""; + const limit = normalizeLimit(req.query.limit, 25, 100); + + if (!name) { + return res.json([]); + } + + const pattern = `%${name}%`; + const rows = db.prepare(` + SELECT + e.*, + COUNT(eg.geometry_id) AS geometry_count + FROM entities e + LEFT JOIN entity_geometries eg + ON eg.entity_id = e.id + WHERE e.is_deleted = 0 + AND e.name LIKE ? + GROUP BY e.id + ORDER BY e.name COLLATE NOCASE ASC + LIMIT ? + `).all(pattern, limit); + + res.json(rows.map(normalizeEntityRow)); +}); + +router.get("/:id", (req, res) => { + const row = db.prepare(` + SELECT + e.*, + COUNT(eg.geometry_id) AS geometry_count + FROM entities e + LEFT JOIN entity_geometries eg + ON eg.entity_id = e.id + WHERE e.id = ? + AND e.is_deleted = 0 + GROUP BY e.id + `).get(req.params.id); + + if (!row) { + return res.status(404).json({ error: "Entity not found" }); + } + + res.json(normalizeEntityRow(row)); +}); + +router.post("/", (req, res) => { + const name = normalizeRequiredString(req.body?.name); + if (!name) { + return res.status(400).json({ error: "name is required" }); + } + + const id = crypto.randomUUID(); + const now = new Date().toISOString(); + const slug = normalizeOptionalString(req.body?.slug) || toSlug(name); + const description = normalizeOptionalString(req.body?.description); + const typeId = normalizeTypeId(req.body?.type_id); + const status = normalizeOptionalNumber(req.body?.status) ?? 1; + + try { + db.prepare(` + INSERT INTO entities ( + id, name, slug, description, type_id, kind, status, is_deleted, created_at, updated_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?) + `).run( + id, + name, + slug, + description, + typeId, + null, + status, + now, + now + ); + } catch (err) { + if (isSqliteConstraint(err)) { + return res.status(409).json({ error: "Entity name/slug must be unique" }); + } + console.error("Create entity failed", err); + return res.status(500).json({ error: "Create entity failed" }); + } + + const created = db.prepare(` + SELECT + e.*, + COUNT(eg.geometry_id) AS geometry_count + FROM entities e + LEFT JOIN entity_geometries eg + ON eg.entity_id = e.id + WHERE e.id = ? + GROUP BY e.id + `).get(id); + + res.status(201).json(normalizeEntityRow(created)); +}); + +router.put("/:id", (req, res) => { + const existing = db.prepare(` + SELECT * + FROM entities + WHERE id = ? + AND is_deleted = 0 + `).get(req.params.id); + + if (!existing) { + return res.status(404).json({ error: "Entity not found" }); + } + + const hasName = Object.prototype.hasOwnProperty.call(req.body || {}, "name"); + const hasSlug = Object.prototype.hasOwnProperty.call(req.body || {}, "slug"); + const hasDescription = Object.prototype.hasOwnProperty.call(req.body || {}, "description"); + const hasTypeId = Object.prototype.hasOwnProperty.call(req.body || {}, "type_id"); + const hasStatus = Object.prototype.hasOwnProperty.call(req.body || {}, "status"); + + if (!hasName && !hasSlug && !hasDescription && !hasTypeId && !hasStatus) { + return res.status(400).json({ error: "No updatable field provided" }); + } + + const name = hasName ? normalizeRequiredString(req.body?.name) : existing.name; + if (!name) { + return res.status(400).json({ error: "name cannot be empty" }); + } + + const slug = hasSlug ? normalizeOptionalString(req.body?.slug) : existing.slug; + const description = hasDescription ? normalizeOptionalString(req.body?.description) : existing.description; + const typeId = hasTypeId ? normalizeTypeId(req.body?.type_id) : existing.type_id; + const status = hasStatus + ? (normalizeOptionalNumber(req.body?.status) ?? existing.status) + : existing.status; + const now = new Date().toISOString(); + + try { + db.prepare(` + UPDATE entities + SET name = ?, + slug = ?, + description = ?, + type_id = ?, + kind = ?, + status = ?, + updated_at = ? + WHERE id = ? + `).run( + name, + slug, + description, + typeId, + null, + status, + now, + req.params.id + ); + } catch (err) { + if (isSqliteConstraint(err)) { + return res.status(409).json({ error: "Entity name/slug must be unique" }); + } + console.error("Update entity failed", err); + return res.status(500).json({ error: "Update entity failed" }); + } + + const updated = db.prepare(` + SELECT + e.*, + COUNT(eg.geometry_id) AS geometry_count + FROM entities e + LEFT JOIN entity_geometries eg + ON eg.entity_id = e.id + WHERE e.id = ? + AND e.is_deleted = 0 + GROUP BY e.id + `).get(req.params.id); + + res.json(normalizeEntityRow(updated)); +}); + +router.delete("/:id", (req, res) => { + const entityId = req.params.id; + const existing = db.prepare(` + SELECT id + FROM entities + WHERE id = ? + AND is_deleted = 0 + `).get(entityId); + + if (!existing) { + return res.status(404).json({ error: "Entity not found" }); + } + + const orphanedGeometryRows = db.prepare(` + SELECT eg_target.geometry_id + FROM entity_geometries eg_target + JOIN geometries g_target + ON g_target.id = eg_target.geometry_id + AND g_target.is_deleted = 0 + LEFT JOIN entity_geometries eg_other + ON eg_other.geometry_id = eg_target.geometry_id + AND eg_other.entity_id <> eg_target.entity_id + LEFT JOIN entities e_other + ON e_other.id = eg_other.entity_id + AND e_other.is_deleted = 0 + WHERE eg_target.entity_id = ? + GROUP BY eg_target.geometry_id + HAVING COUNT(e_other.id) = 0 + `).all(entityId); + + if (orphanedGeometryRows.length) { + const previewIds = orphanedGeometryRows.slice(0, 10).map((row) => row.geometry_id); + const suffix = orphanedGeometryRows.length > 10 ? ", ..." : ""; + return res.status(409).json({ + error: `Cannot delete entity. Reassign ${orphanedGeometryRows.length} linked geometries first: ${previewIds.join(", ")}${suffix}`, + }); + } + + const now = new Date().toISOString(); + const deleted = db.transaction((id, timestamp) => { + const result = db.prepare(` + UPDATE entities + SET is_deleted = 1, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run(timestamp, id); + + if (!result.changes) { + return false; + } + + db.prepare(` + DELETE FROM entity_geometries + WHERE entity_id = ? + `).run(id); + + return true; + })(entityId, now); + + if (!deleted) { + return res.status(404).json({ error: "Entity not found" }); + } + + res.json({ success: true }); +}); + +module.exports = router; + +function normalizeEntityRow(row) { + return { + id: row.id, + name: row.name, + slug: row.slug, + description: row.description, + type_id: row.type_id, + status: row.status, + created_at: row.created_at, + updated_at: row.updated_at, + geometry_count: Number(row.geometry_count || 0), + }; +} + +function normalizeRequiredString(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length ? trimmed : null; +} + +function normalizeOptionalString(value) { + if (value === undefined || value === null) return null; + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length ? trimmed : null; +} + +function normalizeOptionalNumber(value) { + if (value === undefined || value === null || value === "") return null; + const num = Number(value); + if (!Number.isFinite(num)) return null; + return num; +} + +function normalizeTypeId(value) { + if (value === undefined || value === null || value === "") { + return "country"; + } + const trimmed = String(value).trim().toLowerCase(); + return trimmed || "country"; +} + +function normalizeLimit(value, fallback = 25, max = 100) { + const num = Number(value); + if (!Number.isFinite(num)) return fallback; + const intValue = Math.trunc(num); + if (intValue <= 0) return fallback; + return Math.min(intValue, max); +} + +function toSlug(value) { + return value + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 120) || null; +} + +function isSqliteConstraint(err) { + const message = typeof err?.message === "string" ? err.message : ""; + return message.includes("UNIQUE constraint failed"); +} diff --git a/routes/geometries.js b/routes/geometries.js new file mode 100644 index 0000000..e347506 --- /dev/null +++ b/routes/geometries.js @@ -0,0 +1,829 @@ +const express = require("express"); +const crypto = require("crypto"); +const db = require("../db/polygons"); +const { getBBox } = require("../utils/bbox"); + +const router = express.Router(); + +// ======================= +// Create geometry +// ======================= +router.post("/", (req, res) => { + const { geometry } = req.body || {}; + if (!geometry) { + return res.status(400).json({ error: "Missing geometry" }); + } + + let temporalRange; + let entityPayload; + let bindingPayload; + try { + temporalRange = normalizeTemporalRange(req.body?.time_start, req.body?.time_end); + entityPayload = extractEntityIdsFromPayload(req.body || {}); + bindingPayload = extractBindingFromPayload(req.body || {}); + ensureGeometryHasEntities(entityPayload.entityIds); + validateEntityIdsExist(entityPayload.entityIds); + } catch (err) { + return res.status(err.status || 400).json({ error: err.message }); + } + + const id = crypto.randomUUID(); + const now = new Date().toISOString(); + const bbox = getBBox(geometry); + const bindingIds = sanitizeBindingIdsForGeometry(bindingPayload.bindingIds, id); + const geometryType = resolveGeometryType(req.body?.type, entityPayload.entityIds); + + try { + const tx = db.transaction(() => { + db.prepare(` + INSERT INTO geometries ( + id, type, is_deleted, draw_geometry, binding, time_start, time_end, + bbox_min_lng, bbox_min_lat, bbox_max_lng, bbox_max_lat, + created_at, updated_at + ) + VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + id, + geometryType, + JSON.stringify(geometry), + serializeBindingIds(bindingIds), + temporalRange.timeStart, + temporalRange.timeEnd, + bbox.minLng, + bbox.minLat, + bbox.maxLng, + bbox.maxLat, + now, + now + ); + + syncGeometryEntityLinks(id, entityPayload.entityIds, now); + }); + + tx(); + } catch (err) { + if (err.status) { + return res.status(err.status).json({ error: err.message }); + } + console.error("Create geometry failed:", err); + return res.status(500).json({ error: "Create geometry failed" }); + } + + res.json({ id }); +}); + +// ======================= +// Query by bbox/time(/entity) +// ======================= +router.get("/", (req, res) => { + const minLng = Number(req.query.minLng); + const minLat = Number(req.query.minLat); + const maxLng = Number(req.query.maxLng); + const maxLat = Number(req.query.maxLat); + + if ( + !Number.isFinite(minLng) || + !Number.isFinite(minLat) || + !Number.isFinite(maxLng) || + !Number.isFinite(maxLat) + ) { + return res.status(400).json({ error: "Missing/invalid bbox" }); + } + + let t = null; + if (req.query.time !== undefined && req.query.time !== "") { + const parsed = Number(req.query.time); + if (!Number.isFinite(parsed)) { + return res.status(400).json({ error: "Invalid time" }); + } + t = Math.trunc(parsed); + } + + let entityId = null; + try { + entityId = normalizeEntityId(req.query.entity_id); + } catch (err) { + return res.status(err.status || 400).json({ error: err.message }); + } + + const rows = db.prepare(` + SELECT + g.* + FROM geometries g + WHERE g.is_deleted = 0 + AND g.bbox_max_lng >= ? + AND g.bbox_min_lng <= ? + AND g.bbox_max_lat >= ? + AND g.bbox_min_lat <= ? + AND ( + ? IS NULL + OR ( + (g.time_start IS NULL OR g.time_start <= ?) + AND (g.time_end IS NULL OR g.time_end >= ?) + ) + ) + AND ( + ? IS NULL + OR EXISTS ( + SELECT 1 + FROM entity_geometries eg + JOIN entities e + ON e.id = eg.entity_id + AND e.is_deleted = 0 + WHERE eg.geometry_id = g.id + AND eg.entity_id = ? + ) + ) + `).all(minLng, maxLng, minLat, maxLat, t, t, t, entityId, entityId); + + const geometryIds = rows.map((row) => String(row.id)); + const linksByGeometryId = loadGeometryLinksByGeometryId(geometryIds); + + res.json({ + type: "FeatureCollection", + features: rows.map((row) => { + const linkedEntities = linksByGeometryId.get(String(row.id)) || []; + return buildFeatureFromRow(row, linkedEntities); + }), + }); +}); + +// ======================= +// Update geometry +// ======================= +router.put("/:id", (req, res) => { + const { geometry } = req.body || {}; + if (!geometry) { + return res.status(400).json({ error: "Missing geometry" }); + } + + const existing = db.prepare(` + SELECT id, type, time_start, time_end, binding + FROM geometries + WHERE id = ? + AND is_deleted = 0 + `).get(req.params.id); + + if (!existing) { + return res.status(404).json({ error: "Not found" }); + } + + const hasTimeStart = Object.prototype.hasOwnProperty.call(req.body || {}, "time_start"); + const hasTimeEnd = Object.prototype.hasOwnProperty.call(req.body || {}, "time_end"); + const hasType = Object.prototype.hasOwnProperty.call(req.body || {}, "type"); + + let temporalRange; + let entityPayload; + let nextEntityIds; + let bindingPayload; + let nextBindingIds; + let nextType; + try { + temporalRange = normalizeTemporalRange( + hasTimeStart ? req.body?.time_start : existing.time_start, + hasTimeEnd ? req.body?.time_end : existing.time_end + ); + + entityPayload = extractEntityIdsFromPayload(req.body || {}); + nextEntityIds = entityPayload.provided + ? entityPayload.entityIds + : getLinkedEntityIdsByGeometryId(req.params.id); + + nextType = hasType + ? resolveGeometryType(req.body?.type, nextEntityIds, existing.type) + : resolveGeometryType(null, nextEntityIds, existing.type); + + bindingPayload = extractBindingFromPayload(req.body || {}); + nextBindingIds = bindingPayload.provided + ? bindingPayload.bindingIds + : parseBindingIds(existing.binding); + nextBindingIds = sanitizeBindingIdsForGeometry(nextBindingIds, req.params.id); + + ensureGeometryHasEntities(nextEntityIds); + validateEntityIdsExist(nextEntityIds); + } catch (err) { + return res.status(err.status || 400).json({ error: err.message }); + } + + const bbox = getBBox(geometry); + const now = new Date().toISOString(); + + try { + const tx = db.transaction(() => { + const result = db.prepare(` + UPDATE geometries + SET type = ?, + draw_geometry = ?, + binding = ?, + time_start = ?, + time_end = ?, + bbox_min_lng = ?, + bbox_min_lat = ?, + bbox_max_lng = ?, + bbox_max_lat = ?, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run( + nextType, + JSON.stringify(geometry), + serializeBindingIds(nextBindingIds), + temporalRange.timeStart, + temporalRange.timeEnd, + bbox.minLng, + bbox.minLat, + bbox.maxLng, + bbox.maxLat, + now, + req.params.id + ); + + if (!result.changes) { + throw createValidationError("Not found", 404); + } + + if (entityPayload.provided) { + syncGeometryEntityLinks(req.params.id, nextEntityIds, now); + } + }); + + tx(); + } catch (err) { + if (err.status) { + return res.status(err.status).json({ error: err.message }); + } + console.error("Update geometry failed:", err); + return res.status(500).json({ error: "Update geometry failed" }); + } + + res.json({ success: true }); +}); + +// ======================= +// Soft-delete geometry +// ======================= +router.delete("/:id", (req, res) => { + const now = new Date().toISOString(); + const tx = db.transaction(() => { + const result = db.prepare(` + UPDATE geometries + SET is_deleted = 1, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run(now, req.params.id); + + if (!result.changes) { + throw createValidationError("Not found", 404); + } + + db.prepare(`DELETE FROM entity_geometries WHERE geometry_id = ?`).run(req.params.id); + removeBindingReferenceFromAll(req.params.id, now); + }); + + try { + tx(); + } catch (err) { + if (err.status) { + return res.status(err.status).json({ error: err.message }); + } + console.error("Delete geometry failed:", err); + return res.status(500).json({ error: "Delete geometry failed" }); + } + + res.json({ success: true }); +}); + +// ======================= +// Apply batch of create/update/delete (used by FE Save) +// ======================= +router.post("/batch", (req, res) => { + const { changes } = req.body || {}; + if (!Array.isArray(changes)) { + return res.status(400).json({ error: "changes must be an array" }); + } + + const now = new Date().toISOString(); + + try { + const tx = db.transaction((items) => { + for (const change of items) { + const hasAction = Object.prototype.hasOwnProperty.call(change || {}, "action"); + const action = normalizeBatchAction(hasAction ? change.action : change?.type); + + if (!change || !action) { + throw createValidationError("Invalid change entry"); + } + + if (action === "create") { + const feature = change.feature; + if (!feature || !feature.properties || !feature.properties.id || !feature.geometry) { + throw createValidationError("Invalid create payload"); + } + + const temporalRange = normalizeTemporalRange( + feature.properties.time_start, + feature.properties.time_end + ); + const entityPayload = extractEntityIdsFromPayload(feature.properties || {}); + const entityIds = entityPayload.entityIds; + ensureGeometryHasEntities(entityIds); + validateEntityIdsExist(entityIds); + + const bbox = getBBox(feature.geometry); + const geometryId = String(feature.properties.id); + const bindingPayload = extractBindingFromPayload(feature.properties || {}); + const bindingIds = sanitizeBindingIdsForGeometry(bindingPayload.bindingIds, geometryId); + const geometryType = resolveGeometryType(feature.properties?.type, entityIds); + + db.prepare(` + INSERT OR REPLACE INTO geometries ( + id, type, is_deleted, draw_geometry, binding, time_start, time_end, + bbox_min_lng, bbox_min_lat, bbox_max_lng, bbox_max_lat, + created_at, updated_at + ) + VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(( + SELECT created_at FROM geometries WHERE id = ? + ), ?), ?) + `).run( + geometryId, + geometryType, + JSON.stringify(feature.geometry), + serializeBindingIds(bindingIds), + temporalRange.timeStart, + temporalRange.timeEnd, + bbox.minLng, + bbox.minLat, + bbox.maxLng, + bbox.maxLat, + geometryId, + now, + now + ); + + syncGeometryEntityLinks(geometryId, entityIds, now); + continue; + } + + if (action === "update") { + const { id, geometry } = change; + if (!id || !geometry) { + throw createValidationError("Invalid update payload"); + } + + const existing = db.prepare(` + SELECT id, type, time_start, time_end, binding + FROM geometries + WHERE id = ? + AND is_deleted = 0 + `).get(id); + + if (!existing) { + continue; + } + + const hasTimeStart = Object.prototype.hasOwnProperty.call(change, "time_start"); + const hasTimeEnd = Object.prototype.hasOwnProperty.call(change, "time_end"); + const hasType = hasAction && Object.prototype.hasOwnProperty.call(change, "type"); + const temporalRange = normalizeTemporalRange( + hasTimeStart ? change.time_start : existing.time_start, + hasTimeEnd ? change.time_end : existing.time_end + ); + const bindingPayload = extractBindingFromPayload(change); + const nextBindingIds = sanitizeBindingIdsForGeometry( + bindingPayload.provided + ? bindingPayload.bindingIds + : parseBindingIds(existing.binding), + id + ); + + const entityPayload = extractEntityIdsFromPayload(change); + const nextEntityIds = entityPayload.provided + ? entityPayload.entityIds + : getLinkedEntityIdsByGeometryId(id); + ensureGeometryHasEntities(nextEntityIds); + validateEntityIdsExist(nextEntityIds); + const nextType = hasType + ? resolveGeometryType(change.type, nextEntityIds, existing.type) + : resolveGeometryType(null, nextEntityIds, existing.type); + + const bbox = getBBox(geometry); + + db.prepare(` + UPDATE geometries + SET type = ?, + draw_geometry = ?, + binding = ?, + time_start = ?, + time_end = ?, + bbox_min_lng = ?, + bbox_min_lat = ?, + bbox_max_lng = ?, + bbox_max_lat = ?, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run( + nextType, + JSON.stringify(geometry), + serializeBindingIds(nextBindingIds), + temporalRange.timeStart, + temporalRange.timeEnd, + bbox.minLng, + bbox.minLat, + bbox.maxLng, + bbox.maxLat, + now, + id + ); + + if (entityPayload.provided) { + syncGeometryEntityLinks(id, nextEntityIds, now); + } + continue; + } + + if (action === "delete") { + if (!change.id) { + throw createValidationError("Invalid delete payload"); + } + + const result = db.prepare(` + UPDATE geometries + SET is_deleted = 1, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run(now, change.id); + + if (result.changes) { + db.prepare(`DELETE FROM entity_geometries WHERE geometry_id = ?`).run(change.id); + removeBindingReferenceFromAll(change.id, now); + } + continue; + } + + throw createValidationError(`Unknown change type: ${String(action)}`); + } + }); + + tx(changes); + res.json({ success: true, applied: changes.length }); + } catch (err) { + if (err.status) { + return res.status(err.status).json({ error: err.message }); + } + console.error("Batch apply error:", err); + res.status(500).json({ error: "Batch apply failed" }); + } +}); + +module.exports = router; + +function buildFeatureFromRow(row, linkedEntities = []) { + const entityIds = linkedEntities.map((entity) => entity.entity_id); + const primaryEntityId = entityIds[0] || null; + const orderedEntityIds = entityIds; + const orderedLinkedEntities = linkedEntities; + const primaryEntity = + orderedLinkedEntities.find((entity) => entity.entity_id === primaryEntityId) || + orderedLinkedEntities[0] || + null; + const storedGeometryType = normalizeGeometryType(row.type); + const semanticType = storedGeometryType && !isLegacyLineModeToken(storedGeometryType) + ? storedGeometryType + : normalizeGeometryType(primaryEntity?.entity_type_id); + + return { + type: "Feature", + properties: { + id: row.id, + type: semanticType || null, + time_start: row.time_start, + time_end: row.time_end, + binding: parseBindingIds(row.binding), + entity_id: primaryEntityId, + entity_ids: orderedEntityIds, + entity_name: primaryEntity?.entity_name || null, + entity_names: orderedLinkedEntities + .map((entity) => entity.entity_name) + .filter((name) => typeof name === "string" && name.length > 0), + entity_type_id: primaryEntity?.entity_type_id || null, + }, + geometry: JSON.parse(row.draw_geometry), + }; +} + +function normalizeOptionalYear(value) { + if (value === undefined || value === null || value === "") return null; + const num = Number(value); + if (!Number.isFinite(num)) { + throw createValidationError("time_start/time_end must be numbers"); + } + return Math.trunc(num); +} + +function normalizeGeometryType(value) { + if (value === undefined || value === null || value === "") return null; + const normalized = String(value).trim().toLowerCase(); + return normalized.length ? normalized : null; +} + +function resolveGeometryType(requestedType, entityIds, fallbackType = null) { + const normalizedRequestedType = normalizeGeometryType(requestedType); + if (normalizedRequestedType && !isLegacyLineModeToken(normalizedRequestedType)) { + return normalizedRequestedType; + } + + const derivedType = deriveGeometryTypeFromEntityIds(entityIds); + if (derivedType) return derivedType; + + const normalizedFallbackType = normalizeGeometryType(fallbackType); + if (normalizedFallbackType && !isLegacyLineModeToken(normalizedFallbackType)) { + return normalizedFallbackType; + } + return null; +} + +function deriveGeometryTypeFromEntityIds(entityIds) { + if (!Array.isArray(entityIds) || !entityIds.length) return null; + const primaryEntityId = normalizeEntityId(entityIds[0]); + if (!primaryEntityId) return null; + + const row = db.prepare(` + SELECT type_id + FROM entities + WHERE id = ? + AND is_deleted = 0 + LIMIT 1 + `).get(primaryEntityId); + + return normalizeGeometryType(row?.type_id); +} + +function isLegacyLineModeToken(value) { + return value === "line" || value === "path"; +} + +function normalizeTemporalRange(timeStartValue, timeEndValue) { + const timeStart = normalizeOptionalYear(timeStartValue); + const timeEnd = normalizeOptionalYear(timeEndValue); + if (timeStart !== null && timeEnd !== null && timeStart > timeEnd) { + throw createValidationError("time_start must be <= time_end"); + } + return { timeStart, timeEnd }; +} + +function normalizeEntityId(value) { + if (value === undefined || value === null || value === "") return null; + const normalized = String(value).trim(); + return normalized || null; +} + +function normalizeEntityIds(rawEntityIds) { + if (rawEntityIds === undefined) return []; + if (rawEntityIds === null) return []; + if (!Array.isArray(rawEntityIds)) { + throw createValidationError("entity_ids must be an array"); + } + + const deduped = []; + const seen = new Set(); + for (const rawId of rawEntityIds) { + const entityId = normalizeEntityId(rawId); + if (!entityId || seen.has(entityId)) continue; + seen.add(entityId); + deduped.push(entityId); + } + return deduped; +} + +function normalizeBindingIds(rawBinding) { + if (rawBinding === undefined || rawBinding === null || rawBinding === "") { + return []; + } + + if (!Array.isArray(rawBinding)) { + throw createValidationError("binding must be an array"); + } + + const deduped = []; + const seen = new Set(); + + for (const rawId of rawBinding) { + if (typeof rawId !== "string" && typeof rawId !== "number") { + throw createValidationError("binding must contain geometry ids as string/number"); + } + + const normalized = String(rawId).trim(); + if (!normalized || seen.has(normalized)) continue; + seen.add(normalized); + deduped.push(normalized); + } + + return deduped; +} + +function parseBindingIds(rawBinding) { + if (rawBinding === undefined || rawBinding === null || rawBinding === "") { + return []; + } + + if (Array.isArray(rawBinding)) { + try { + return normalizeBindingIds(rawBinding); + } catch (_err) { + return []; + } + } + + if (typeof rawBinding === "string") { + try { + const parsed = JSON.parse(rawBinding); + return normalizeBindingIds(parsed); + } catch (_err) { + const plain = rawBinding.trim(); + return plain.length ? [plain] : []; + } + } + + return []; +} + +function extractBindingFromPayload(payload) { + const hasBinding = Object.prototype.hasOwnProperty.call(payload || {}, "binding"); + if (!hasBinding) { + return { + provided: false, + bindingIds: [], + }; + } + + return { + provided: true, + bindingIds: normalizeBindingIds(payload.binding), + }; +} + +function sanitizeBindingIdsForGeometry(bindingIds, geometryId) { + const selfId = String(geometryId); + return bindingIds.filter((bindingId) => bindingId !== selfId); +} + +function serializeBindingIds(bindingIds) { + return bindingIds.length ? JSON.stringify(bindingIds) : null; +} + +function extractEntityIdsFromPayload(payload) { + const hasEntityIds = Object.prototype.hasOwnProperty.call(payload || {}, "entity_ids"); + const hasEntityId = Object.prototype.hasOwnProperty.call(payload || {}, "entity_id"); + if (!hasEntityIds && !hasEntityId) { + return { + provided: false, + entityIds: [], + }; + } + + const fromArray = hasEntityIds ? normalizeEntityIds(payload.entity_ids) : []; + const singleEntityId = hasEntityId ? normalizeEntityId(payload.entity_id) : null; + + const entityIds = [...fromArray]; + if (singleEntityId && !entityIds.includes(singleEntityId)) { + entityIds.unshift(singleEntityId); + } + + return { + provided: true, + entityIds, + }; +} + +function ensureGeometryHasEntities(entityIds) { + if (!Array.isArray(entityIds) || !entityIds.length) { + throw createValidationError("geometry must be linked to at least one entity"); + } +} + +function validateEntityIdsExist(entityIds) { + if (!entityIds.length) { + throw createValidationError("geometry must be linked to at least one entity"); + } + + const placeholders = entityIds.map(() => "?").join(","); + const rows = db.prepare(` + SELECT id + FROM entities + WHERE is_deleted = 0 + AND id IN (${placeholders}) + `).all(...entityIds); + + const found = new Set(rows.map((row) => row.id)); + const missing = entityIds.filter((entityId) => !found.has(entityId)); + if (missing.length) { + throw createValidationError(`Entity not found: ${missing.join(", ")}`); + } +} + +function getLinkedEntityIdsByGeometryId(geometryId) { + const rows = db.prepare(` + SELECT eg.entity_id + FROM entity_geometries eg + JOIN entities e + ON e.id = eg.entity_id + AND e.is_deleted = 0 + WHERE eg.geometry_id = ? + ORDER BY eg.rowid ASC + `).all(String(geometryId)); + + return rows.map((row) => row.entity_id); +} + +function loadGeometryLinksByGeometryId(geometryIds) { + const map = new Map(); + if (!geometryIds.length) return map; + + const placeholders = geometryIds.map(() => "?").join(","); + const rows = db.prepare(` + SELECT + eg.geometry_id, + eg.entity_id, + e.name AS entity_name, + e.type_id AS entity_type_id + FROM entity_geometries eg + JOIN entities e + ON e.id = eg.entity_id + AND e.is_deleted = 0 + WHERE eg.geometry_id IN (${placeholders}) + ORDER BY eg.rowid ASC + `).all(...geometryIds); + + for (const row of rows) { + const geometryId = String(row.geometry_id); + const current = map.get(geometryId) || []; + current.push({ + entity_id: row.entity_id, + entity_name: row.entity_name || null, + entity_type_id: row.entity_type_id || null, + }); + map.set(geometryId, current); + } + + return map; +} + +function syncGeometryEntityLinks(geometryId, entityIds, now) { + db.prepare(` + DELETE FROM entity_geometries + WHERE geometry_id = ? + `).run(String(geometryId)); + + for (const entityId of entityIds) { + db.prepare(` + INSERT INTO entity_geometries (entity_id, geometry_id, created_at) + VALUES (?, ?, ?) + `).run(entityId, String(geometryId), now); + } +} + +function removeBindingReferenceFromAll(removedGeometryId, now) { + const removedId = String(removedGeometryId); + + const rows = db.prepare(` + SELECT id, binding + FROM geometries + WHERE is_deleted = 0 + AND binding IS NOT NULL + AND binding != '' + `).all(); + + for (const row of rows) { + const currentBindingIds = parseBindingIds(row.binding); + if (!currentBindingIds.length) continue; + + const nextBindingIds = currentBindingIds.filter((bindingId) => bindingId !== removedId); + if (nextBindingIds.length === currentBindingIds.length) continue; + + db.prepare(` + UPDATE geometries + SET binding = ?, + updated_at = ? + WHERE id = ? + AND is_deleted = 0 + `).run(serializeBindingIds(nextBindingIds), now, row.id); + } +} + +function createValidationError(message, status = 400) { + const err = new Error(message); + err.status = status; + return err; +} + +function normalizeBatchAction(value) { + if (value === undefined || value === null) return null; + const normalized = String(value).trim().toLowerCase(); + if (normalized === "create" || normalized === "update" || normalized === "delete") { + return normalized; + } + return null; +} diff --git a/routes/rasterTiles.js b/routes/rasterTiles.js new file mode 100644 index 0000000..4f8a629 --- /dev/null +++ b/routes/rasterTiles.js @@ -0,0 +1,57 @@ +const express = require("express"); +const Database = require("better-sqlite3"); +const path = require("path"); + +const router = express.Router(); + +const mbtilesPath = path.join(__dirname, "..", "data", "raster.mbtiles"); +const tileDb = new Database(mbtilesPath, { readonly: true }); + +const metadataRows = tileDb.prepare("SELECT name, value FROM metadata").all(); +const metadata = {}; + +for (const row of metadataRows) { + metadata[row.name] = row.value; +} + +let contentType = "application/octet-stream"; +if (metadata.format === "png") { + contentType = "image/png"; +} else if (metadata.format === "jpg" || metadata.format === "jpeg") { + contentType = "image/jpeg"; +} else if (metadata.format === "webp") { + contentType = "image/webp"; +} + +router.get("/metadata/info", (req, res) => { + res.json(metadata); +}); + +router.get("/:z/:x/:y", (req, res) => { + const z = Number(req.params.z); + const x = Number(req.params.x); + const y = Number(req.params.y); + + if (!Number.isInteger(z) || !Number.isInteger(x) || !Number.isInteger(y)) { + return res.status(400).send("Invalid tile coordinates"); + } + + const tmsY = (1 << z) - 1 - y; + + const tile = tileDb.prepare(` + SELECT tile_data + FROM tiles + WHERE zoom_level = ? + AND tile_column = ? + AND tile_row = ? + `).get(z, x, tmsY); + + if (!tile) { + return res.status(404).send("Tile not found"); + } + + res.setHeader("Content-Type", contentType); + res.send(tile.tile_data); +}); + +module.exports = router; diff --git a/routes/tiles.js b/routes/tiles.js new file mode 100644 index 0000000..07b3546 --- /dev/null +++ b/routes/tiles.js @@ -0,0 +1,79 @@ +const express = require("express"); +const Database = require("better-sqlite3"); +const path = require("path"); + +const router = express.Router(); + +// ======================= +// MBTiles DB (READONLY) +// ======================= +const mbtilesPath = path.join(__dirname, "..", "data", "map.mbtiles"); +const tileDb = new Database(mbtilesPath, { readonly: true }); + +// ======================= +// ๐Ÿ“Š METADATA +// ======================= +const metadataRows = tileDb.prepare("SELECT name, value FROM metadata").all(); +const metadata = {}; + +for (const row of metadataRows) { + metadata[row.name] = row.value; +} + +// decide content-type +let contentType = "application/octet-stream"; + +if (metadata.format === "pbf") { + contentType = "application/x-protobuf"; +} else if (metadata.format === "png") { + contentType = "image/png"; +} else if (metadata.format === "jpg" || metadata.format === "jpeg") { + contentType = "image/jpeg"; +} + +// ======================= +// METADATA API +// ======================= +router.get("/metadata/info", (req, res) => { + res.json(metadata); +}); + +// ======================= +// TILE API (XYZ โ†’ TMS) +// ======================= +router.get("/:z/:x/:y", (req, res) => { + const z = Number(req.params.z); + const x = Number(req.params.x); + const y = Number(req.params.y); + + if (!Number.isInteger(z) || !Number.isInteger(x) || !Number.isInteger(y)) { + return res.status(400).send("Invalid tile coordinates"); + } + + // convert XYZ โ†’ TMS + const tmsY = (1 << z) - 1 - y; + + const stmt = tileDb.prepare(` + SELECT tile_data + FROM tiles + WHERE zoom_level = ? + AND tile_column = ? + AND tile_row = ? + `); + + const tile = stmt.get(z, x, tmsY); + + if (!tile) { + return res.status(404).send("Tile not found"); + } + + res.setHeader("Content-Type", contentType); + + if (metadata.format === "pbf") { + res.setHeader("Content-Encoding", "gzip"); + } + + res.send(tile.tile_data); +}); + +module.exports = router; diff --git a/swagger.js b/swagger.js new file mode 100644 index 0000000..69acd3c --- /dev/null +++ b/swagger.js @@ -0,0 +1,729 @@ +const openApiSpec = { + openapi: "3.0.3", + info: { + title: "Ultimate History Map API", + version: "1.0.0", + description: "API docs for tiles, geometries, and entities.", + }, + servers: [ + { + url: "http://localhost:3000", + description: "Local", + }, + ], + tags: [ + { name: "System", description: "Health and meta endpoints" }, + { name: "Tiles", description: "Vector and raster tile endpoints" }, + { name: "Geometries", description: "Geometry CRUD and batch save" }, + { name: "Entities", description: "Entity CRUD" }, + ], + components: { + schemas: { + ErrorResponse: { + type: "object", + properties: { + error: { type: "string" }, + }, + required: ["error"], + }, + SuccessResponse: { + type: "object", + properties: { + success: { type: "boolean" }, + }, + required: ["success"], + }, + Entity: { + type: "object", + properties: { + id: { type: "string" }, + name: { type: "string" }, + slug: { type: "string", nullable: true }, + description: { type: "string", nullable: true }, + type_id: { type: "string" }, + status: { type: "number" }, + created_at: { type: "string", format: "date-time", nullable: true }, + updated_at: { type: "string", format: "date-time", nullable: true }, + geometry_count: { type: "number" }, + }, + required: ["id", "name", "type_id", "geometry_count"], + }, + EntityCreateInput: { + type: "object", + properties: { + name: { type: "string" }, + slug: { type: "string", nullable: true }, + description: { type: "string", nullable: true }, + type_id: { type: "string", nullable: true }, + status: { type: "number", nullable: true }, + }, + required: ["name"], + }, + EntityUpdateInput: { + type: "object", + properties: { + name: { type: "string" }, + slug: { type: "string", nullable: true }, + description: { type: "string", nullable: true }, + type_id: { type: "string" }, + status: { type: "number" }, + }, + }, + GeoJSONGeometry: { + type: "object", + properties: { + type: { + type: "string", + enum: [ + "Point", + "MultiPoint", + "LineString", + "MultiLineString", + "Polygon", + "MultiPolygon", + ], + }, + coordinates: { + type: "array", + items: {}, + }, + }, + required: ["type", "coordinates"], + }, + GeometryFeature: { + type: "object", + properties: { + type: { type: "string", enum: ["Feature"] }, + properties: { + type: "object", + properties: { + id: { type: "string" }, + type: { type: "string", nullable: true }, + time_start: { type: "number", nullable: true }, + time_end: { type: "number", nullable: true }, + binding: { + type: "array", + items: { type: "string" }, + }, + entity_id: { type: "string", nullable: true }, + entity_ids: { + type: "array", + items: { type: "string" }, + }, + entity_name: { type: "string", nullable: true }, + entity_names: { + type: "array", + items: { type: "string" }, + }, + entity_type_id: { type: "string", nullable: true }, + }, + required: ["id"], + }, + geometry: { $ref: "#/components/schemas/GeoJSONGeometry" }, + }, + required: ["type", "properties", "geometry"], + }, + GeometryFeatureCollection: { + type: "object", + properties: { + type: { type: "string", enum: ["FeatureCollection"] }, + features: { + type: "array", + items: { $ref: "#/components/schemas/GeometryFeature" }, + }, + }, + required: ["type", "features"], + }, + GeometryUpsertInput: { + type: "object", + properties: { + geometry: { $ref: "#/components/schemas/GeoJSONGeometry" }, + type: { type: "string", nullable: true }, + time_start: { type: "number", nullable: true }, + time_end: { type: "number", nullable: true }, + binding: { + type: "array", + items: { type: "string" }, + }, + entity_id: { type: "string", nullable: true }, + entity_ids: { + type: "array", + items: { type: "string" }, + }, + }, + required: ["geometry"], + }, + GeometryCreateResponse: { + type: "object", + properties: { + id: { type: "string" }, + }, + required: ["id"], + }, + BatchCreateChange: { + type: "object", + properties: { + action: { type: "string", enum: ["create"] }, + feature: { $ref: "#/components/schemas/GeometryFeature" }, + }, + required: ["action", "feature"], + }, + BatchUpdateChange: { + type: "object", + properties: { + action: { type: "string", enum: ["update"] }, + id: { type: "string" }, + geometry: { $ref: "#/components/schemas/GeoJSONGeometry" }, + type: { type: "string", nullable: true }, + time_start: { type: "number", nullable: true }, + time_end: { type: "number", nullable: true }, + binding: { + type: "array", + items: { type: "string" }, + }, + entity_id: { type: "string", nullable: true }, + entity_ids: { + type: "array", + items: { type: "string" }, + }, + }, + required: ["action", "id", "geometry"], + }, + BatchDeleteChange: { + type: "object", + properties: { + action: { type: "string", enum: ["delete"] }, + id: { type: "string" }, + }, + required: ["action", "id"], + }, + GeometryBatchPayload: { + type: "object", + properties: { + changes: { + type: "array", + items: { + oneOf: [ + { $ref: "#/components/schemas/BatchCreateChange" }, + { $ref: "#/components/schemas/BatchUpdateChange" }, + { $ref: "#/components/schemas/BatchDeleteChange" }, + ], + }, + }, + }, + required: ["changes"], + }, + GeometryBatchResponse: { + type: "object", + properties: { + success: { type: "boolean" }, + applied: { type: "number" }, + }, + required: ["success", "applied"], + }, + MetadataResponse: { + type: "object", + additionalProperties: { + oneOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }], + }, + }, + }, + }, + paths: { + "/": { + get: { + tags: ["System"], + summary: "Health check", + responses: { + 200: { + description: "Server status text", + content: { + "text/plain": { + schema: { type: "string" }, + }, + }, + }, + }, + }, + }, + "/tiles/metadata/info": { + get: { + tags: ["Tiles"], + summary: "Get vector tiles metadata", + responses: { + 200: { + description: "MBTiles metadata", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/MetadataResponse" }, + }, + }, + }, + }, + }, + }, + "/tiles/{z}/{x}/{y}": { + get: { + tags: ["Tiles"], + summary: "Get vector tile by XYZ", + parameters: [ + { name: "z", in: "path", required: true, schema: { type: "integer" } }, + { name: "x", in: "path", required: true, schema: { type: "integer" } }, + { name: "y", in: "path", required: true, schema: { type: "integer" } }, + ], + responses: { + 200: { + description: "Tile binary", + content: { + "application/x-protobuf": { + schema: { type: "string", format: "binary" }, + }, + "image/png": { + schema: { type: "string", format: "binary" }, + }, + "image/jpeg": { + schema: { type: "string", format: "binary" }, + }, + "application/octet-stream": { + schema: { type: "string", format: "binary" }, + }, + }, + }, + 400: { + description: "Invalid tile coordinates", + }, + 404: { + description: "Tile not found", + }, + }, + }, + }, + "/raster-tiles/metadata/info": { + get: { + tags: ["Tiles"], + summary: "Get raster tiles metadata", + responses: { + 200: { + description: "MBTiles metadata", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/MetadataResponse" }, + }, + }, + }, + }, + }, + }, + "/raster-tiles/{z}/{x}/{y}": { + get: { + tags: ["Tiles"], + summary: "Get raster tile by XYZ", + parameters: [ + { name: "z", in: "path", required: true, schema: { type: "integer" } }, + { name: "x", in: "path", required: true, schema: { type: "integer" } }, + { name: "y", in: "path", required: true, schema: { type: "integer" } }, + ], + responses: { + 200: { + description: "Tile binary", + content: { + "image/png": { schema: { type: "string", format: "binary" } }, + "image/jpeg": { schema: { type: "string", format: "binary" } }, + "image/webp": { schema: { type: "string", format: "binary" } }, + "application/octet-stream": { schema: { type: "string", format: "binary" } }, + }, + }, + 400: { + description: "Invalid tile coordinates", + }, + 404: { + description: "Tile not found", + }, + }, + }, + }, + "/entities": { + get: { + tags: ["Entities"], + summary: "List entities", + parameters: [ + { + name: "q", + in: "query", + required: false, + schema: { type: "string" }, + description: "Search by name or slug", + }, + ], + responses: { + 200: { + description: "Entity list", + content: { + "application/json": { + schema: { + type: "array", + items: { $ref: "#/components/schemas/Entity" }, + }, + }, + }, + }, + }, + }, + post: { + tags: ["Entities"], + summary: "Create entity", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/EntityCreateInput" }, + }, + }, + }, + responses: { + 201: { + description: "Entity created", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/Entity" }, + }, + }, + }, + 400: { + description: "Invalid payload", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 409: { + description: "Unique conflict", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + }, + "/entities/search": { + get: { + tags: ["Entities"], + summary: "Search entities by name", + parameters: [ + { + name: "name", + in: "query", + required: true, + schema: { type: "string" }, + description: "Entity name keyword", + }, + { + name: "limit", + in: "query", + required: false, + schema: { type: "integer", minimum: 1, maximum: 100 }, + }, + ], + responses: { + 200: { + description: "Matched entity list", + content: { + "application/json": { + schema: { + type: "array", + items: { $ref: "#/components/schemas/Entity" }, + }, + }, + }, + }, + }, + }, + }, + "/entities/{id}": { + get: { + tags: ["Entities"], + summary: "Get entity by id", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + responses: { + 200: { + description: "Entity", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/Entity" }, + }, + }, + }, + 404: { + description: "Not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + put: { + tags: ["Entities"], + summary: "Update entity", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/EntityUpdateInput" }, + }, + }, + }, + responses: { + 200: { + description: "Entity updated", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/Entity" }, + }, + }, + }, + 400: { + description: "Invalid payload", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 404: { + description: "Not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 409: { + description: "Unique conflict", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + delete: { + tags: ["Entities"], + summary: "Soft-delete entity", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + responses: { + 200: { + description: "Soft-delete success", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/SuccessResponse" }, + }, + }, + }, + 409: { + description: "Entity is still the last active link of one or more geometries", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 404: { + description: "Not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + }, + "/geometries": { + get: { + tags: ["Geometries"], + summary: "Query geometries by bbox, time, and entity", + parameters: [ + { name: "minLng", in: "query", required: true, schema: { type: "number" } }, + { name: "minLat", in: "query", required: true, schema: { type: "number" } }, + { name: "maxLng", in: "query", required: true, schema: { type: "number" } }, + { name: "maxLat", in: "query", required: true, schema: { type: "number" } }, + { name: "time", in: "query", required: false, schema: { type: "integer" } }, + { name: "entity_id", in: "query", required: false, schema: { type: "string" } }, + ], + responses: { + 200: { + description: "Feature collection", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryFeatureCollection" }, + }, + }, + }, + 400: { + description: "Invalid query", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + post: { + tags: ["Geometries"], + summary: "Create geometry", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryUpsertInput" }, + }, + }, + }, + responses: { + 200: { + description: "Created geometry id", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryCreateResponse" }, + }, + }, + }, + 400: { + description: "Invalid payload", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 404: { + description: "Entity not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + }, + "/geometries/{id}": { + put: { + tags: ["Geometries"], + summary: "Update geometry", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryUpsertInput" }, + }, + }, + }, + responses: { + 200: { + description: "Updated", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/SuccessResponse" }, + }, + }, + }, + 400: { + description: "Invalid payload", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + 404: { + description: "Not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + delete: { + tags: ["Geometries"], + summary: "Soft-delete geometry", + parameters: [ + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + responses: { + 200: { + description: "Soft-delete success", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/SuccessResponse" }, + }, + }, + }, + 404: { + description: "Not found", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + }, + "/geometries/batch": { + post: { + tags: ["Geometries"], + summary: "Apply batch create/update/delete geometries", + requestBody: { + required: true, + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryBatchPayload" }, + }, + }, + }, + responses: { + 200: { + description: "Batch applied", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/GeometryBatchResponse" }, + }, + }, + }, + 400: { + description: "Invalid payload", + content: { + "application/json": { + schema: { $ref: "#/components/schemas/ErrorResponse" }, + }, + }, + }, + }, + }, + }, + }, +}; + +module.exports = { + openApiSpec, +}; diff --git a/utils/bbox.js b/utils/bbox.js new file mode 100644 index 0000000..d7408d8 --- /dev/null +++ b/utils/bbox.js @@ -0,0 +1,45 @@ +function getBBox(geometry) { + let minLng = Infinity, minLat = Infinity; + let maxLng = -Infinity, maxLat = -Infinity; + + function process(coords) { + if (typeof coords[0] === "number") { + const [lng, lat] = coords; + + minLng = Math.min(minLng, lng); + minLat = Math.min(minLat, lat); + maxLng = Math.max(maxLng, lng); + maxLat = Math.max(maxLat, lat); + } else { + coords.forEach(process); + } + } + + // ๐Ÿ”ฅ handle theo type cho rรต rร ng + switch (geometry.type) { + case "Point": + process(geometry.coordinates); + break; + + case "MultiPoint": + case "LineString": + process(geometry.coordinates); + break; + + case "MultiLineString": + case "Polygon": + process(geometry.coordinates); + break; + + case "MultiPolygon": + process(geometry.coordinates); + break; + + default: + throw new Error("Unsupported geometry type: " + geometry.type); + } + + return { minLng, minLat, maxLng, maxLat }; +} + +module.exports = { getBBox }; \ No newline at end of file