@dromney/mapthis 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +56 -0
  3. package/dist/ai/index.cjs +474 -0
  4. package/dist/ai/index.cjs.map +1 -0
  5. package/dist/ai/index.d.cts +117 -0
  6. package/dist/ai/index.d.ts +117 -0
  7. package/dist/ai/index.js +447 -0
  8. package/dist/ai/index.js.map +1 -0
  9. package/dist/domain-CZ-L-ntu.d.ts +163 -0
  10. package/dist/domain-Dc1wSTkf.d.cts +163 -0
  11. package/dist/errors-Bw97z_4m.d.cts +12 -0
  12. package/dist/errors-Bw97z_4m.d.ts +12 -0
  13. package/dist/generate/index.cjs +222 -0
  14. package/dist/generate/index.cjs.map +1 -0
  15. package/dist/generate/index.d.cts +140 -0
  16. package/dist/generate/index.d.ts +140 -0
  17. package/dist/generate/index.js +220 -0
  18. package/dist/generate/index.js.map +1 -0
  19. package/dist/geocoding/index.cjs +90 -0
  20. package/dist/geocoding/index.cjs.map +1 -0
  21. package/dist/geocoding/index.d.cts +36 -0
  22. package/dist/geocoding/index.d.ts +36 -0
  23. package/dist/geocoding/index.js +86 -0
  24. package/dist/geocoding/index.js.map +1 -0
  25. package/dist/index.cjs +546 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/index.d.cts +5 -0
  28. package/dist/index.d.ts +5 -0
  29. package/dist/index.js +469 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/parser-CzXzpmVv.d.cts +111 -0
  32. package/dist/parser-N7-fNxeu.d.ts +111 -0
  33. package/dist/react/index.cjs +394 -0
  34. package/dist/react/index.cjs.map +1 -0
  35. package/dist/react/index.js +383 -0
  36. package/dist/react/index.js.map +1 -0
  37. package/dist/schemas-Dy5coqXo.d.cts +484 -0
  38. package/dist/schemas-Dy5coqXo.d.ts +484 -0
  39. package/dist/scrape/index.cjs +133 -0
  40. package/dist/scrape/index.cjs.map +1 -0
  41. package/dist/scrape/index.d.cts +60 -0
  42. package/dist/scrape/index.d.ts +60 -0
  43. package/dist/scrape/index.js +125 -0
  44. package/dist/scrape/index.js.map +1 -0
  45. package/dist/search/index.cjs +76 -0
  46. package/dist/search/index.cjs.map +1 -0
  47. package/dist/search/index.d.cts +75 -0
  48. package/dist/search/index.d.ts +75 -0
  49. package/dist/search/index.js +71 -0
  50. package/dist/search/index.js.map +1 -0
  51. package/dist/types/index.cjs +215 -0
  52. package/dist/types/index.cjs.map +1 -0
  53. package/dist/types/index.d.cts +4 -0
  54. package/dist/types/index.d.ts +4 -0
  55. package/dist/types/index.js +171 -0
  56. package/dist/types/index.js.map +1 -0
  57. package/dist/types-BhqKlq0k.d.ts +31 -0
  58. package/dist/types-rFjK5YcJ.d.cts +31 -0
  59. package/dist/utils/index.cjs +335 -0
  60. package/dist/utils/index.cjs.map +1 -0
  61. package/dist/utils/index.d.cts +363 -0
  62. package/dist/utils/index.d.ts +363 -0
  63. package/dist/utils/index.js +301 -0
  64. package/dist/utils/index.js.map +1 -0
  65. package/package.json +150 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/types/errors.ts","../../src/ai/errors.ts","../../src/ai/prompts.ts","../../src/scrape/errors.ts","../../src/scrape/html.ts","../../src/scrape/text.ts","../../src/ai/summarize.ts","../../src/ai/locations.ts","../../src/ai/openai.ts","../../src/ai/parser.ts"],"names":[],"mappings":";;;;;;AAOO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EACpC,WAAA,CAAY,SAAkB,OAAA,EAAwB;AAClD,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AAAA,EAChB;AACJ,CAAA;;;ACVO,IAAM,OAAA,GAAN,cAAsB,YAAA,CAAa;AAAA,EACtC,WAAA,CAAY,SAAkB,OAAA,EAAwB;AAClD,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,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S,IAAI,CAAA;AAAA,IACtE,sBAAA,EAAwB,CAAC,IAAA,KAAS,sBAAA,CAAuB,SAAS,IAAI,CAAA;AAAA,IACtE,qBAAA,EAAuB,CAAC,GAAA,KAAQ,qBAAA,CAAsB,SAAS,GAAG;AAAA,GACtE;AACJ","file":"index.js","sourcesContent":["/**\n * Base error class for every error thrown by the mapthis package.\n *\n * All feature-specific error classes (scrape, search, ai, geocoding) extend\n * this, so consumers can do `catch (e) { if (e instanceof MapthisError) ... }`\n * to distinguish library errors from other exceptions.\n */\nexport class MapthisError extends Error {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"MapthisError\"\n }\n}\n","import { MapthisError } from \"../types/errors\"\n\nexport class AiError extends MapthisError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"AiError\"\n }\n}\n\n/**\n * The LLM returned zero locations after deduplication.\n */\nexport class NoLocationsFoundError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message ?? \"No locations found in input\", options)\n this.name = \"NoLocationsFoundError\"\n }\n}\n\n/**\n * Summarization pipeline failed (one of the chunk calls rejected).\n */\nexport class SummarizeTextError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"SummarizeTextError\"\n }\n}\n\n/**\n * A JSON schema passed to the LLM was rejected as invalid by the provider.\n */\nexport class InvalidJsonSchemaError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"InvalidJsonSchemaError\"\n }\n}\n\n/**\n * The LLM response could not be parsed as JSON (typically because the output\n * was truncated or malformed).\n */\nexport class AiResponseJsonError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"AiResponseJsonError\"\n }\n}\n\n/**\n * Input text exceeded the model's context window.\n */\nexport class AiInputLengthError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"AiInputLengthError\"\n }\n}\n\n/**\n * The LLM hit the output token limit before completing its JSON response.\n */\nexport class AiOutputLengthError extends AiError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"AiOutputLengthError\"\n }\n}\n","import type { JSONSchema7Object } from \"json-schema\"\n\n/**\n * Semantic version of the location-extraction system prompt. Stored alongside\n * each place record in the private app so results can be re-run when the\n * prompt is updated. Bump when you change {@link LOCATIONS_SYSTEM_MESSAGE} or\n * {@link LOCATIONS_SCHEMA} in a way that meaningfully changes output.\n */\nexport const LOCATIONS_PROMPT_VERSION = \"0.0.1\"\n\nexport const LOCATIONS_FUNCTIONS_NAME = \"get_places\"\n\nexport const LOCATIONS_SYSTEM_MESSAGE = `You parse a list of place addresses, corresponding brief one-sentence descriptions, and a descriptive title (preferably directly quoted) from text. These addresses might be countries, cities, attractions, parks, bars, etc.\nIf the text seems to be listing places that are all within a single parent place, you don't return the parent place, but you do add it to all the childrens' addresses.\nFor example, for an article about places in greece, you would not return \"greece\", but if the Acropolis was mentioned, you would return \"Acropolis, Athens, Greece\"\n\nYou ignore extraneous text, such as recommended articles, advertisments, etc.\n`\n\nexport const LOCATIONS_SCHEMA: JSONSchema7Object = {\n type: \"object\",\n required: [\"locations\", \"title\"],\n properties: {\n locations: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"address\", \"description\"],\n properties: {\n address: { type: \"string\" },\n description: { type: \"string\" },\n },\n },\n },\n title: { type: \"string\" },\n },\n}\n\nexport const LOCATIONS_MAX_OUTPUT_TOKENS = 500\n\n/**\n * Semantic version of the summarization prompt. Bump when meaningful changes\n * are made to {@link SUMMARIZATION_PROMPT}.\n */\nexport const SUMMARIZE_PROMPT_VERSION = \"0.0.1\"\n\nexport const SUMMARIZATION_PROMPT = `Summarize the given text. The summary must reduce the number of characters from the original text by at least a factor of {RATIO}.\nFor example, text of 1000 characters must output a summary less than {EXAMPLE} characters.\nThis summary will be used to extract a list of locations and addresses, so keep any text that seems to be a list of locations/places, a location and paragraph describing it, or otherwise clearly a location name or address.\nHere is the text:\n`\n","import { MapthisError } from \"../types/errors\"\n\nexport class ScrapeError extends MapthisError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"ScrapeError\"\n }\n}\n\n/**\n * Thrown when a provided URL fails validation or cannot be parsed by `fetch`.\n */\nexport class InvalidUrlError extends ScrapeError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"InvalidUrlError\"\n }\n}\n\n/**\n * Thrown when a remote server returns 401 or 403 for an HTML fetch, meaning\n * the page does not permit anonymous scraping.\n */\nexport class HtmlUnauthorizedError extends ScrapeError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"HtmlUnauthorizedError\"\n }\n}\n\n/**\n * Thrown when the underlying `html-to-text` conversion fails.\n */\nexport class HtmlToTextError extends ScrapeError {\n constructor(message?: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"HtmlToTextError\"\n }\n}\n","import { z } from \"zod\"\nimport { HtmlUnauthorizedError, InvalidUrlError, ScrapeError } from \"./errors\"\n\nconst withHttps = (url: string): string => {\n const hasHttp = /^http?:\\/\\//i.test(url)\n const hasHttps = /^https?:\\/\\//i.test(url)\n if (!hasHttp && !hasHttps) return `https://${url}`\n return url\n}\n\n/**\n * Fetch the raw HTML of a URL, performing light validation first.\n *\n * - URLs without a scheme are prefixed with `https://`.\n * - URL shape is validated via Zod before the network call.\n * - 401/403 responses throw {@link HtmlUnauthorizedError}.\n * - Other non-OK responses throw {@link ScrapeError} with the status text.\n * - `TypeError` from `fetch` (typically malformed URL) is rethrown as\n * {@link InvalidUrlError}.\n *\n * This function does not set any special headers, user agent, or cookies.\n * Sites with aggressive bot-detection may return empty bodies or errors; the\n * caller is responsible for retry / user-agent rotation strategies if needed.\n */\nexport async function getHtmlFromUrl(url: string): Promise<string> {\n const urlFixed = withHttps(url.toLowerCase())\n const isUrl = z.string().url().safeParse(urlFixed)\n if (!isUrl.success) throw new InvalidUrlError(`Invalid URL: ${url}`)\n\n try {\n const response = await fetch(urlFixed)\n const html = await response.text()\n if (response.status === 403 || response.status === 401) {\n throw new HtmlUnauthorizedError(\n `${response.status} Not authorized to scrape this website`,\n )\n }\n if (!response.ok) {\n throw new ScrapeError(\n `Bad response when getting HTML. Status: ${response.status} ${response.statusText}`,\n )\n }\n return html\n } catch (error) {\n if (error instanceof TypeError) {\n throw new InvalidUrlError(`Invalid URL. Original error: ${error.message}`)\n }\n throw error\n }\n}\n","import { convert } from \"html-to-text\"\nimport { HtmlToTextError } from \"./errors\"\nimport { getHtmlFromUrl } from \"./html\"\n\nconst SKIP_SELECTORS = [\n \"img\",\n \"header\",\n \"footer\",\n \"audio\",\n \"button\",\n \"canvas\",\n \"code\",\n \"nav\",\n \"#nav\",\n \"figure\",\n \"figcaption\",\n \".comment\",\n \".comments\",\n \"#comments\",\n \"#related-posts\",\n \"#related\",\n \".related\",\n \".related-posts\",\n] as const\n\n/**\n * Convert raw HTML to plain text suitable for LLM consumption.\n *\n * The converter is configured to:\n * - strip anchor hrefs when they duplicate the link text;\n * - skip navigation, footer, comments, related-post widgets, images, and\n * other non-content elements;\n * - collapse repeated blank lines and double spaces so token count doesn't\n * balloon from whitespace.\n */\nexport function htmlToText(html: string): string {\n try {\n let out = convert(html, {\n wordwrap: false,\n selectors: [\n {\n selector: \"a\",\n options: {\n ignoreHref: true,\n hideLinkHrefIfSameAsText: true,\n },\n },\n ...SKIP_SELECTORS.map((tag) => ({ selector: tag, format: \"skip\" })),\n ],\n })\n out = out.replaceAll(\"\\r\\n\", \"\\n\")\n // Iteratively collapse blank lines and double spaces. 20 passes is\n // overkill for any realistic input but cheap and bounds worst case.\n for (let i = 0; i < 20; i++) {\n out = out.replaceAll(\"\\n\\n\\n\", \"\\n\\n\")\n out = out.replaceAll(\" \", \" \")\n }\n return out\n } catch (error) {\n if (error instanceof Error) {\n throw new HtmlToTextError(`HTML to text conversion failed: ${error.message}`, {\n cause: error,\n })\n }\n throw new HtmlToTextError(\"HTML to text conversion failed\")\n }\n}\n\n/**\n * Convenience: fetch a URL and convert its HTML to plain text in one call.\n *\n * Equivalent to `htmlToText(await getHtmlFromUrl(url))`.\n */\nexport async function getTextFromUrl(url: string): Promise<string> {\n const html = await getHtmlFromUrl(url)\n return htmlToText(html)\n}\n","import { SummarizeTextError } from \"./errors\"\nimport type { OpenAiBackend } from \"./openai\"\nimport { SUMMARIZATION_PROMPT, SUMMARIZE_PROMPT_VERSION } from \"./prompts\"\nimport type { SummarizedText } from \"./types\"\n\n/**\n * Reduce a large text to a summary that will fit inside the model's context\n * window alongside a known downstream prompt (e.g. the location-extraction\n * call).\n *\n * Algorithm overview\n * ------------------\n * We need to fit both the summary and a downstream \"final\" prompt into the\n * model's context window. Given:\n *\n * - `token_limit` — model context window (with a safety factor)\n * - `text_tokens` — size of the input text\n * - `summarize_prompt_tokens` — size of the summarization prompt itself\n * - `final_prompt_tokens` — size of the downstream prompt\n * - `final_output_tokens` — expected size of the downstream response\n *\n * We split the input into chunks, summarize each in parallel, and concatenate\n * the results. The per-chunk size is chosen so that the combined summary\n * leaves room for the downstream prompt:\n *\n * final_input_tokens = token_limit - final_output_tokens\n * summary_output_tokens = final_input_tokens - final_prompt_tokens\n * num_chunks = ceil((text_tokens + summary_output_tokens)\n * / (token_limit - summarize_prompt_tokens))\n * chunk_output_tokens = summary_output_tokens / num_chunks\n * chunk_input_tokens = token_limit - summarize_prompt_tokens - chunk_output_tokens\n *\n * A safety factor is applied to chunk output sizes because LLMs routinely\n * overshoot explicit length instructions.\n */\nexport async function summarizeText(\n backend: OpenAiBackend,\n text: string,\n finalPrompt = \"\",\n finalOutputTokens = 0,\n chunkOutputSafetyFactor = 0.3,\n tokenLimitSafetyFactor = 0.02,\n): Promise<SummarizedText> {\n const tokenLimit = backend.tokenLimit * (1 - tokenLimitSafetyFactor)\n const textTokens = backend.countTokens(text)\n const summarizePromptTokens = backend.countTokens(SUMMARIZATION_PROMPT)\n const finalPromptTokens = backend.countTokens(finalPrompt)\n\n const finalInputTokens = tokenLimit - finalOutputTokens\n const summaryOutputTokens = finalInputTokens - finalPromptTokens\n\n const numChunks = Math.max(\n 1,\n Math.ceil((textTokens + summaryOutputTokens) / (tokenLimit - summarizePromptTokens)),\n )\n const chunkOutputTokens = Math.floor(\n (summaryOutputTokens / numChunks) * (1 - chunkOutputSafetyFactor),\n )\n const chunkInputTokens = Math.floor(tokenLimit - summarizePromptTokens - chunkOutputTokens)\n const summaryRatio = chunkOutputTokens / chunkInputTokens\n\n // Split the text into chunks that each fit inside `chunkInputTokens`.\n // Lines longer than a single chunk are force-split by token, not by\n // character, so UTF-8 multibyte characters aren't corrupted.\n const textLines = text.split(\"\\n\")\n const chunks: string[] = []\n\n let currentChunk = \"\"\n let currentChunkTokens = 0\n const nextChunk = (): void => {\n if (currentChunk) chunks.push(currentChunk)\n currentChunk = \"\"\n currentChunkTokens = 0\n }\n\n // We need an encoder for the force-split path. The backend's countTokens\n // gives us length but not the encoded array; for force-splitting we only\n // need to chunk by an approximate token count using the same rounding.\n // To keep this function backend-agnostic, we fall back to character-based\n // splitting for over-long lines (rare edge case in practice).\n for (const line of textLines) {\n const numLineTokens = backend.countTokens(line) + 1 // +1 for the newline\n\n if (numLineTokens > chunkInputTokens) {\n // Long line: flush current chunk, then split this line by\n // approximate token ratio into sub-chunks.\n nextChunk()\n const charsPerToken = line.length / Math.max(1, backend.countTokens(line))\n const charsPerChunk = Math.max(1, Math.floor(chunkInputTokens * charsPerToken))\n for (let i = 0; i < line.length; i += charsPerChunk) {\n chunks.push(line.slice(i, i + charsPerChunk))\n }\n continue\n }\n\n if (currentChunkTokens + numLineTokens > chunkInputTokens) {\n nextChunk()\n }\n currentChunkTokens += numLineTokens\n currentChunk += line + \"\\n\"\n }\n nextChunk()\n\n try {\n const ratioText = (Math.ceil(summaryRatio * 10) / 10).toFixed(1)\n const exampleText = Math.ceil(1000 / Math.max(summaryRatio, 0.01)).toFixed(0)\n const summaryPrompt = SUMMARIZATION_PROMPT.replace(\"{RATIO}\", ratioText).replace(\n \"{EXAMPLE}\",\n exampleText,\n )\n\n let inputTokens = 0\n let outputTokens = 0\n const summaries = await Promise.all(\n chunks.map(async (chunk) => {\n const response = await backend.chatCompletion(summaryPrompt + chunk)\n inputTokens += response.inputTokens\n outputTokens += response.outputTokens\n return response.output\n }),\n )\n\n const summarized = summaries.join(\"\\n\")\n const summarizedTokens = backend.countTokens(summarized)\n\n return {\n text,\n textTokens,\n summarized,\n summarizedTokens,\n inputTokens,\n outputTokens,\n chunks: chunks.length,\n summarizePromptVersion: SUMMARIZE_PROMPT_VERSION,\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new SummarizeTextError(`Failed to summarize text: ${error.message}`, {\n cause: error,\n })\n }\n throw new SummarizeTextError(\"Failed to summarize text (unknown error)\")\n }\n}\n","import { getHtmlFromUrl } from \"../scrape/html\"\nimport { htmlToText } from \"../scrape/text\"\nimport type { ParsedLocations } from \"../types/domain\"\nimport { NoLocationsFoundError } from \"./errors\"\nimport type { OpenAiBackend } from \"./openai\"\nimport {\n LOCATIONS_FUNCTIONS_NAME,\n LOCATIONS_MAX_OUTPUT_TOKENS,\n LOCATIONS_PROMPT_VERSION,\n LOCATIONS_SCHEMA,\n LOCATIONS_SYSTEM_MESSAGE,\n} from \"./prompts\"\nimport { summarizeText } from \"./summarize\"\nimport type { GetLocationsResponse } from \"./types\"\n\nconst FINAL_PROMPT = LOCATIONS_SYSTEM_MESSAGE + JSON.stringify(LOCATIONS_SCHEMA) + LOCATIONS_FUNCTIONS_NAME\n\nasync function callLocationExtraction(backend: OpenAiBackend, text: string) {\n const out = await backend.chatFunctionJson<ParsedLocations>(\n LOCATIONS_SYSTEM_MESSAGE,\n text,\n LOCATIONS_SCHEMA,\n LOCATIONS_FUNCTIONS_NAME,\n )\n\n // LLM frequently returns the same address twice across different prompts.\n // Dedupe by address string.\n const seen = new Set<string>()\n const unique = out.output.locations.filter((loc) => {\n if (seen.has(loc.address)) return false\n seen.add(loc.address)\n return true\n })\n if (unique.length === 0) throw new NoLocationsFoundError()\n out.output.locations = unique\n\n return out\n}\n\n/**\n * Parse locations from freeform text. Two-stage: summarize to fit the context\n * window, then a function-calling JSON completion for extraction.\n */\nexport async function parseLocationsFromText(\n backend: OpenAiBackend,\n text: string,\n): Promise<GetLocationsResponse> {\n const {\n summarized,\n inputTokens: sumIn,\n outputTokens: sumOut,\n textTokens,\n summarizedTokens,\n summarizePromptVersion,\n } = await summarizeText(backend, text, FINAL_PROMPT, LOCATIONS_MAX_OUTPUT_TOKENS)\n\n const {\n output,\n inputTokens: locIn,\n outputTokens: locOut,\n } = await callLocationExtraction(backend, summarized)\n\n return {\n output,\n locationInputTokens: locIn,\n locationOutputTokens: locOut,\n summaryInputTokens: sumIn,\n summaryOutputTokens: sumOut,\n inputTokens: sumIn + locIn,\n outputTokens: sumOut + locOut,\n textTokens,\n summarizedTokens,\n summaryPromptVersion: summarizePromptVersion,\n locationPromptVersion: LOCATIONS_PROMPT_VERSION,\n }\n}\n\n/**\n * Parse locations from HTML. Equivalent to `htmlToText` followed by\n * {@link parseLocationsFromText}.\n */\nexport async function parseLocationsFromHtml(\n backend: OpenAiBackend,\n html: string,\n): Promise<GetLocationsResponse> {\n return parseLocationsFromText(backend, htmlToText(html))\n}\n\n/**\n * Parse locations from a URL. Equivalent to fetching the HTML, converting to\n * text, and calling {@link parseLocationsFromText}. Throws any scrape errors\n * unchanged.\n */\nexport async function parseLocationsFromUrl(\n backend: OpenAiBackend,\n url: string,\n): Promise<GetLocationsResponse> {\n const html = await getHtmlFromUrl(url)\n return parseLocationsFromHtml(backend, html)\n}\n","import { encodingForModel, getEncoding, type Tiktoken, type TiktokenModel } from \"js-tiktoken\"\nimport OpenAI from \"openai\"\nimport type { JSONSchema7Object } from \"json-schema\"\nimport {\n AiInputLengthError,\n AiOutputLengthError,\n AiResponseJsonError,\n AiError,\n InvalidJsonSchemaError,\n} from \"./errors\"\nimport type { OpenAIOutput } from \"./types\"\n\nexport const DEFAULT_MODEL = \"gpt-4o-mini\"\nexport const DEFAULT_TOKEN_LIMIT = 128000\n\n/**\n * An OpenAI-backed inference context shared by the summarizer and location\n * parser. Instances are produced by {@link createOpenAiBackend} so API keys\n * and model choices live in the consumer's code, never in module-level state.\n */\nexport interface OpenAiBackend {\n readonly model: string\n readonly tokenLimit: number\n countTokens(text: string): number\n chatCompletion(content: string): Promise<OpenAIOutput<string>>\n chatFunctionJson<T>(\n systemMessage: string,\n userMessage: string,\n schema: JSONSchema7Object,\n functionName: string,\n ): Promise<OpenAIOutput<T>>\n}\n\nexport interface OpenAiBackendConfig {\n /** OpenAI API key. Passed directly to the SDK. */\n apiKey: string\n /** Model name passed to the completions API. Defaults to `gpt-4o-mini`. */\n model?: string\n /** Context-window budget used by the summarizer. Defaults to 128k. */\n tokenLimit?: number\n /**\n * Optional base URL for the OpenAI API. Use this to route through an\n * OpenAI-compatible gateway (Azure, Together, etc.).\n */\n baseURL?: string\n}\n\nfunction resolveEncoding(model: string): Tiktoken {\n try {\n return encodingForModel(model as TiktokenModel)\n } catch {\n // Fallback for models tiktoken does not recognize by name.\n return getEncoding(\"cl100k_base\")\n }\n}\n\n/**\n * Construct an {@link OpenAiBackend} bound to a specific API key and model.\n */\nexport function createOpenAiBackend(config: OpenAiBackendConfig): OpenAiBackend {\n const model = config.model ?? DEFAULT_MODEL\n const tokenLimit = config.tokenLimit ?? DEFAULT_TOKEN_LIMIT\n const openai = new OpenAI({\n apiKey: config.apiKey,\n ...(config.baseURL ? { baseURL: config.baseURL } : {}),\n })\n const encoding = resolveEncoding(model)\n\n return {\n model,\n tokenLimit,\n\n countTokens(text: string): number {\n return encoding.encode(text).length\n },\n\n async chatCompletion(content: string): Promise<OpenAIOutput<string>> {\n const response = await openai.chat.completions.create({\n messages: [{ role: \"user\", content }],\n model,\n })\n return {\n output: response.choices[0]?.message.content ?? \"\",\n inputTokens: response.usage?.prompt_tokens ?? 0,\n outputTokens: response.usage?.completion_tokens ?? 0,\n }\n },\n\n async chatFunctionJson<T>(\n systemMessage: string,\n userMessage: string,\n schema: JSONSchema7Object,\n functionName: string,\n ): Promise<OpenAIOutput<T>> {\n try {\n const completion = await openai.chat.completions.create({\n model,\n messages: [\n { role: \"system\", content: systemMessage },\n { role: \"user\", content: userMessage },\n ],\n functions: [{ name: functionName, parameters: schema }],\n function_call: { name: functionName },\n })\n\n const functionCall = completion.choices[0]?.message.function_call\n if (!functionCall) {\n throw new AiResponseJsonError(\"No function call in OpenAI response\")\n }\n\n const inputTokens = completion.usage?.prompt_tokens ?? 0\n const outputTokens = completion.usage?.completion_tokens ?? 0\n\n try {\n const output = JSON.parse(functionCall.arguments) as T\n return { output, inputTokens, outputTokens }\n } catch (error) {\n if (error instanceof SyntaxError) {\n const msg = error.message.toLowerCase()\n if (\n msg.includes(\"unexpected end of json input\") ||\n msg.includes(\"unterminated string in js\")\n ) {\n throw new AiOutputLengthError(\n `Output tokens exceeded: ${error.message}`,\n { cause: error },\n )\n }\n throw new AiResponseJsonError(\n `Failed to parse JSON from OpenAI response: ${error.message}`,\n { cause: error },\n )\n }\n throw new AiResponseJsonError(\n \"Failed to parse JSON from OpenAI response (unknown reason)\",\n )\n }\n } catch (error) {\n if (error instanceof AiError) throw error\n if (error instanceof OpenAI.APIError) {\n const msg = error.message.toLowerCase()\n if (msg.includes(\"maximum context\")) {\n throw new AiInputLengthError(`Text too long: ${error.message}`, {\n cause: error,\n })\n }\n if (msg.includes(\"invalid schema\")) {\n throw new InvalidJsonSchemaError(`Invalid schema: ${error.message}`, {\n cause: error,\n })\n }\n throw new AiError(`OpenAI error: ${error.message}`, { cause: error })\n }\n throw new AiError(\"OpenAI error (unknown)\", {\n cause: error instanceof Error ? error : undefined,\n })\n }\n },\n }\n}\n","import {\n parseLocationsFromHtml,\n parseLocationsFromText,\n parseLocationsFromUrl,\n} from \"./locations\"\nimport { createOpenAiBackend, type OpenAiBackendConfig } from \"./openai\"\nimport type { GetLocationsResponse } from \"./types\"\n\n/**\n * A configured location-extraction pipeline. Hold onto one of these for the\n * lifetime of your app — it wraps an OpenAI client and a tiktoken encoder.\n */\nexport interface LocationParser {\n parseLocationsFromText(text: string): Promise<GetLocationsResponse>\n parseLocationsFromHtml(html: string): Promise<GetLocationsResponse>\n parseLocationsFromUrl(url: string): Promise<GetLocationsResponse>\n}\n\nexport type LocationParserConfig = OpenAiBackendConfig\n\n/**\n * Create a {@link LocationParser} bound to an OpenAI API key.\n *\n * @example\n * ```ts\n * const parser = createLocationParser({\n * apiKey: process.env.OPENAI_API_KEY!,\n * model: \"gpt-4o-mini\",\n * })\n * const { output } = await parser.parseLocationsFromUrl(\n * \"https://example.com/best-restaurants-tokyo\",\n * )\n * console.log(output.title, output.locations)\n * ```\n */\nexport function createLocationParser(config: LocationParserConfig): LocationParser {\n const backend = createOpenAiBackend(config)\n return {\n parseLocationsFromText: (text) => parseLocationsFromText(backend, text),\n parseLocationsFromHtml: (html) => parseLocationsFromHtml(backend, html),\n parseLocationsFromUrl: (url) => parseLocationsFromUrl(backend, url),\n }\n}\n"]}
