UNPKG

digipinjs

Version:

A comprehensive TypeScript library for encoding and decoding Indian geographic coordinates into DIGIPIN format (Indian Postal Digital PIN system). Features CLI tools, caching, batch processing, and Express middleware for seamless integration.

74 lines (73 loc) 2.58 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.watchEncodeStream = watchEncodeStream; exports.watchDecodeStream = watchDecodeStream; const readline_1 = __importDefault(require("readline")); const core_1 = require("./core"); const util_1 = require("./util"); function parseCoordinateLine(line, format) { if (format === 'csv') { const [latStr, lngStr] = line.split(',').map((value) => value.trim()); if (!latStr || !lngStr) { throw new Error('Expected "lat,lng" comma separated values'); } const lat = Number(latStr); const lng = Number(lngStr); if (Number.isNaN(lat) || Number.isNaN(lng)) { throw new Error('Unable to parse coordinates from CSV input'); } return { lat, lng }; } const parsed = JSON.parse(line); const lat = parsed.lat ?? parsed.latitude; const lng = parsed.lng ?? parsed.longitude; if (typeof lat !== 'number' || typeof lng !== 'number') { throw new Error('JSON input must contain numeric lat/lng or latitude/longitude fields'); } return { lat, lng }; } function watchEncodeStream(input, options) { const format = options.inputFormat ?? 'json'; const rl = readline_1.default.createInterface({ input, crlfDelay: Infinity }); rl.on('line', (line) => { const raw = line.trim(); if (!raw) { return; } try { const { lat, lng } = parseCoordinateLine(raw, format); const pin = (0, core_1.getDigiPin)(lat, lng, options); options.onResult({ raw, lat, lng, pin }); } catch (error) { options.onError?.(error, raw); } }); return rl; } function watchDecodeStream(input, options) { const rl = readline_1.default.createInterface({ input, crlfDelay: Infinity }); rl.on('line', (line) => { const raw = line.trim(); if (!raw) { return; } try { const normalized = (0, util_1.normalizeDigiPin)(raw); const coords = (0, core_1.getLatLngFromDigiPin)(normalized, options); options.onResult({ raw, pin: normalized, latitude: coords.latitude, longitude: coords.longitude, }); } catch (error) { options.onError?.(error, raw); } }); return rl; }