@@ -0,0 +1,163 @@
1
+ import { a as PlaceProvider, G as GenerationSourceType } from './schemas-Dy5coqXo.js';
2
+
3
+ /**
4
+ * Hand-rolled plain TypeScript domain types for mapthis entities.
5
+ *
6
+ * These types are the open-source contract for the shape of maps, places, and
7
+ * groups. They intentionally avoid any ORM dependency — consumers using
8
+ * Prisma, Drizzle, Kysely, or a custom data layer should write thin adapter
9
+ * functions (e.g. `prismaMapToMap`) that map their DB records to these types.
10
+ *
11
+ * Fields use `Date` for timestamps (not strings). Callers serializing to JSON
12
+ * should convert at their transport boundary.
13
+ *
14
+ * Note: the core aggregate type is named `PlaceMap` rather than `Map` to
15
+ * avoid shadowing the global `Map` class in consumer code — types and values
16
+ * technically live in separate namespaces, but the name collision hurts IDE
17
+ * navigation and code review legibility.
18
+ */
19
+ interface Timestamped {
20
+ createdAt: Date;
21
+ updatedAt: Date;
22
+ deletedAt: Date | null;
23
+ }
24
+ interface Audited {
25
+ createdBy: string | null;
26
+ updatedBy: string | null;
27
+ deletedBy: string | null;
28
+ }
29
+ interface Partner extends Timestamped {
30
+ id: string;
31
+ createdBy: string;
32
+ updatedBy: string;
33
+ deletedBy: string | null;
34
+ name: string;
35
+ image: string | null;
36
+ }
37
+ type PartnerUserRole = "owner" | "admin" | "user";
38
+ interface PartnerUser extends Timestamped {
39
+ id: string;
40
+ createdBy: string;
41
+ updatedBy: string;
42
+ role: PartnerUserRole;
43
+ partnerId: string;
44
+ userId: string;
45
+ }
46
+ interface PartnerUrl extends Timestamped, Audited {
47
+ id: string;
48
+ url: string;
49
+ partnerId: string;
50
+ }
51
+ /**
52
+ * A "map" in the product sense: a titled, user-owned collection of places
53
+ * grouped by {@link PlaceGroup}s.
54
+ */
55
+ interface PlaceMap extends Timestamped, Audited {
56
+ id: string;
57
+ ipAddress: string | null;
58
+ title: string | null;
59
+ description: string | null;
60
+ userPublic: boolean;
61
+ partnerPublic: boolean;
62
+ publicEdit: boolean;
63
+ partnerId: string | null;
64
+ externalId: string | null;
65
+ url: string | null;
66
+ sourceType: GenerationSourceType | null;
67
+ source: string | null;
68
+ copiedFrom: string | null;
69
+ requestedThrough: string | null;
70
+ }
71
+ interface PlaceGroup extends Timestamped, Audited {
72
+ id: string;
73
+ mapId: string;
74
+ color: string | null;
75
+ hidden: boolean;
76
+ name: string | null;
77
+ description: string | null;
78
+ source: string | null;
79
+ sourceType: string | null;
80
+ showDirections: boolean;
81
+ position: number | null;
82
+ parentGroupId: string | null;
83
+ }
84
+ interface PositionedPlaceGroup extends PlaceGroup {
85
+ position: number;
86
+ }
87
+ interface Place extends Timestamped, Audited {
88
+ id: string;
89
+ query: string | null;
90
+ name: string | null;
91
+ address: string | null;
92
+ lat: number | null;
93
+ lon: number | null;
94
+ description: string | null;
95
+ hidden: boolean;
96
+ flyTo: boolean;
97
+ position: number | null;
98
+ groupId: string | null;
99
+ provider: PlaceProvider | null;
100
+ providerId: string | null;
101
+ source: string | null;
102
+ sourceType: string | null;
103
+ error: string | null;
104
+ mapId: string;
105
+ locationPromptVersion: string | null;
106
+ summaryPromptVersion: string | null;
107
+ }
108
+ /**
109
+ * A {@link PlaceMap} with its groups and places eagerly loaded. This is the
110
+ * typical shape returned from an API that serves a full map page.
111
+ */
112
+ interface PopulatedPlaceMap extends PlaceMap {
113
+ groups: PlaceGroup[];
114
+ places: Place[];
115
+ }
116
+ /**
117
+ * A partner-owned pointer from a URL or external ID to the {@link PlaceMap}
118
+ * that should be served as the default for that key.
119
+ */
120
+ interface DefaultPlaceMap extends Timestamped, Audited {
121
+ id: string;
122
+ mapId: string;
123
+ partnerId: string;
124
+ url: string | null;
125
+ externalId: string | null;
126
+ }
127
+ /**
128
+ * A single location extracted from freeform input by an LLM, before geocoding.
129
+ */
130
+ interface ParsedLocation {
131
+ address: string;
132
+ description?: string;
133
+ }
134
+ /**
135
+ * A titled collection of parsed locations — typically one LLM output.
136
+ */
137
+ interface ParsedLocations {
138
+ title: string;
139
+ locations: ParsedLocation[];
140
+ }
141
+ interface PlaceQueryResultData {
142
+ name: string;
143
+ address: string;
144
+ lat: number;
145
+ lng: number;
146
+ provider: PlaceProvider;
147
+ providerId: string;
148
+ }
149
+ /**
150
+ * The result of geocoding a single `ParsedLocation` — either data or error,
151
+ * never both.
152
+ */
153
+ type PlaceQueryResult = {
154
+ input: ParsedLocation;
155
+ } & ({
156
+ data: PlaceQueryResultData;
157
+ error: null;
158
+ } | {
159
+ data: null;
160
+ error: string;
161
+ });
162
+
163
+ export type { Audited as A, DefaultPlaceMap as D, ParsedLocation as P, Timestamped as T, ParsedLocations as a, Partner as b, PartnerUrl as c, PartnerUser as d, PartnerUserRole as e, Place as f, PlaceGroup as g, PlaceMap as h, PlaceQueryResult as i, PopulatedPlaceMap as j, PositionedPlaceGroup as k };
@@ -0,0 +1,163 @@
1
+ import { a as PlaceProvider, G as GenerationSourceType } from './schemas-Dy5coqXo.cjs';
2
+
3
+ /**
4
+ * Hand-rolled plain TypeScript domain types for mapthis entities.
5
+ *
6
+ * These types are the open-source contract for the shape of maps, places, and
7
+ * groups. They intentionally avoid any ORM dependency — consumers using
8
+ * Prisma, Drizzle, Kysely, or a custom data layer should write thin adapter
9
+ * functions (e.g. `prismaMapToMap`) that map their DB records to these types.
10
+ *
11
+ * Fields use `Date` for timestamps (not strings). Callers serializing to JSON
12
+ * should convert at their transport boundary.
13
+ *
14
+ * Note: the core aggregate type is named `PlaceMap` rather than `Map` to
15
+ * avoid shadowing the global `Map` class in consumer code — types and values
16
+ * technically live in separate namespaces, but the name collision hurts IDE
17
+ * navigation and code review legibility.
18
+ */
19
+ interface Timestamped {
20
+ createdAt: Date;
21
+ updatedAt: Date;
22
+ deletedAt: Date | null;
23
+ }
24
+ interface Audited {
25
+ createdBy: string | null;
26
+ updatedBy: string | null;
27
+ deletedBy: string | null;
28
+ }
29
+ interface Partner extends Timestamped {
30
+ id: string;
31
+ createdBy: string;
32
+ updatedBy: string;
33
+ deletedBy: string | null;
34
+ name: string;
35
+ image: string | null;
36
+ }
37
+ type PartnerUserRole = "owner" | "admin" | "user";
38
+ interface PartnerUser extends Timestamped {
39
+ id: string;
40
+ createdBy: string;
41
+ updatedBy: string;
42
+ role: PartnerUserRole;
43
+ partnerId: string;
44
+ userId: string;
45
+ }
46
+ interface PartnerUrl extends Timestamped, Audited {
47
+ id: string;
48
+ url: string;
49
+ partnerId: string;
50
+ }
51
+ /**
52
+ * A "map" in the product sense: a titled, user-owned collection of places
53
+ * grouped by {@link PlaceGroup}s.
54
+ */
55
+ interface PlaceMap extends Timestamped, Audited {
56
+ id: string;
57
+ ipAddress: string | null;
58
+ title: string | null;
59
+ description: string | null;
60
+ userPublic: boolean;
61
+ partnerPublic: boolean;
62
+ publicEdit: boolean;
63
+ partnerId: string | null;
64
+ externalId: string | null;
65
+ url: string | null;
66
+ sourceType: GenerationSourceType | null;
67
+ source: string | null;
68
+ copiedFrom: string | null;
69
+ requestedThrough: string | null;
70
+ }
71
+ interface PlaceGroup extends Timestamped, Audited {
72
+ id: string;
73
+ mapId: string;
74
+ color: string | null;
75
+ hidden: boolean;
76
+ name: string | null;
77
+ description: string | null;
78
+ source: string | null;
79
+ sourceType: string | null;
80
+ showDirections: boolean;
81
+ position: number | null;
82
+ parentGroupId: string | null;
83
+ }
84
+ interface PositionedPlaceGroup extends PlaceGroup {
85
+ position: number;
86
+ }
87
+ interface Place extends Timestamped, Audited {
88
+ id: string;
89
+ query: string | null;
90
+ name: string | null;
91
+ address: string | null;
92
+ lat: number | null;
93
+ lon: number | null;
94
+ description: string | null;
95
+ hidden: boolean;
96
+ flyTo: boolean;
97
+ position: number | null;
98
+ groupId: string | null;
99
+ provider: PlaceProvider | null;
100
+ providerId: string | null;
101
+ source: string | null;
102
+ sourceType: string | null;
103
+ error: string | null;
104
+ mapId: string;
105
+ locationPromptVersion: string | null;
106
+ summaryPromptVersion: string | null;
107
+ }
108
+ /**
109
+ * A {@link PlaceMap} with its groups and places eagerly loaded. This is the
110
+ * typical shape returned from an API that serves a full map page.
111
+ */
112
+ interface PopulatedPlaceMap extends PlaceMap {
113
+ groups: PlaceGroup[];
114
+ places: Place[];
115
+ }
116
+ /**
117
+ * A partner-owned pointer from a URL or external ID to the {@link PlaceMap}
118
+ * that should be served as the default for that key.
119
+ */
120
+ interface DefaultPlaceMap extends Timestamped, Audited {
121
+ id: string;
122
+ mapId: string;
123
+ partnerId: string;
124
+ url: string | null;
125
+ externalId: string | null;
126
+ }
127
+ /**
128
+ * A single location extracted from freeform input by an LLM, before geocoding.
129
+ */
130
+ interface ParsedLocation {
131
+ address: string;
132
+ description?: string;
133
+ }
134
+ /**
135
+ * A titled collection of parsed locations — typically one LLM output.
136
+ */
137
+ interface ParsedLocations {
138
+ title: string;
139
+ locations: ParsedLocation[];
140
+ }
141
+ interface PlaceQueryResultData {
142
+ name: string;
143
+ address: string;
144
+ lat: number;
145
+ lng: number;
146
+ provider: PlaceProvider;
147
+ providerId: string;
148
+ }
149
+ /**
150
+ * The result of geocoding a single `ParsedLocation` — either data or error,
151
+ * never both.
152
+ */
153
+ type PlaceQueryResult = {
154
+ input: ParsedLocation;
155
+ } & ({
156
+ data: PlaceQueryResultData;
157
+ error: null;
158
+ } | {
159
+ data: null;
160
+ error: string;
161
+ });
162
+
163
+ export type { Audited as A, DefaultPlaceMap as D, ParsedLocation as P, Timestamped as T, ParsedLocations as a, Partner as b, PartnerUrl as c, PartnerUser as d, PartnerUserRole as e, Place as f, PlaceGroup as g, PlaceMap as h, PlaceQueryResult as i, PopulatedPlaceMap as j, PositionedPlaceGroup as k };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Base error class for every error thrown by the mapthis package.
3
+ *
4
+ * All feature-specific error classes (scrape, search, ai, geocoding) extend
5
+ * this, so consumers can do `catch (e) { if (e instanceof MapthisError) ... }`
6
+ * to distinguish library errors from other exceptions.
7
+ */
8
+ declare class MapthisError extends Error {
9
+ constructor(message?: string, options?: ErrorOptions);
10
+ }
11
+
12
+ export { MapthisError as M };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Base error class for every error thrown by the mapthis package.
3
+ *
4
+ * All feature-specific error classes (scrape, search, ai, geocoding) extend
5
+ * this, so consumers can do `catch (e) { if (e instanceof MapthisError) ... }`
6
+ * to distinguish library errors from other exceptions.
7
+ */
8
+ declare class MapthisError extends Error {
9
+ constructor(message?: string, options?: ErrorOptions);
10
+ }
11
+
12
+ export { MapthisError as M };
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ // src/types/schemas.ts
6
+ zod.z.literal("openai");
7
+ zod.z.union([zod.z.literal("google"), zod.z.literal("locationiq")]);
8
+ var generationSourceType = zod.z.union([
9
+ zod.z.literal("blank"),
10
+ zod.z.literal("autocomplete"),
11
+ zod.z.literal("url"),
12
+ zod.z.literal("text"),
13
+ zod.z.literal("list")
14
+ ]);
15
+ var latitude = zod.z.coerce.number().min(-90, "Min latitude is -90").max(90, "Max latitude is 90");
16
+ var longitude = zod.z.coerce.number().min(-180, "Min longitude is -180").max(180, "Max longitude is 180");
17
+ zod.z.object({
18
+ lat: latitude,
19
+ lng: longitude
20
+ });
21
+ var placesFromUrl = zod.z.string().url({ message: "Invalid url" }).min(6).max(2048);
22
+ var placesFromList = zod.z.preprocess(
23
+ (v) => String(v).split("\n").map((line) => line.trim()).filter((line) => !!line).join("\n"),
24
+ zod.z.string().min(6, "Must be at least 6 characters").max(1e3, "List too long")
25
+ ).refine(
26
+ (v) => !v.split("\n").find((line) => line.length < 2),
27
+ "All lines must be at least 2 characters"
28
+ );
29
+ var placesFromText = zod.z.string().min(6, "Must be at least 6 characters").max(2e3, "Over character limit");
30
+ var mapExternalId = zod.z.string().min(6).max(100);
31
+ var mapTitle = zod.z.string().min(3, { message: "Title must be at least 3 characters" }).max(100, { message: "Title must be at most 100 characters" });
32
+ var mapDescription = zod.z.string().max(1e3, { message: "Limit is 1000 characters" });
33
+ var mapCreationQuery = zod.z.string().min(10, "Minimum 10 characters for search").max(200, "Maximum 200 characters");
34
+ var groupName = zod.z.string().min(3, { message: "Name must be at least 3 characters" }).max(200, { message: "Name must be at most 200 characters" });
35
+ var groupDescription = zod.z.string().max(400, { message: "Limit is 400 characters" });
36
+ var groupColor = zod.z.string().startsWith("#").length(7);
37
+ var placeName = zod.z.string().min(2, { message: "Name must be at least 2 characters" }).max(200, { message: "Name must be at most 200 characters" });
38
+ var placeDescription = zod.z.string().max(400, { message: "Limit is 400 characters" });
39
+ var createMapBase = zod.z.object({
40
+ title: mapTitle.optional(),
41
+ description: mapDescription.optional(),
42
+ externalId: mapExternalId.optional()
43
+ });
44
+ createMapBase.extend({
45
+ sourceType: generationSourceType,
46
+ source: zod.z.string().optional()
47
+ });
48
+ createMapBase.extend({
49
+ url: placesFromUrl
50
+ });
51
+ createMapBase.extend({
52
+ list: placesFromList
53
+ });
54
+ createMapBase.extend({
55
+ text: placesFromText
56
+ });
57
+ createMapBase.extend({
58
+ queryOrUrl: zod.z.union([mapCreationQuery, placesFromUrl])
59
+ });
60
+ var addPlacesBaseSchema = zod.z.object({
61
+ sourceType: generationSourceType,
62
+ source: zod.z.string()
63
+ });
64
+ addPlacesBaseSchema.extend({
65
+ mapId: zod.z.string(),
66
+ groupId: zod.z.string().optional()
67
+ });
68
+ zod.z.object({
69
+ url: placesFromUrl
70
+ });
71
+ zod.z.object({
72
+ list: placesFromList
73
+ });
74
+ zod.z.object({
75
+ text: placesFromText
76
+ });
77
+ var providerAutocompletePlace = zod.z.object({
78
+ query: zod.z.string(),
79
+ provider: zod.z.literal("google"),
80
+ providerId: zod.z.string(),
81
+ name: zod.z.string(),
82
+ description: zod.z.string().optional(),
83
+ address: zod.z.string(),
84
+ lat: zod.z.number().min(-90).max(90),
85
+ lng: zod.z.number().min(-180).max(180)
86
+ });
87
+ providerAutocompletePlace.extend({
88
+ mapId: zod.z.string(),
89
+ groupId: zod.z.string().optional()
90
+ });
91
+ zod.z.object({
92
+ title: mapTitle,
93
+ description: mapDescription.optional(),
94
+ userPublic: zod.z.boolean().optional(),
95
+ partnerPublic: zod.z.boolean().optional(),
96
+ url: zod.z.string().url().nullable().optional()
97
+ });
98
+ zod.z.object({
99
+ groups: zod.z.array(
100
+ zod.z.object({
101
+ id: zod.z.string().uuid().nullable(),
102
+ position: zod.z.number()
103
+ })
104
+ ),
105
+ places: zod.z.array(
106
+ zod.z.object({
107
+ id: zod.z.string(),
108
+ groupId: zod.z.string().uuid().nullable(),
109
+ position: zod.z.number()
110
+ })
111
+ )
112
+ });
113
+ zod.z.object({
114
+ id: zod.z.string(),
115
+ name: placeName,
116
+ description: placeDescription.optional(),
117
+ hidden: zod.z.boolean()
118
+ });
119
+ zod.z.object({
120
+ query: mapCreationQuery
121
+ });
122
+ zod.z.object({
123
+ name: groupName,
124
+ description: groupDescription.optional(),
125
+ parentGroupId: zod.z.string().optional(),
126
+ color: groupColor.optional()
127
+ });
128
+ zod.z.object({
129
+ id: zod.z.string().uuid(),
130
+ color: groupColor.nullable(),
131
+ hidden: zod.z.boolean(),
132
+ name: groupName,
133
+ description: groupDescription.optional()
134
+ });
135
+ var placeMeta = zod.z.object({
136
+ id: zod.z.string(),
137
+ updatedAt: zod.z.coerce.date(),
138
+ groupId: zod.z.string().nullable(),
139
+ position: zod.z.number().nullable(),
140
+ error: zod.z.string().nullable(),
141
+ lat: zod.z.number().nullable(),
142
+ lon: zod.z.number().nullable(),
143
+ name: zod.z.string().nullable()
144
+ });
145
+ placeMeta.extend({
146
+ position: zod.z.number()
147
+ });
148
+ placeMeta.extend({
149
+ lat: zod.z.number(),
150
+ lon: zod.z.number(),
151
+ error: zod.z.null()
152
+ });
153
+
154
+ // src/generate/generator.ts
155
+ var DEFAULT_TITLES = {
156
+ url: "Map from Site",
157
+ text: "Map from Text",
158
+ list: "Map from List"
159
+ };
160
+ function toUsage(r) {
161
+ const { output: _output, ...rest } = r;
162
+ return rest;
163
+ }
164
+ function createMapGenerator(config) {
165
+ const { parser, geocoder } = config;
166
+ return {
167
+ async generateFromSource(options) {
168
+ let parsedLocs = [];
169
+ let title = DEFAULT_TITLES[options.sourceType];
170
+ let usage = void 0;
171
+ let locationPromptVersion = void 0;
172
+ let summaryPromptVersion = void 0;
173
+ switch (options.sourceType) {
174
+ case "url": {
175
+ const url = placesFromUrl.parse(options.source);
176
+ const llm = await parser.parseLocationsFromUrl(url);
177
+ parsedLocs = llm.output.locations;
178
+ if (llm.output.title) title = llm.output.title;
179
+ locationPromptVersion = llm.locationPromptVersion;
180
+ summaryPromptVersion = llm.summaryPromptVersion;
181
+ usage = toUsage(llm);
182
+ break;
183
+ }
184
+ case "text": {
185
+ const text = placesFromText.parse(options.source);
186
+ const llm = await parser.parseLocationsFromText(text);
187
+ parsedLocs = llm.output.locations;
188
+ if (llm.output.title) title = llm.output.title;
189
+ locationPromptVersion = llm.locationPromptVersion;
190
+ summaryPromptVersion = llm.summaryPromptVersion;
191
+ usage = toUsage(llm);
192
+ break;
193
+ }
194
+ case "list": {
195
+ const list = placesFromList.parse(options.source);
196
+ parsedLocs = list.trim().split("\n").map((line) => ({ address: line, description: "" }));
197
+ break;
198
+ }
199
+ default: {
200
+ const _exhaustive = options;
201
+ throw new Error(
202
+ `Unsupported sourceType: ${_exhaustive.sourceType}`
203
+ );
204
+ }
205
+ }
206
+ const places = await geocoder.geocodeMany(parsedLocs);
207
+ return {
208
+ title,
209
+ places,
210
+ sourceType: options.sourceType,
211
+ source: options.source,
212
+ locationPromptVersion,
213
+ summaryPromptVersion,
214
+ usage
215
+ };
216
+ }
217
+ };
218
+ }
219
+
220
+ exports.createMapGenerator = createMapGenerator;
221
+ //# sourceMappingURL=index.cjs.map
222
+ //# sourceMappingURL=index.cjs.map