From e1e729a5ea489ba6e214186e1265a9a0e20db5ba Mon Sep 17 00:00:00 2001 From: Lee Overy Date: Sun, 19 Apr 2026 17:37:05 +0100 Subject: [PATCH 1/5] =?UTF-8?q?feat(knowledge):=20setup=20wizard=20?= =?UTF-8?q?=E2=80=94=20system=20config=20+=20project=20init=20+=20stub=20m?= =?UTF-8?q?ode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the setup stub with an interactive readline wizard that handles system config (~/.config/workflows/config.json) and project init (.workflows/.knowledge/config.json + store.msp + metadata.json) in one guided flow. Aborts cleanly on non-TTY invocation. Idempotent: fully configured projects prompt to skip; partial configs are completed. OpenAI path validates the API key via a test embed; stub path writes a minimal config for keyword-only mode. Co-Authored-By: Claude Opus 4.7 (1M context) --- .tick/tasks.jsonl | 4 +- .../workflow-knowledge/scripts/knowledge.cjs | 154 ++++--- src/knowledge/config.js | 26 ++ src/knowledge/index.js | 13 +- src/knowledge/setup.js | 402 ++++++++++++++++++ tests/scripts/test-knowledge-cli.sh | 16 +- tests/scripts/test-knowledge-config.cjs | 198 ++++++++- 7 files changed, 742 insertions(+), 71 deletions(-) create mode 100644 src/knowledge/setup.js diff --git a/.tick/tasks.jsonl b/.tick/tasks.jsonl index 099244284..c3c7e7945 100644 --- a/.tick/tasks.jsonl +++ b/.tick/tasks.jsonl @@ -29,8 +29,8 @@ {"id":"tick-09d9ca","title":"Knowledge SKILL.md + Two-Step Retrieval Documentation","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-1"],"description":"Problem: The knowledge base CLI exists (Phases 1-4) and is wired into skills (Phase 5), but Claude has no documentation explaining what it is, how to use it, or when to query it. Without Layer 1, Layers 2 and 3 have nothing to reference for API details.\n\nSolution: Create the knowledge skill file (SKILL.md) that serves as the API documentation layer — what commands exist, how to call them, what the output looks like, and how the two-step retrieval pattern works.\n\nOutcome: A comprehensive skill file that any processing skill can reference for knowledge base API details, enabling Claude to query the knowledge base correctly.\n\nDo:\n- Create skills/workflow-knowledge/SKILL.md following the project's skill file conventions (see CLAUDE.md Skill File Structure section).\n- This is a model-invocable skill, not user-invocable. It is loaded by reference from Layer 2 usage references (Task 6-2). It is NOT directly invoked by users.\n- Content sections:\n\n PURPOSE:\n - What the knowledge base is: a RAG system storing all workflow artifacts at full fidelity for semantic search\n - Why it exists: cross-work-unit and intra-work-unit context surfacing\n - What it indexes: research, discussion, investigation, specification (not planning, implementation, review)\n\n QUERY COMMAND:\n - Single query: node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003csearch_term\u003e [flags]\n - Batch query: node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003cterm1\u003e \u003cterm2\u003e [termN...] [flags]\n Multiple positional arguments run separate searches, merge results, deduplicate by chunk ID (highest score kept), apply --limit to merged set. Efficient: one store load, multiple searches.\n - Flags: --work-type, --phase, --work-unit (re-ranking hint, not filter), --limit\n - Search modes: hybrid (default when provider configured), keyword-only (when no provider)\n - Query construction guidance: use natural language, not topic slugs. Descriptive queries produce better semantic matching. Multiple queries from different angles are encouraged.\n - Example queries showing good vs poor query construction\n\n OUTPUT FORMAT:\n - Document the exact format (from design doc lines 580-603):\n [N results]\n [phase | work_unit/topic | confidence | YYYY-MM-DD]\n chunk content verbatim\n Source: source_file_path\n - Result count header, provenance line, verbatim content, source path\n - Empty results: [0 results]\n - Stub mode note when applicable: [keyword-only mode — configure embedding provider for semantic search]\n\n CONFIDENCE TIERS:\n - Explain what confidence means and how to weigh it:\n specification (high) — validated decisions, what was decided and why\n investigation (medium) — diagnostic knowledge, tied to specific symptoms\n discussion (low-medium) — conversational, may contain corrected assumptions\n research (low) — exploratory, may contain dead ends and rejected paths\n - Low confidence is not low value — research that rejected an approach prevents re-exploring dead ends\n\n TWO-STEP RETRIEVAL PATTERN:\n - Step 1: query returns chunks with provenance (lightweight, lands in context)\n - Step 2: if a chunk looks relevant, read the actual source file (source_file in metadata) for full detail\n - This keeps context lean — surface-level awareness, deep dive on demand\n - Claude should NOT read source files for every result, only when a chunk warrants deeper investigation\n\n WHAT NOT TO DO:\n - Do not dump large result sets into context speculatively\n - Do not query using topic slugs as search terms (poor semantic signal)\n - Do not query during specification phase (explicitly excluded — spec turns decisions into a golden doc, cross-cutting concerns merge at planning time)\n - Do not prepend metadata to stored content (already in enum fields)\n\nAcceptance Criteria:\n- SKILL.md exists at skills/workflow-knowledge/SKILL.md\n- Documents both single and batch query invocation forms\n- Documents all query flags and their behaviour\n- Documents the exact output format with examples\n- Documents confidence tiers with guidance on how to weigh them\n- Documents the two-step retrieval pattern (query -\u003e read source file on demand)\n- Documents what NOT to do (spec exclusion, slug queries, speculative dumps)\n- Follows project skill file conventions from CLAUDE.md\n- Can be loaded by reference from Layer 2 files (Task 6-2)\n\nTests:\n- No automated tests — documentation task. Validation is manual:\n - Read the SKILL.md and verify it provides enough information to correctly construct and interpret knowledge queries\n - Verify it follows the project's skill file structure conventions\n\nEdge Cases:\n- The SKILL.md must describe BOTH hybrid and keyword-only modes without making keyword-only feel broken — it is a supported degraded mode\n- Must not duplicate the CLI help text verbatim — this is higher-level guidance about when and why, not just how\n- Must explain that --work-unit is a re-ranking hint, not a filter — this is a common misunderstanding that would produce wrong queries if not clear\n- Batch query section must explain deduplication and merged limit behaviour\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 1 description), Retrieved Context Format (lines 576-605, exact output format), Confidence Tiers (lines 514-525), Two-step retrieval pattern (lines 735-737), Query construction (line 737), Batch query (line 602-603, merged and deduplicated), Specification excluded from automatic retrieval (line 560)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T18:59:31Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:01:08Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:22:30Z","updated":"2026-04-18T19:01:08Z","closed":"2026-04-18T19:01:08Z"} {"id":"tick-c5a9f0","title":"Per-Phase Usage References + Contextual Query at Phase Start","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-2"],"description":"Problem: Layer 1 (SKILL.md) documents the API, but Claude needs phase-specific guidance on WHEN to query and WHY — the trigger heuristics contextualised for each phase's work. Without Layer 2, Claude has the capability but not the judgment to use it effectively. Additionally, Claude needs explicit guidance on how to handle query failures — the design doc mandates pausing the workflow, not silently proceeding.\n\nSolution: Create usage reference files loaded early in processing skills that describe when and why to query during each specific phase, how to handle failures, plus the contextual query at phase start for research, discussion, and investigation.\n\nOutcome: Every processing skill loads phase-appropriate querying guidance early in its flow, the three early phases perform a contextual query at phase start, and query failures are handled by pausing with user options rather than silently skipping.\n\nDo:\n\nUSAGE REFERENCE FILES (Layer 2):\n- Create reference files — either one shared file or per-phase files, depending on how much the guidance differs between phases. The design doc (line 720) says: may be shared if guidance is generic enough, or local per phase if each needs different emphasis.\n- Recommended approach: one shared reference at skills/workflow-shared/references/knowledge-usage.md that covers the common trigger heuristics, with phase-specific notes where needed. This avoids maintaining 8 near-identical files.\n- Content:\n - Load the knowledge SKILL.md (Layer 1, Task 6-1) by reference for API details\n - Trigger heuristics — when to query (from design doc lines 551-557):\n 1. At topic boundaries — conversation edges toward adjacent territory\n 2. Upstream/downstream dependencies — current topic may affect or be affected by other work\n 3. Unfamiliar territory — not sure whether something was explored before\n 4. User prompts — user asks to check for prior context\n - Encourage proactive querying — under-querying is the bigger risk (design doc line 1003)\n - Multiple queries from different angles are expected and encouraged\n - Query construction: use natural language derived from what is currently being discussed, not topic names\n - Two-step retrieval reminder: query first (lightweight), read source file only when a chunk warrants investigation\n\nQUERY FAILURE HANDLING (from design doc lines 767-776):\n- This is skill-level behavior, not CLI behavior. The CLI retries 3 times and then exits with a non-zero code and error message (Task 4-4). The SKILL must handle what happens next:\n 1. If knowledge query fails (non-zero exit): PAUSE the workflow. Do not silently proceed without context.\n 2. Present the error clearly: what failed, likely causes (API key expired, network down, store corrupted).\n 3. Offer the user two options: fix the issue and retry, or explicitly choose to proceed without knowledge context.\n 4. If the user chooses to proceed: continue the phase but note that knowledge retrieval was skipped. This note should be visible in the output so the user knows context may be missing.\n- The design doc is emphatic: the value of the knowledge base is too high to silently skip (line 776).\n- This failure handling guidance goes in the usage reference (Layer 2) so it applies to all phases that load it.\n\n- Phase-specific notes within the shared reference (or in separate files if warranted):\n - Research: query at start + throughout. Early phase, high chance of overlap with prior work.\n - Discussion: query at start + throughout. Decisions being made that may relate to prior decisions.\n - Investigation: query at start + throughout. Symptoms and root causes may have been seen before.\n - Specification: EXCLUDED from automatic retrieval. Explicit note: do not query during spec authoring. Cross-cutting concerns merge at planning time, not spec time (design doc line 560).\n - Scoping: query throughout. Quick-fix scoping benefits from knowing if the issue was discussed elsewhere.\n - Planning: query throughout, especially for cross-cutting context. The explicit cross-cutting query is handled separately (Task 6-3).\n - Implementation: query when hitting unfamiliar territory or when a task touches areas covered by prior work.\n - Review: query to verify decisions against prior context.\n\nCONTEXTUAL QUERY AT PHASE START:\n- Add to the processing skills for research, discussion, and investigation: at the beginning of the phase (after loading references, before the first substantive step), construct a natural language query from available context and search the knowledge base.\n- Available context for query construction (from design doc line 549): topic description, bootstrap answers, handoff context, problem statement — whatever is available at that point.\n- NOT the topic slug. The query must be descriptive: not auth-flow but user authentication flow using OAuth2 with PKCE for mobile and web clients.\n- Returns a small, focused result set. Zero cost if nothing comes back. High value when it catches prior work.\n- This is a single query, not a dump. If results come back, Claude reads them and proceeds with that context. If nothing comes back, proceed as normal.\n- Specification is EXCLUDED — no contextual query at spec phase start.\n\nLOAD DIRECTIVES IN PROCESSING SKILLS:\n- Add a load directive for the usage reference early in each processing skill (alongside where case conventions are loaded). The exact insertion point varies per skill — read each to find the right place.\n- Processing skills that need this:\n skills/workflow-research-process/SKILL.md\n skills/workflow-discussion-process/SKILL.md\n skills/workflow-investigation-process/SKILL.md\n skills/workflow-scoping-process/SKILL.md\n skills/workflow-planning-process/SKILL.md\n skills/workflow-implementation-process/SKILL.md\n skills/workflow-review-process/SKILL.md\n- Specification process does NOT load the usage reference (excluded from automatic retrieval).\n\nALLOWED-TOOLS FOR REMAINING PROCESSING SKILLS:\n- Add Bash(node .claude/skills/workflow-knowledge/scripts/knowledge.cjs) to:\n skills/workflow-planning-process/SKILL.md\n skills/workflow-implementation-process/SKILL.md\n skills/workflow-review-process/SKILL.md\n- These 3 were deferred from Phase 5 — now they need it for autonomous querying.\n- Scoping process already has it from Phase 5 Task 5-2. Research, discussion, investigation, specification process already have it from Task 5-2.\n\nAcceptance Criteria:\n- Usage reference file(s) exist with trigger heuristics and phase-specific guidance\n- Usage reference loads Layer 1 (SKILL.md) by reference for API details\n- Query failure handling documented: pause workflow, present error, offer user choice to proceed or fix\n- All 7 processing skills (except specification) load the usage reference early in their flow\n- Specification process does NOT load the usage reference\n- Research, discussion, and investigation processing skills perform a contextual query at phase start\n- Contextual query uses descriptive natural language, not topic slugs\n- allowed-tools added to planning, implementation, and review processing skills\n- Trigger heuristics match the design doc (topic boundaries, dependencies, unfamiliar territory, user prompts)\n\nTests:\n- No automated tests — skill file editing task. Validation is manual:\n - Start a discussion in a test project with existing indexed knowledge -\u003e verify contextual query runs and surfaces relevant prior work\n - Start a specification -\u003e verify no contextual query runs\n - Simulate query failure -\u003e verify workflow pauses with user options (not silent skip)\n - Verify all processing skills load the usage reference\n\nEdge Cases:\n- Contextual query with no prior knowledge indexed — returns [0 results], phase proceeds normally with no delay or noise\n- Phase start with very little context available (e.g., just a topic name) — construct the best query possible from what is available. A poor query that returns nothing is fine. The design doc accepts zero cost if nothing comes back.\n- Query failure during contextual query at phase start — same failure handling applies (pause, present, offer choice). The contextual query is not exempt from failure handling.\n- Shared vs per-phase reference: if a shared reference becomes unwieldy with too many phase-specific notes, split into per-phase files. Start shared, split if needed.\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 2 description), Autonomous querying trigger heuristics (lines 551-557), Contextual query at phase start (line 549), Specification excluded (line 560), Query Failures section (lines 767-776, pause workflow, present error, user choice), Autonomous query guardrails review finding #16 (line 1002)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T19:01:23Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:10:11Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:23:15Z","updated":"2026-04-18T19:10:11Z","closed":"2026-04-18T19:10:11Z"} {"id":"tick-2841d6","title":"Inline Callouts + Planning Entry Cross-Cutting Query","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-3"],"description":"Problem: Layer 2 provides general guidance loaded once at the start of a phase, but Claude can lose awareness of the knowledge base as a conversation develops. Layer 3 addresses this with targeted nudges at specific moments where querying is most valuable. Additionally, the planning entry skill has an existing manual approach for cross-cutting context that should be replaced with a targeted semantic query.\n\nSolution: Add inline callouts at pertinent points in processing skills and replace the planning entry cross-cutting context approach with a knowledge base query.\n\nOutcome: Claude gets timely reminders to check the knowledge base at high-value moments, and planning entry uses semantic search instead of manually reading every cross-cutting spec.\n\nDo:\n\nINLINE CALLOUTS (Layer 3):\n- Add brief reminders within the step flow of processing skills at moments where the knowledge base is most valuable. These are nudges, not full reference loads — same pattern as existing callouts for review agents and commit reminders (design doc line 722).\n- Format: a short inline note like: Consider querying the knowledge base — this subtopic may have been explored in prior work. Or: If this constraint seems familiar, check the knowledge base for prior decisions.\n- Placement is judgment-based — read each processing skill and identify moments where:\n - A complex subtopic is being explored\n - A decision is being made that could conflict with prior work\n - An assumption is being introduced that may have been validated or rejected before\n - The conversation moves to adjacent territory\n- Processing skills to add callouts to (all except specification):\n skills/workflow-research-process/SKILL.md — when exploring new directions, before concluding\n skills/workflow-discussion-process/SKILL.md — when discussing options, before deciding\n skills/workflow-investigation-process/SKILL.md — when analysing root causes\n skills/workflow-scoping-process/SKILL.md — when scoping constraints\n skills/workflow-planning-process/SKILL.md — when designing phases/tasks that touch other areas\n skills/workflow-implementation-process/SKILL.md — when hitting unfamiliar code areas\n skills/workflow-review-process/SKILL.md — when verifying decisions against original intent\n- These are 1-2 line callouts embedded at specific step boundaries, NOT new steps or reference loads. They should feel natural, not interruptive.\n- Do NOT add callouts to the specification process — specification is excluded from automatic retrieval.\n\nPLANNING ENTRY CROSS-CUTTING QUERY:\n- This replaces existing functionality in skills/workflow-planning-entry/references/cross-cutting-context.md (design doc line 562).\n- The current approach: reads every cross-cutting specification and manually assesses relevance to the current topic. This is expensive (loads all cross-cutting specs into context) and keyword-dependent (misses semantic connections).\n- The replacement: a targeted semantic query filtered to work_type: cross-cutting.\n node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003ctopic_description\u003e --work-type cross-cutting --limit 10\n- The query term should be constructed from the current topic's specification summary or description — not the topic name.\n- Results are cross-cutting specs that are semantically relevant to the current plan. Claude reads the results, identifies applicable cross-cutting decisions, and incorporates them into the planning context.\n- This is a deterministic step replacing existing functionality, not a speculative search (design doc line 726).\n- Update or replace cross-cutting-context.md to use the knowledge query instead of manual spec reading.\n- Ensure skills/workflow-planning-entry/SKILL.md has allowed-tools for knowledge.cjs if not already present (it may have been added as an entry-point skill in Task 5-1, but planning-entry is a phase entry skill, not an entry-point skill — check).\n\nAcceptance Criteria:\n- Inline callouts exist at pertinent points in 7 processing skills (all except specification)\n- Callouts are brief nudges (1-2 lines), not full reference loads\n- Callouts are placed at high-value moments identified by reading each skill's flow\n- Specification process has NO callouts\n- Planning entry cross-cutting query replaces the manual approach in cross-cutting-context.md\n- Cross-cutting query uses --work-type cross-cutting filter\n- Cross-cutting query uses descriptive topic text, not topic slug\n- Planning entry has allowed-tools for knowledge.cjs\n\nTests:\n- No automated tests — skill file editing task. Validation is manual:\n - Read processing skills and verify callouts are placed at high-value moments\n - Start planning for a topic with existing cross-cutting specs indexed -\u003e verify the query surfaces relevant cross-cutting decisions\n - Verify the old manual cross-cutting spec reading approach is replaced, not duplicated\n\nEdge Cases:\n- Planning entry cross-cutting query when no cross-cutting specs are indexed — returns [0 results], planning proceeds without cross-cutting context (same as today when no cross-cutting specs exist)\n- Callout placement in skills with varying step structures — read each skill carefully, do not add callouts at the same structural position in every skill. Placement is semantic, not mechanical.\n- The planning-entry skill is a phase entry skill (internal, user-invocable: false), not an entry-point skill. It was NOT updated in Task 5-1 (which targeted start-*/continue-* skills). It needs allowed-tools for the cross-cutting query added here.\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 3 description — inline callouts same pattern as review agents and commit reminders), Planning entry cross-cutting query (line 562, replaces existing manual approach, filtered to work_type: cross-cutting), and the note that this is a deterministic step replacing existing functionality (line 726)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T19:10:26Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:13:35Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:23:50Z","updated":"2026-04-18T19:13:35Z","closed":"2026-04-18T19:13:35Z"} -{"id":"tick-2e511f","title":"Phase 7: Setup Wizard","status":"open","priority":2,"refs":["knowledge-base-7"],"parent":"tick-cbbd13","created":"2026-04-09T19:04:09Z","updated":"2026-04-09T19:04:09Z"} -{"id":"tick-78c1c7","title":"Setup Wizard: System Config + Project Init + Stub Mode","status":"open","priority":2,"type":"task","refs":["knowledge-base-7-1"],"description":"Problem: Users need a single entry point to configure the knowledge base for the first time. This involves system-level configuration (API keys, provider choice) that lives in the user's home directory and project-level initialisation that lives in .workflows/. Both must be handled in one flow so the user doesn't need to know the internal structure.\n\nSolution: Implement the knowledge setup command as an interactive wizard using Node's readline interface, handling system config, project init, and stub mode in one guided flow.\n\nOutcome: A user can run one command and have a fully configured knowledge base ready for use, with clear prompts at each step and graceful handling of partial or existing configuration.\n\nDo:\n- Implement the setup command handler in the CLI (invoked by Task 3-1 dispatch).\n- Invocation: knowledge setup (no arguments)\n- HUMAN-ONLY — uses interactive prompts throughout via Node readline interface (process.stdin/process.stdout). Claude cannot handle interactive terminals — this is the natural protection against accidental invocation (design doc line 632).\n\nSTEP 1: SYSTEM CONFIG (~/.config/workflows/config.json):\n- Check if system config already exists.\n - If it exists: read it, display current settings, ask if the user wants to reconfigure or skip. If skip, proceed to Step 2.\n - If it does not exist: create ~/.config/workflows/ directory if needed.\n- Prompt for provider:\n Which embedding provider? (openai / skip)\n - openai: proceed with OpenAI configuration\n - skip: stub mode (keyword-only search, no embeddings). Write config with no provider field. Display clear message about limitations. Proceed to Step 2.\n- If openai selected:\n - Prompt for model (default: text-embedding-3-small):\n Embedding model [text-embedding-3-small]:\n - Prompt for dimensions (default: 1536):\n Vector dimensions [1536]:\n - Prompt for API key env var name (default: OPENAI_API_KEY):\n API key environment variable [OPENAI_API_KEY]:\n - Check if the env var is set in the current environment:\n - If set: validate with a test embed call — embed a short test string and verify a vector is returned. If validation fails, display the error and ask the user to fix it or continue anyway.\n - If not set: warn the user and explain they need to set this env var in their shell profile before using the knowledge base. Do not block — they may be setting it up for later.\n- Write system config to ~/.config/workflows/config.json:\n { knowledge: { provider, model, dimensions, api_key_env, similarity_threshold: 0.8, decay_months: 6 } }\n- For stub mode (skip): write minimal config:\n { knowledge: { similarity_threshold: 0.8, decay_months: 6 } }\n\nSTEP 2: PROJECT INIT (.workflows/.knowledge/):\n- Check if project knowledge base directory already exists with config.json and store.msp.\n - If fully initialised: display status and ask to skip or reinitialise. If skip, proceed to Step 3.\n - If partially initialised (directory exists but missing files): complete the missing pieces.\n - If not initialised: create from scratch.\n- Create .workflows/.knowledge/ directory.\n- Write .workflows/.knowledge/config.json — project-level config. By default this is empty (inherits everything from system config):\n { knowledge: {} }\n The user can customise project-level overrides later by editing this file.\n- Create an empty Orama store and save it to .workflows/.knowledge/store.msp using createStore + saveStore from Phase 1. Use the dimensions from the resolved config (system + project merge).\n- Write .workflows/.knowledge/metadata.json with the provider/model/dimensions from the resolved config (or empty provider fields for stub mode).\n\nREADLINE INTERFACE:\n- Use Node built-in readline module (require('readline')).\n- Create interface with input: process.stdin, output: process.stdout.\n- Use rl.question() for prompts with defaults shown in brackets.\n- Close the interface when done.\n- If stdin is not a TTY (piped input, non-interactive environment): detect with process.stdin.isTTY and abort with message: knowledge setup requires an interactive terminal. Run it directly, not through Claude.\n\nAcceptance Criteria:\n- knowledge setup prompts for provider, model, dimensions, API key env var\n- System config is written to ~/.config/workflows/config.json\n- Project knowledge base is initialised at .workflows/.knowledge/ with config.json, store.msp, metadata.json\n- Test embed call validates the API key when configured\n- Stub mode writes config without provider, displays limitation message\n- Existing system config is detected and can be skipped or reconfigured\n- Existing project init is detected and can be skipped\n- Non-interactive terminal is detected and aborts with clear message\n- npm run build succeeds with the setup command included\n\nTests:\n- No automated tests for the interactive flow — it is inherently human-driven.\n- Unit tests for the non-interactive parts (tests/scripts/test-knowledge-config.cjs — extend from Task 3-1):\n - it creates a valid system config object from provider choices\n - it creates a valid stub-mode config object\n - it detects existing system config correctly\n - it detects existing project init correctly\n - it creates the project directory structure correctly\n\nEdge Cases:\n- ~/.config/workflows/ directory does not exist — create it (mkdir -p equivalent with { recursive: true })\n- .workflows/ directory does not exist — this means no workflow project exists. Display error: No .workflows/ directory found. Initialise a workflow project first.\n- System config file exists but is invalid JSON — display error, offer to overwrite\n- API key env var is set but the test embed call fails (wrong key, network error) — display error, offer to continue setup anyway (user may fix the key later)\n- User presses Ctrl+C during setup — readline handles SIGINT, process exits cleanly\n- Previous setup was stub mode, user re-runs with openai — detect existing store has no vectors, suggest knowledge rebuild after setup completes\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, interactive wizard flow, skip logic, stub mode), System config creation flow review finding #18 (line 1008), Configuration Hierarchy section (lines 258-301, system and project config schemas)","parent":"tick-2e511f","created":"2026-04-09T19:05:02Z","updated":"2026-04-09T19:05:02Z"} +{"id":"tick-2e511f","title":"Phase 7: Setup Wizard","status":"in_progress","priority":2,"refs":["knowledge-base-7"],"transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:28:36Z","auto":true}],"parent":"tick-cbbd13","created":"2026-04-09T19:04:09Z","updated":"2026-04-19T16:28:36Z"} +{"id":"tick-78c1c7","title":"Setup Wizard: System Config + Project Init + Stub Mode","status":"done","priority":2,"type":"task","refs":["knowledge-base-7-1"],"description":"Problem: Users need a single entry point to configure the knowledge base for the first time. This involves system-level configuration (API keys, provider choice) that lives in the user's home directory and project-level initialisation that lives in .workflows/. Both must be handled in one flow so the user doesn't need to know the internal structure.\n\nSolution: Implement the knowledge setup command as an interactive wizard using Node's readline interface, handling system config, project init, and stub mode in one guided flow.\n\nOutcome: A user can run one command and have a fully configured knowledge base ready for use, with clear prompts at each step and graceful handling of partial or existing configuration.\n\nDo:\n- Implement the setup command handler in the CLI (invoked by Task 3-1 dispatch).\n- Invocation: knowledge setup (no arguments)\n- HUMAN-ONLY — uses interactive prompts throughout via Node readline interface (process.stdin/process.stdout). Claude cannot handle interactive terminals — this is the natural protection against accidental invocation (design doc line 632).\n\nSTEP 1: SYSTEM CONFIG (~/.config/workflows/config.json):\n- Check if system config already exists.\n - If it exists: read it, display current settings, ask if the user wants to reconfigure or skip. If skip, proceed to Step 2.\n - If it does not exist: create ~/.config/workflows/ directory if needed.\n- Prompt for provider:\n Which embedding provider? (openai / skip)\n - openai: proceed with OpenAI configuration\n - skip: stub mode (keyword-only search, no embeddings). Write config with no provider field. Display clear message about limitations. Proceed to Step 2.\n- If openai selected:\n - Prompt for model (default: text-embedding-3-small):\n Embedding model [text-embedding-3-small]:\n - Prompt for dimensions (default: 1536):\n Vector dimensions [1536]:\n - Prompt for API key env var name (default: OPENAI_API_KEY):\n API key environment variable [OPENAI_API_KEY]:\n - Check if the env var is set in the current environment:\n - If set: validate with a test embed call — embed a short test string and verify a vector is returned. If validation fails, display the error and ask the user to fix it or continue anyway.\n - If not set: warn the user and explain they need to set this env var in their shell profile before using the knowledge base. Do not block — they may be setting it up for later.\n- Write system config to ~/.config/workflows/config.json:\n { knowledge: { provider, model, dimensions, api_key_env, similarity_threshold: 0.8, decay_months: 6 } }\n- For stub mode (skip): write minimal config:\n { knowledge: { similarity_threshold: 0.8, decay_months: 6 } }\n\nSTEP 2: PROJECT INIT (.workflows/.knowledge/):\n- Check if project knowledge base directory already exists with config.json and store.msp.\n - If fully initialised: display status and ask to skip or reinitialise. If skip, proceed to Step 3.\n - If partially initialised (directory exists but missing files): complete the missing pieces.\n - If not initialised: create from scratch.\n- Create .workflows/.knowledge/ directory.\n- Write .workflows/.knowledge/config.json — project-level config. By default this is empty (inherits everything from system config):\n { knowledge: {} }\n The user can customise project-level overrides later by editing this file.\n- Create an empty Orama store and save it to .workflows/.knowledge/store.msp using createStore + saveStore from Phase 1. Use the dimensions from the resolved config (system + project merge).\n- Write .workflows/.knowledge/metadata.json with the provider/model/dimensions from the resolved config (or empty provider fields for stub mode).\n\nREADLINE INTERFACE:\n- Use Node built-in readline module (require('readline')).\n- Create interface with input: process.stdin, output: process.stdout.\n- Use rl.question() for prompts with defaults shown in brackets.\n- Close the interface when done.\n- If stdin is not a TTY (piped input, non-interactive environment): detect with process.stdin.isTTY and abort with message: knowledge setup requires an interactive terminal. Run it directly, not through Claude.\n\nAcceptance Criteria:\n- knowledge setup prompts for provider, model, dimensions, API key env var\n- System config is written to ~/.config/workflows/config.json\n- Project knowledge base is initialised at .workflows/.knowledge/ with config.json, store.msp, metadata.json\n- Test embed call validates the API key when configured\n- Stub mode writes config without provider, displays limitation message\n- Existing system config is detected and can be skipped or reconfigured\n- Existing project init is detected and can be skipped\n- Non-interactive terminal is detected and aborts with clear message\n- npm run build succeeds with the setup command included\n\nTests:\n- No automated tests for the interactive flow — it is inherently human-driven.\n- Unit tests for the non-interactive parts (tests/scripts/test-knowledge-config.cjs — extend from Task 3-1):\n - it creates a valid system config object from provider choices\n - it creates a valid stub-mode config object\n - it detects existing system config correctly\n - it detects existing project init correctly\n - it creates the project directory structure correctly\n\nEdge Cases:\n- ~/.config/workflows/ directory does not exist — create it (mkdir -p equivalent with { recursive: true })\n- .workflows/ directory does not exist — this means no workflow project exists. Display error: No .workflows/ directory found. Initialise a workflow project first.\n- System config file exists but is invalid JSON — display error, offer to overwrite\n- API key env var is set but the test embed call fails (wrong key, network error) — display error, offer to continue setup anyway (user may fix the key later)\n- User presses Ctrl+C during setup — readline handles SIGINT, process exits cleanly\n- Previous setup was stub mode, user re-runs with openai — detect existing store has no vectors, suggest knowledge rebuild after setup completes\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, interactive wizard flow, skip logic, stub mode), System config creation flow review finding #18 (line 1008), Configuration Hierarchy section (lines 258-301, system and project config schemas)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:28:36Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-19T16:36:59Z","auto":false}],"parent":"tick-2e511f","created":"2026-04-09T19:05:02Z","updated":"2026-04-19T16:36:59Z","closed":"2026-04-19T16:36:59Z"} {"id":"tick-b4348b","title":"Setup Wizard: Initial Indexing + Idempotency + CLI Integration","status":"open","priority":2,"type":"task","refs":["knowledge-base-7-2"],"description":"Problem: After system config and project init (Task 7-1), the knowledge base is empty. Existing projects may have dozens of completed artifacts that need to be indexed. The setup wizard must automatically index everything as its final step, and re-running setup must be safe — skipping already-completed steps without duplicating work.\n\nSolution: Wire up the existing bulk index logic (Task 4-4) as the final step of the setup wizard, ensure the full setup flow is idempotent, and register setup in the CLI dispatch.\n\nOutcome: Running knowledge setup on a project with existing completed work populates the knowledge base immediately. Re-running setup on an already-configured project skips to indexing (or exits if everything is done).\n\nDo:\n\nINITIAL INDEXING (Step 3 of the setup wizard):\n- After system config (Step 1) and project init (Step 2) complete (or are skipped), run initial indexing.\n- This delegates to the existing knowledge index (no args) bulk index logic from Task 4-4.\n- The bulk index discovers all completed artifacts via manifest, diffs against the store (which is empty for first setup), and indexes everything.\n- Display progress as files are indexed (same output as the bulk index command).\n- Display a clear completion summary covering how many files and chunks were indexed.\n- If the store already has chunks (re-run scenario): the bulk index logic naturally skips already-indexed items and only processes missing ones. No special handling needed.\n- If indexing fails for some files: the retry/pending queue mechanism from Task 4-4 handles it. Inform the user that some files could not be indexed and were added to the pending queue for automatic retry on next use.\n\nIDEMPOTENCY:\n- The full setup flow must be safe to re-run at any point:\n - System config exists → display current settings, offer to skip or reconfigure\n - Project init exists → display status, offer to skip or reinitialise\n - Store has chunks → bulk index skips already-indexed, only processes new/missing\n - Everything is current → display a clear \"already set up\" message and exit.\n- This covers the design doc requirement (line 631): skips steps that are already done.\n- Also covers the interrupted-setup scenario (design doc finding #5, line 965): if setup was interrupted mid-indexing, re-running picks up where it left off via the pending queue.\n\nCLI INTEGRATION:\n- Register the setup command in the CLI dispatch from Task 3-1. Task 3-1 lists setup alongside other Phase 4+ commands with a \"not yet implemented\" placeholder — replace that placeholder with a real handler that calls the wizard flow from Task 7-1 followed by the initial indexing from this task.\n\nSTUB-TO-FULL UPGRADE PATH:\n- If the user previously ran setup in stub mode and now re-runs with an OpenAI provider:\n - System config is updated with the new provider settings.\n - The existing store has no vectors (keyword-only mode).\n - Inform the user that the previous setup was keyword-only and they should run knowledge rebuild to re-index with embeddings for full hybrid search.\n - Do NOT automatically rebuild — it is destructive and may take time. The user should run it explicitly.\n- This matches the design doc (line 329): upgrading from stub to full requires knowledge rebuild.\n\nAcceptance Criteria:\n- Setup wizard indexes all existing completed artifacts as its final step\n- Progress and summary output matches the bulk index command\n- Failed indexing files are logged to pending queue with a note to the user\n- Re-running setup on a fully configured project exits cleanly with an already-set-up message\n- Re-running setup after interrupted indexing picks up where it left off\n- Setup command registered in CLI dispatch, replacing the Task 3-1 not-yet-implemented placeholder\n- Stub-to-full upgrade detected and user informed about knowledge rebuild\n- npm run build succeeds\n\nTests:\n- Unit tests for idempotency logic (tests/scripts/test-knowledge-config.cjs — extend):\n - it detects fully configured state (system + project + indexed)\n - it detects partially configured state (system exists, project missing)\n - it detects empty store needing initial indexing\n- CLI dispatch test (tests/scripts/test-knowledge-cli.sh — extend):\n - it routes to setup command without error (non-interactive detection will abort, which is the expected behaviour in test)\n- Manual validation:\n - Run setup on a project with existing completed artifacts -\u003e verify all are indexed\n - Run setup again -\u003e verify it skips everything and exits cleanly\n - Run setup after interruption -\u003e verify pending queue items are processed\n\nEdge Cases:\n- Project with no completed work units — initial indexing indexes 0 files, which is correct. The knowledge base is ready but empty.\n- Project with hundreds of completed artifacts — initial indexing may take time (embedding API calls). Display progress so the user knows it is working.\n- Setup interrupted with Ctrl+C during indexing — indexed files are saved (each save is atomic), unindexed files go to pending queue. Re-run picks up.\n- System config points to a provider but the API key env var is not set — initial indexing will fail (provider cannot embed). The retry/pending queue catches this. Setup still completes — the project is initialised, indexing is pending.\n- Multiple projects sharing the same system config — this is normal. System config has provider/key, each project has its own .workflows/.knowledge/. Setup only modifies the current project.\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, initial indexing as final step, skip logic), Init/resumability finding #5 (line 965, interrupted setup, pending queue picks up), Upgrading from stub to full (line 329, requires rebuild)","parent":"tick-2e511f","created":"2026-04-09T19:05:40Z","updated":"2026-04-10T20:47:17Z"} {"id":"tick-74a599","title":"Phase 8: Release Process","status":"open","priority":2,"refs":["knowledge-base-8"],"parent":"tick-cbbd13","created":"2026-04-09T19:05:44Z","updated":"2026-04-09T19:05:44Z"} {"id":"tick-7f4725","title":"Release Script Build Integration","status":"open","priority":2,"type":"task","refs":["knowledge-base-8-1"],"description":"Problem: The knowledge CLI bundle (knowledge.cjs) must be committed to the repo before tagging because AGNTC installs from git tags with no build step. During Phases 1-7 development, the bundle was built and committed manually. For production releases, the build must be formalised into the release pipeline to prevent shipping stale bundles.\n\nSolution: Integrate the esbuild build step into the local release script so the bundle is always fresh when a release tag is created.\n\nOutcome: The release process automatically builds knowledge.cjs from source before tagging, ensuring every tagged release has an up-to-date bundle.\n\nDo:\n- Read the existing release script at the project root (./release) before editing. Study:\n 1. Where perform_release runs the dirty-tree gate (git status --porcelain check that aborts on any uncommitted changes)\n 2. Where perform_release currently stages/commits (note: this is gated inside an `if [[ \"$VERSION_STRATEGY\" != \"none\" ]]` block — the default \"none\" strategy currently performs no commit at all, only tag + push)\n 3. Where the annotated tag is created and pushed\n- The build step must sit AFTER the existing dirty-tree check and BEFORE the annotated tag is created. Placing it before the dirty-tree check would cause the gate to abort on a bundle rebuild; placing it after the tag would ship a stale bundle in the tagged commit.\n- The build step sequence:\n 1. Run `npm install` (ensure dev dependencies are available)\n 2. Run `npm run build` (esbuild bundles src/knowledge/ into skills/workflow-knowledge/scripts/knowledge.cjs)\n 3. Check whether the bundle changed (e.g., git diff on the bundle path)\n 4. If it changed: stage and commit the updated bundle. IMPORTANT: this commit must occur in ALL version strategies, including `VERSION_STRATEGY=\"none\"` — the existing `none` branch performs no commits, so this task is introducing a new commit point into a previously commit-free path. Do not hide the bundle commit inside the existing version-bump commit block; it is a distinct concern and must run regardless of version strategy.\n 5. If the bundle did not change: no commit needed, proceed.\n 6. Proceed with the existing tag + push flow.\n- Build failure (non-zero exit from `npm run build`) must abort the release — do not tag with a stale or missing bundle. Clean exit with a clear error.\n- The bundle commit is the only permitted mutation after the dirty-tree check passes. The dirty-tree check still protects against unrelated uncommitted user changes — the user's working tree must be clean entering the release, and the bundle commit is the only thing the release script itself adds on top.\n- DECISION POINT: the design doc (line 52) flags a choice between local build and CI build. This task implements the local-in-release-script path. Reasoning: the bundle must be committed BEFORE tagging (AGNTC installs from tags), and GitHub Actions runs AFTER tag push — too late to commit. Local build keeps the flow simple (build → commit → tag → push → CI validates). CI validates the committed bundle in Task 8-2 but does not rebuild it.\n- package.json already exists from Phase 1 (Task 1-1) with dev deps and build script. No changes needed to package.json.\n- node_modules/ is already gitignored from Phase 1. No changes needed.\n- The design doc also mentions (line 53) that GitHub releases may no longer be needed since AGNTC uses tags, not releases. Consider simplifying if trivial; defer if not. This is a note, not a requirement.\n\nAcceptance Criteria:\n- Release script runs `npm install` + `npm run build` between the dirty-tree check and the annotated tag\n- Updated bundle is committed before the tag is created\n- Bundle commit occurs in all version strategies, including `VERSION_STRATEGY=\"none\"` (previously commit-free)\n- Build failure aborts the release with a clear error message\n- Existing dirty-tree check still rejects unrelated uncommitted user changes\n- Existing release flow (version handling, tag, push) is preserved after the build step\n- Tagged releases contain the up-to-date knowledge.cjs bundle\n- node_modules/ remains gitignored\n\nTests:\n- Test file: tests/scripts/test-release-build.sh (shell test)\n- it runs the build step before tagging\n- it commits the updated bundle when the diff shows changes (in both default and `none` version strategies)\n- it skips the commit when the bundle is unchanged\n- it aborts release on build failure\n- it still rejects dirty working tree on entry\n- Manual validation:\n - Run release with modified source -\u003e verify bundle is rebuilt and committed before tag\n - Run release with no source changes -\u003e verify no unnecessary commit\n - Run release with `VERSION_STRATEGY=\"none\"` and modified source -\u003e verify bundle commit still happens\n\nEdge Cases:\n- First release after Phase 1 — bundle already exists and is committed. Build step rebuilds it (may or may not change depending on esbuild determinism). If unchanged, no commit.\n- npm install fails (network error, registry down) — abort release with clear error\n- Bundle size grows significantly in later phases — Task 1-1 sets a size threshold. If build produces a bundle over that, Task 1-1's test-knowledge-build.sh fails, which blocks CI in Task 8-2, which blocks the release.\n- Git working directory has uncommitted changes at script start — the existing dirty-tree gate aborts before any build step runs. User must commit or stash first.\n- Uncommitted bundle diff at script start — same as above, aborts on the dirty-tree gate. User handles manually.\n\nSpec Reference: knowledge-base/design.md — Release Process section (lines 45-54, build before tagging, bundle committed, local vs CI decision, GitHub releases simplification consideration), Build and Distribution section (lines 448-457, bundle committed to repo, release workflow change required). Script file to modify: ./release (perform_release function — dirty-tree check, VERSION_STRATEGY branch, tag creation).","parent":"tick-74a599","created":"2026-04-09T19:06:33Z","updated":"2026-04-10T20:47:18Z"} diff --git a/skills/workflow-knowledge/scripts/knowledge.cjs b/skills/workflow-knowledge/scripts/knowledge.cjs index 87d8ec8ca..46151323b 100644 --- a/skills/workflow-knowledge/scripts/knowledge.cjs +++ b/skills/workflow-knowledge/scripts/knowledge.cjs @@ -1,29 +1,86 @@ -"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var st=b(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SUPPORTED_LANGUAGES=V.SPLITTERS=V.STEMMERS=void 0;V.getLocale=Lo;V.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};V.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};V.SUPPORTED_LANGUAGES=Object.keys(V.STEMMERS);function Lo(t){return t!==void 0&&V.SUPPORTED_LANGUAGES.includes(t)?V.STEMMERS[t]:void 0}});var R=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=Co;O.sprintf=qo;O.formatBytes=$o;O.isInsideWebWorker=kr;O.isInsideNode=Nr;O.getNanosecondTimeViaPerformance=rn;O.formatNanoseconds=zo;O.getNanosecondsTime=Vo;O.uniqueId=Wo;O.getOwnProperty=Ho;O.getTokenFrequency=Ko;O.insertSortedValue=Go;O.sortTokenScorePredicate=Ur;O.intersect=Yo;O.getDocumentProperties=Rr;O.getNested=Jo;O.flattenObject=Lr;O.convertDistanceToMeters=Zo;O.removeVectorsFromHits=Qo;O.isPromise=ec;O.isAsyncFunction=Br;O.setIntersection=tc;O.setUnion=rc;O.setDifference=sc;O.sleep=ic;var Bo=B(),jo=Date.now().toString().slice(5),Fo=0,vr=1024,Dr=BigInt(1e3),Mr=BigInt(1e6),Or=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function Co(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[d,l]=s.split(".").map(f=>Number.parseFloat(f));return typeof l=="number"&&l>=0&&(a=a.toFixed(l)),typeof d=="number"&&d>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function $o(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(vr));return`${parseFloat((t/Math.pow(vr,s)).toFixed(n))} ${r[s]}`}function kr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Nr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function rn(){return BigInt(Math.floor(performance.now()*1e6))}function zo(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Ur(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function Yo(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Rr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function ec(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Br(t){return Array.isArray(t)?t.some(e=>Br(e)):t?.constructor?.name==="AsyncFunction"}var Pr="intersection"in new Set;function tc(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if(Pr)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var B=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.createError=lc;var oc=st(),cc=R(),uc=oc.SUPPORTED_LANGUAGES.join(` - - `),ac={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. +"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=b(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SUPPORTED_LANGUAGES=V.SPLITTERS=V.STEMMERS=void 0;V.getLocale=ic;V.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};V.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};V.SUPPORTED_LANGUAGES=Object.keys(V.STEMMERS);function ic(t){return t!==void 0&&V.SUPPORTED_LANGUAGES.includes(t)?V.STEMMERS[t]:void 0}});var L=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=ac;O.sprintf=lc;O.formatBytes=dc;O.isInsideWebWorker=$r;O.isInsideNode=zr;O.getNanosecondTimeViaPerformance=dn;O.formatNanoseconds=fc;O.getNanosecondsTime=hc;O.uniqueId=pc;O.getOwnProperty=gc;O.getTokenFrequency=yc;O.insertSortedValue=mc;O.sortTokenScorePredicate=Vr;O.intersect=wc;O.getDocumentProperties=Wr;O.getNested=_c;O.flattenObject=Kr;O.convertDistanceToMeters=bc;O.removeVectorsFromHits=Ic;O.isPromise=xc;O.isAsyncFunction=Hr;O.setIntersection=Ec;O.setUnion=vc;O.setDifference=Tc;O.sleep=Dc;var oc=j(),cc=Date.now().toString().slice(5),uc=0,jr=1024,Fr=BigInt(1e3),Cr=BigInt(1e6),Br=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function ac(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[l,d]=s.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(a=a.toFixed(d)),typeof l=="number"&&l>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function dc(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(jr));return`${parseFloat((t/Math.pow(jr,s)).toFixed(n))} ${r[s]}`}function $r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function zr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function dn(){return BigInt(Math.floor(performance.now()*1e6))}function fc(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Vr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function wc(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Wr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function xc(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Hr(t){return Array.isArray(t)?t.some(e=>Hr(e)):t?.constructor?.name==="AsyncFunction"}var qr="intersection"in new Set;function Ec(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if(qr)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var j=b(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.createError=Nc;var Mc=lt(),Oc=L(),Pc=Mc.SUPPORTED_LANGUAGES.join(` + - `),kc={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. Supported languages are: - - ${uc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. + - ${Pc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance. Please install it before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy `,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration. Please provide a chat model before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy -`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function lc(t,...e){let n=new Error((0,cc.sprintf)(ac[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var Le=b(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.getDocumentProperties=void 0;W.formatElapsedTime=fc;W.getDocumentIndexId=hc;W.validateSchema=Fr;W.isGeoPointType=yc;W.isVectorType=Cr;W.isArrayType=qr;W.getInnerType=$r;W.getVectorSize=zr;var it=B(),jr=R(),dc=R();Object.defineProperty(W,"getDocumentProperties",{enumerable:!0,get:function(){return dc.getDocumentProperties}});function fc(t){return{raw:Number(t),formatted:(0,jr.formatNanoseconds)(t)}}function hc(t){if(t.id){if(typeof t.id!="string")throw(0,it.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,jr.uniqueId)()}function Fr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.createInternalDocumentIDStore=mc;we.save=Vr;we.load=Wr;we.getInternalDocumentId=Hr;we.getDocumentIdFromInternalId=wc;function mc(){return{idToInternalId:new Map,internalIdToId:[],save:Vr,load:Wr}}function Vr(t){return{internalIdToId:t.internalIdToId}}function Wr(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?Hr(t,e.toString()):e}function wc(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.create=Kr;H.get=Gr;H.getMultiple=Yr;H.getAll=Jr;H.store=Xr;H.remove=Zr;H.count=Qr;H.load=es;H.save=ts;H.createDocumentsStore=_c;var on=$();function Kr(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Gr(t,e){let n=(0,on.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function Yr(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function Qr(t){return t.count}function es(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function ts(t){return{docs:t.docs,count:t.count}}function _c(){return{create:Kr,get:Gr,getMultiple:Yr,getAll:Jr,store:Xr,remove:Zr,count:Qr,load:es,save:ts}}});var ns=b(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.AVAILABLE_PLUGIN_HOOKS=void 0;Be.getAllPluginsByHook=bc;var Sc=B();Be.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function bc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.SINGLE_OR_ARRAY_COMPONENTS=z.FUNCTION_COMPONENTS=z.OBJECT_COMPONENTS=void 0;z.runSingleHook=Ic;z.runMultipleHook=xc;z.runAfterSearch=Ec;z.runBeforeSearch=Ac;z.runAfterCreate=Tc;var je=R();z.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];z.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];z.SINGLE_OR_ARRAY_COMPONENTS=[];function Ic(t,e,n,r){if(t.some(je.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function xc(t,e,n){if(t.some(je.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function Ec(t,e,n,r,s){if(t.some(je.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function Ac(t,e,n,r){if(t.some(je.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Tc(t,e){if(t.some(je.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var rs=b(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.AVLTree=Te.AVLNode=void 0;var ce=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Te.AVLNode=ce;var un=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ce(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ce.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ce(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ce(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:d,node:l}=i[a];if(l.updateHeight(),u){let f=this.rebalanceNode(l);d?d.l===l?d.l=f:d.r===l&&(d.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Te.AVLTree=un});var ss=b(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.FlatTree=void 0;var an=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ot.FlatTree=an});var ln=b(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.boundedLevenshtein=vc;Fe.syncBoundedLevenshtein=Dc;Fe.levenshtein=Mc;function is(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function vc(t,e,n){let r=is(t,e,n);return{distance:r,isBounded:r>=0}}function Dc(t,e,n){let r=is(t,e,n);return{distance:r,isBounded:r>=0}}function Mc(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var cs=b(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.RadixTree=ve.RadixNode=void 0;var os=ln(),dn=R(),Ce=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,dn.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,os.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,dn.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let d of u)a.includes(d)||a.push(d)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:l,d:f}=c;if(l&&((0,os.syncBoundedLevenshtein)(e,l,s).isBounded&&(i[l]=[]),(0,dn.getOwnProperty)(i,l)!==void 0&&f.size>0)){let p=new Set(i[l]);for(let g of f)p.add(g);i[l]=Array.from(p)}}if(u>=e.length)continue;let d=e[u];if(c.c.has(d)){let l=c.c.get(d);o.push({node:l,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[l,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),l!==d&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};ve.RadixNode=Ce;var fn=class t extends Ce{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,Ce.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};ve.RadixTree=fn});var us=b(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.BKDTree=void 0;var Oc=2,Pc=6371e3,ct=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},hn=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ct(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%Oc===0)if(e.lon0;){let{node:a,depth:d}=c.pop();if(a==null)continue;let l=o(e,a.point);(r?l<=n:l>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:d+1}),a.right!=null&&c.push({node:a.right,depth:d+1})}return s&&u.sort((a,d)=>{let l=o(e,a.point),f=o(e,d.point);return s.toLowerCase()==="asc"?l-f:f-l}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let d=t.isPointInPolygon(e,u.point);(d&&n||!d&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,d)=>{let l=u(c,a.point),f=u(c,d.point);return r.toLowerCase()==="asc"?l-f:f-l})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ct.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(l-a)*(i-d)/(f-d)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return Pc*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,d=Math.atan((1-s)*Math.tan(c)),l=Math.atan((1-s)*Math.tan(u)),f=Math.sin(d),p=Math.cos(d),g=Math.sin(l),y=Math.cos(l),h=a,m,w=1e3,S,_,I,T,D,A;do{let Ae=Math.sin(h),Re=Math.cos(h);if(S=Math.sqrt(y*Ae*(y*Ae)+(p*g-f*y*Re)*(p*g-f*y*Re)),S===0)return 0;_=f*g+p*y*Re,I=Math.atan2(S,_),T=p*y*Ae/S,D=1-T*T,A=_-2*f*g/D,isNaN(A)&&(A=0);let nn=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-nn)*s*T*(I+nn*S*(A+nn*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),Ee=1+k/16384*(4096+k*(-768+k*(320-175*k))),Y=k/1024*(256+k*(-128+k*(74-47*k))),tn=Y*S*(A+Y/4*(_*(-1+2*A*A)-Y/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*Ee*(I-tn)}};ut.BKDTree=hn});var as=b(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.BoolNode=void 0;var pn=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};at.BoolNode=pn});var ls=b(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.prioritizeTokenScores=Nc;lt.BM25=Uc;var kc=B();function Nc(t,e,n=0,r){if(e===0)throw(0,kc.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let d=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];l=0}let f=d.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.VectorIndex=ue.DEFAULT_SIMILARITY=void 0;ue.getMagnitude=yn;ue.findSimilarVectors=ds;ue.DEFAULT_SIMILARITY=.8;var gn=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=yn(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),ds(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};ue.VectorIndex=gn;function yn(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var dt=b(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.insertDocumentScoreParameters=Ss;L.insertTokenScoreParameters=bs;L.removeDocumentScoreParameters=Is;L.removeTokenScoreParameters=xs;L.create=_n;L.insert=Es;L.insertVector=As;L.remove=Ts;L.calculateResultScores=Sn;L.search=vs;L.searchByWhereClause=qe;L.getSearchableProperties=Ds;L.getSearchablePropertiesWithTypes=Ms;L.load=Os;L.save=Ps;L.createIndex=Bc;L.searchByGeoWhereClause=Fc;var De=B(),gs=rs(),ys=ss(),ms=cs(),$e=us(),ws=as(),ee=R(),Rc=ls(),_e=Le(),wn=$(),_s=mn();function Ss(t,e,n,r,s){let i=(0,wn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function bs(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,wn.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function Is(t,e,n,r){let s=(0,wn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function xs(t,e,n){t.tokenOccurrences[e][n]--}function _n(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){_n(t,e,o,r,c);continue}if((0,_e.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new _s.VectorIndex((0,_e.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new ws.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new gs.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new ms.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new ys.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new $e.BKDTree,isArray:u};break;default:throw(0,De.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function Lc(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:d}=e.indexes[n];switch(a){case"Bool":{d[u?"true":"false"].add(r);break}case"AVL":{let l=c?.avlRebalanceThreshold??1;d.insert(u,r,l);break}case"Radix":{let l=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,l,o);for(let f of l)t.insertTokenScoreParameters(e,n,r,l,f),d.insert(f,r);break}case"Flat":{d.insert(u,r);break}case"BKD":{d.insert(u,[r]);break}}}}function Es(t,e,n,r,s,i,o,c,u,a,d){if((0,_e.isVectorType)(o))return As(e,n,i,r,s);let l=Lc(t,e,n,s,c,u,a,d);if(!(0,_e.isArrayType)(o))return l(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let tn=Y.length;for(let rt=0;rt[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(l===1)return m;if(l===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(T=>T===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([T])=>T===I)),_=Math.ceil(S.length*l);return[...w,...S.slice(0,_)]}return m}function qe(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>qe(t,e,u,r));return(0,ee.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>qe(t,e,u,r)).reduce((u,a)=>(0,ee.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let d=1;d<=u.internalIdToId.length;d++)c.add(d);let a=qe(t,e,o,r);return(0,ee.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,De.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:d}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,ee.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,ee.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=hs(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=hs(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=Cc(i[o],y)}}continue}let l=Object.keys(c);if(l.length>1)throw(0,De.createError)("INVALID_FILTER_OPERATION",l.length);if(a==="Flat"){let f=new Set(d?u.filterArr(c):u.filter(c));i[o]=(0,ee.setUnion)(i[o],f);continue}if(a==="AVL"){let f=l[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,De.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,ee.setUnion)(i[o],g)}}return(0,ee.setIntersection)(...Object.values(i))}function Ds(t){return t.searchableProperties}function Ms(t){return t.searchablePropertiesWithTypes}function Os(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,d={},l={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":d[f]={type:"Radix",node:ms.RadixTree.fromJSON(p),isArray:y};break;case"Flat":d[f]={type:"Flat",node:ys.FlatTree.fromJSON(p),isArray:y};break;case"AVL":d[f]={type:"AVL",node:gs.AVLTree.fromJSON(p),isArray:y};break;case"BKD":d[f]={type:"BKD",node:$e.BKDTree.fromJSON(p),isArray:y};break;case"Bool":d[f]={type:"Bool",node:ws.BoolNode.fromJSON(p),isArray:y};break;default:d[f]=n[f]}}for(let f of Object.keys(r))l[f]={type:"Vector",isArray:!1,node:_s.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:d,vectorIndexes:l,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function Ps(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let l of Object.keys(n))a[l]=n[l].node.toJSON();let d={};for(let l of Object.keys(e)){let{type:f,node:p,isArray:g}=e[l];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?d[l]={type:f,node:p.toJSON(),isArray:g}:(d[l]=e[l],d[l].node=d[l].node.toJSON())}return{indexes:d,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function Bc(){return{create:_n,insert:Es,remove:Ts,insertDocumentScoreParameters:Ss,insertTokenScoreParameters:bs,removeDocumentScoreParameters:Is,removeTokenScoreParameters:xs,calculateResultScores:Sn,search:vs,searchByWhereClause:qe,getSearchableProperties:Ds,getSearchablePropertiesWithTypes:Ms,load:Os,save:Ps}}function hs(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function jc(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function Fc(t,e){let n=t,r=jc(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:d="m",inside:l=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,ee.convertDistanceToMeters)(u,d);return c=o.searchByRadius(p,g,l,"asc",f),ps(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:d=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",d);let l=$e.BKDTree.calculatePolygonCentroid(u);return ps(c,l,d)}return null}function Cc(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.load=Us;ze.save=Rs;ze.createSorter=tu;var bn=B(),qc=Le(),ft=$(),$c=R(),zc=st();function ks(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=ks(t,e,c,r,u);(0,$c.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,qc.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,bn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function Vc(t,e,n,r){return r?.enabled!==!1?ks(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function Wc(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,ft.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&In(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function Ns(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)Yc(t,n);t.isSorted=!0}function Hc(t,e,n){return e[1].localeCompare(n[1],(0,zc.getLocale)(t))}function Kc(t,e){return t[1]-e[1]}function Gc(t,e){return e[1]?-1:1}function Yc(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=Hc.bind(null,t.language);break;case"number":r=Kc.bind(null);break;case"boolean":r=Gc.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function Xc(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,ft.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function Zc(t,e,n){if(!t.enabled)throw(0,bn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,bn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return In(t,r),Ns(t),e.sort((o,c)=>{let u=i.docs.get((0,ft.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,ft.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),d=typeof u<"u",l=typeof a<"u";return!d&&!l?0:d?l?s?a-u:u-a:-1:1}),e}function Qc(t){return t.enabled?t.sortableProperties:[]}function eu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Us(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,d])=>[+a,d])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Rs(t){if(!t.enabled)return{enabled:!1};Jc(t),Ns(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function tu(){return{create:Vc,insert:Wc,remove:Xc,save:Rs,load:Us,sortBy:Zc,getSortableProperties:Qc,getSortablePropertiesWithTypes:eu}}});var Bs=b(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.replaceDiacritics=iu;var Ls=192,nu=383,ru=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function su(t){return tnu?t:ru[t-Ls]||t}function iu(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.stemmer=lu;var ou={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},cu={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},uu="[^aeiou]",pt="[aeiouy]",J=uu+"[^aeiouy]*",Ve=pt+"[aeiou]*",An="^("+J+")?"+Ve+J,au="^("+J+")?"+Ve+J+"("+Ve+")?$",ht="^("+J+")?"+Ve+J+Ve+J,js="^("+J+")?"+pt;function lu(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(An),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(js),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+J+pt+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(js),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(An),e&&r.test(e)&&(t=e+ou[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(An),e&&r.test(e)&&(t=e+cu[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(ht),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(ht),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(ht),s=new RegExp(au),i=new RegExp("^"+J+pt+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(ht),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var yt=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.normalizeToken=vn;gt.createTokenizer=pu;var Se=B(),du=Bs(),qs=st(),fu=Fs();function vn(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,du.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function hu(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function Cs(t,e,n,r=!0){if(e&&e!==this.language)throw(0,Se.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=qs.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=hu(i);return this.allowDuplicates?o:Array.from(new Set(o))}function pu(t={}){if(!t.language)t.language="english";else if(!qs.SUPPORTED_LANGUAGES.includes(t.language))throw(0,Se.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,Se.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=fu.stemmer;else throw(0,Se.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,Se.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,Se.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,Se.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Cs,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:vn,normalizationCache:new Map};return r.tokenize=Cs.bind(r),r.normalizeToken=vn,r}});var Dn=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getMatchingRules=$s;Me.load=zs;Me.save=Vs;Me.createPinning=xu;function gu(t){return{sharedInternalDocumentStore:t,rules:new Map}}function yu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function mu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function wu(t,e){return t.rules.delete(e)}function _u(t,e){return t.rules.get(e)}function Su(t){return Array.from(t.rules.values())}function bu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Iu(t,e){return t?e.conditions.every(n=>bu(t,n)):!1}function $s(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Iu(e,r)&&n.push(r);return n}function zs(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function Vs(t){return{rules:Array.from(t.rules.entries())}}function xu(){return{create:gu,addRule:yu,updateRule:mu,removeRule:wu,getRule:_u,getAllRules:Su,getMatchingRules:$s,load:zs,save:Vs}}});var Ks=b(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.create=Pu;var mt=Le(),Eu=cn(),Ws=ns(),wt=Q(),Au=dt(),Tu=$(),vu=xn(),Hs=yt(),Du=Dn(),_t=B(),Mu=R();function Ou(t){let e={formatElapsedTime:mt.formatElapsedTime,getDocumentIndexId:mt.getDocumentIndexId,getDocumentProperties:mt.getDocumentProperties,validateSchema:mt.validateSchema};for(let n of wt.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,_t.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!wt.OBJECT_COMPONENTS.includes(n)&&!wt.FUNCTION_COMPONENTS.includes(n))throw(0,_t.createError)("UNSUPPORTED_COMPONENT",n)}function Pu({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,_t.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,Mu.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,d=r.pinning;if(o?o.tokenize?o=o:o=(0,Hs.createTokenizer)(o):o=(0,Hs.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,_t.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let l=(0,Tu.createInternalDocumentIDStore)();c||=(0,Au.createIndex)(),a||=(0,vu.createSorter)(),u||=(0,Eu.createDocumentsStore)(),d||=(0,Du.createPinning)(),Ou(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:d,internalDocumentIDStore:l,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:ku()};h.data={index:h.index.create(h,l,t),docs:h.documentsStore.create(h,l),sorting:h.sorter.create(h,l,t,e),pinning:h.pinning.create(l)};for(let w of Ws.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,Ws.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,wt.runAfterCreate)(m,h),h}function ku(){return"{{VERSION}}"}});var On=b(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.getByID=Nu;St.count=Uu;function Nu(t,e){return t.documentsStore.get(t.data.docs,e)}function Uu(t){return t.documentsStore.count(t.data.docs)}});var Pn=b(U=>{"use strict";var Gs=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ru=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Lu=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Gs(e,t,n)},We=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.insert=Un;He.insertMultiple=zu;He.innerInsertMultiple=Vu;var kn=Pn(),F=R(),Oe=Q(),Pe=B(),Nn=$();function Un(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Pe.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?Fu(t,e,n,r,s):Cu(t,e,n,r,s)}var Bu=new Set(["enum","enum[]"]),ju=new Set(["string","number"]);async function Fu(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Pe.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Nn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Oe.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Pe.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),d=t.index.getSearchableProperties(i),l=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,d);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=l[p];Ys(y,h,p,g)}return await qu(t,c,d,f,a,n,e,s),r||await(0,Oe.runSingleHook)(t.afterInsert,t,c,e),c}function Cu(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Pe.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Nn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Oe.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Pe.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),d=t.index.getSearchableProperties(i),l=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,d);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=l[p];Ys(y,h,p,g)}return $u(t,c,d,f,a,n,e,s),r||(0,Oe.runSingleHook)(t.afterInsert,t,c,e),c}function Ys(t,e,n,r){if(!((0,kn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,kn.isVectorType)(e)&&Array.isArray(r))&&!((0,kn.isArrayType)(e)&&Array.isArray(r))&&!(Bu.has(e)&&ju.has(t))&&t!==e)throw(0,Pe.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function qu(t,e,n,r,s,i,o,c){for(let d of n){let l=r[d];if(typeof l>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[d];await t.index.beforeInsert?.(t.data.index,d,e,l,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,d,e,p,l,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,d,e,l,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let d of u){let l=a[d];if(typeof l>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[d];t.sorter.insert(t.data.sorting,d,e,l,f,i)}}function $u(t,e,n,r,s,i,o,c){for(let d of n){let l=r[d];if(typeof l>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[d],p=(0,Nn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,d,e,l,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,d,e,p,l,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,d,e,l,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let d of u){let l=a[d];if(typeof l>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[d];t.sorter.insert(t.data.sorting,d,e,l,f,i)}}function zu(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsertMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?Js(t,e,n,r,s,i):Xs(t,e,n,r,s,i)}async function Js(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let d=Math.min(a+n,e.length),l=e.slice(a,d);for(let f of l){let p={avlRebalanceThreshold:l.length},g=await Un(t,f,r,s,p);o.push(g)}return d};return await(async()=>{let a=0;for(;a0){let l=Date.now()-d,f=i-l;f>0&&(0,F.sleep)(f)}}})(),s||await(0,Oe.runMultipleHook)(t.afterInsertMultiple,t,e),o}function Xs(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let d=e.slice(c*n,(c+1)*n);if(d.length===0)return!1;for(let l of d){let f={avlRebalanceThreshold:d.length},p=Un(t,l,r,s,f);o.push(p)}return c++,!0}function a(){let d=Date.now();for(;u();)if(i>0){let f=Date.now()-d;if(f>=i){let p=i-f%i;p>0&&(0,F.sleep)(p)}}}return a(),s||(0,Oe.runMultipleHook)(t.afterInsertMultiple,t,e),o}function Vu(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?Js(t,e,n,r,s,i):Xs(t,e,n,r,s,i)}});var Zs=b(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.insertPin=Wu;be.updatePin=Hu;be.deletePin=Ku;be.getPin=Gu;be.getAllPins=Yu;function Wu(t,e){t.pinning.addRule(t.data.pinning,e)}function Hu(t,e){t.pinning.updateRule(t.data.pinning,e)}function Ku(t,e){return t.pinning.removeRule(t.data.pinning,e)}function Gu(t,e){return t.pinning.getRule(t.data.pinning,e)}function Yu(t){return t.pinning.getAllRules(t.data.pinning)}});var Ln=b(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.remove=Rn;It.removeMultiple=Zu;var le=Q(),de=$(),ae=R();function Rn(t,e,n,r){return(0,ae.isAsyncFunction)(t.index.beforeRemove)||(0,ae.isAsyncFunction)(t.index.remove)||(0,ae.isAsyncFunction)(t.index.afterRemove)?Ju(t,e,n,r):Xu(t,e,n,r)}async function Ju(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,de.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,de.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),d=t.documentsStore.count(o);r||await(0,le.runSingleHook)(t.beforeRemove,t,a);let l=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,l);for(let h of l){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,d),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,d)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,d)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,le.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Xu(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,de.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,de.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),d=t.documentsStore.count(o);r||(0,le.runSingleHook)(t.beforeRemove,t,a);let l=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,l);for(let h of l){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,d),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,d)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,d)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,le.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Zu(t,e,n,r,s){return(0,ae.isAsyncFunction)(t.index.beforeRemove)||(0,ae.isAsyncFunction)(t.index.remove)||(0,ae.isAsyncFunction)(t.index.afterRemove)||(0,ae.isAsyncFunction)(t.beforeRemoveMultiple)||(0,ae.isAsyncFunction)(t.afterRemoveMultiple)?Qu(t,e,n,r,s):ea(t,e,n,r,s)}async function Qu(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,de.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,de.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,le.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function d(){let l=e.slice(a*n,++a*n);if(!l.length)return c();for(let f of l)try{await Rn(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(d,0)}setTimeout(d,0)}),s||await(0,le.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function ea(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,de.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,de.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,le.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let d of a)Rn(t,d,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,le.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Bn=b(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.MODE_VECTOR_SEARCH=fe.MODE_HYBRID_SEARCH=fe.MODE_FULLTEXT_SEARCH=void 0;fe.MODE_FULLTEXT_SEARCH="fulltext";fe.MODE_HYBRID_SEARCH="hybrid";fe.MODE_VECTOR_SEARCH="vector"});var xt=b(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getFacets=oa;var ta=B(),na=R();function ra(t,e){return t[1]-e[1]}function sa(t,e){return e[1]-t[1]}function ia(t="desc"){return t.toLowerCase()==="asc"?ra:sa}function oa(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let d;if(c[a]==="number"){let{ranges:l}=n[a],f=l.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function ei(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Et=b(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.getGroups=aa;var ti=B(),Fn=R(),ca=$(),ua={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},ni=["string","number","boolean"];function aa(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,ti.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!ni.includes(i[w]))throw(0,ti.createError)("INVALID_GROUP_BY_PROPERTY",w,ni.join(", "),i[w])}let o=e.map(([m])=>(0,ca.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,d=[],l={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}d.push(Array.from(_)),l[w]=S}let f=ri(d),p=f.length,g=[];for(let m=0;mT-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),T=S.getInitialValue(w.indexes.length),D=_.reduce(I,T);h[m]={values:w.values,result:D}}return h}function ri(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=ri(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Fn.safeArrayPush)(c,o),s.push(c)}return s}});var At=b(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.applyPinningRules=fa;var la=$(),da=Dn();function fa(t,e,n,r){let s=(0,da.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,la.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),d=1e6,l=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?l.push([h,d-m]):t.documentsStore.get(t.data.docs,h)&&l.push([h,0]);l.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of l){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var $n=b(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.defaultBM25Params=void 0;te.innerFullTextSearch=oi;te.fullTextSearch=Ia;var ha=xt(),pa=Et(),si=Q(),ga=$(),ya=dt(),ma=At(),wa=B(),Tt=R(),_a=On(),ii=Ke();function oi(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let l=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>l[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let l of s)if(!o.includes(l))throw(0,wa.createError)("UNKNOWN_INDEX",l,o.join(", "));o=o.filter(l=>s.includes(l))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,d=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let l=(0,_a.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},xa(e.relevance),l,u,d),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=ba(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${Sa(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let l=(0,ya.searchByGeoWhereClause)(i,e.where);l?a=l:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function Sa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ba(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Ia(t,e,n){let r=(0,Tt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:d=0,distinctOn:l,includeVectors:f=!1}=e,p=e.preflight===!0,g=oi(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,ga.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(Tt.sortTokenScorePredicate);g=(0,ma.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=l?(0,ii.fetchDocumentsWithDistinct)(t,g,d,a,l):(0,ii.fetchDocuments)(t,g,d,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,Tt.removeVectorsFromHits)(h,c)),u){let m=(0,ha.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,pa.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,Tt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,si.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,si.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}te.defaultBM25Params={k:1.2,b:.75,d:.5};function xa(t){let e=t??{};return e.k=e.k??te.defaultBM25Params.k,e.b=e.b??te.defaultBM25Params.b,e.d=e.d??te.defaultBM25Params.d,e}});var Ot=b(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.innerVectorSearch=ui;Mt.searchVector=Ma;var vt=R(),Ea=xt(),Dt=B(),Aa=Et(),Ta=$(),ci=Q(),va=mn(),Da=At();function ui(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Dt.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Dt.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Dt.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Dt.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??va.DEFAULT_SIMILARITY,c)}function Ma(t,e,n="english"){let r=(0,vt.getNanosecondsTime)();function s(){let c=ui(t,e,n).sort(vt.sortTokenScorePredicate);c=(0,Da.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,Ea.getFacets)(t,c,e.facets));let d=e.vector.property,l=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.innerHybridSearch=di;kt.hybridSearch=La;var Pt=R(),Oa=xt(),Pa=Et(),ka=Ke(),Na=$n(),Ua=Ot(),ai=Q(),Ra=At();function di(t,e,n){let r=Ba((0,Na.innerFullTextSearch)(t,e,n)),s=(0,Ua.innerVectorSearch)(t,e,n),i=e.hybridWeights;return Fa(r,s,e.term??"",i)}function La(t,e,n){let r=(0,Pt.getNanosecondsTime)();function s(){let c=di(t,e,n);c=(0,Ra.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,Oa.getFacets)(t,c,e.facets));let d;e.groupBy&&(d=(0,Pa.getGroups)(t,c,e.groupBy));let l=e.offset??0,f=e.limit??10,p=(0,ka.fetchDocuments)(t,c,l,f).filter(Boolean),g=(0,Pt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,Pt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...d?{groups:d}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,Pt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,ai.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,ai.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function zn(t){return t[1]}function Ba(t){let e=Math.max.apply(Math,t.map(zn));return t.map(([n,r])=>[n,r/e])}function li(t,e){return t/e}function ja(t,e){return(n,r)=>n*t+r*e}function Fa(t,e,n,r){let s=Math.max.apply(Math,t.map(zn)),i=Math.max.apply(Math,e.map(zn)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:Ca(n),a=new Map,d=t.length,l=ja(c,u);for(let p=0;pg[1]-p[1])}function Ca(t){return{text:.5,vector:.5}}});var Ke=b(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.search=Ha;Ge.fetchDocumentsWithDistinct=Ka;Ge.fetchDocuments=Ga;var hi=$(),qa=B(),$a=R(),Nt=Bn(),za=$n(),Va=Ot(),Wa=fi();function Ha(t,e,n){let r=e.mode??Nt.MODE_FULLTEXT_SEARCH;if(r===Nt.MODE_FULLTEXT_SEARCH)return(0,za.fullTextSearch)(t,e,n);if(r===Nt.MODE_VECTOR_SEARCH)return(0,Va.searchVector)(t,e);if(r===Nt.MODE_HYBRID_SEARCH)return(0,Wa.hybridSearch)(t,e);throw(0,qa.createError)("INVALID_SEARCH_MODE",r)}function Ka(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,d=0;for(let l=0;l"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,$a.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),d++,!(d<=n)&&(c.push({id:(0,hi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),d>=n+r)))break}return c}function Ga(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,d]=u;if(!o.has(a)){let l=t.documentsStore.get(s,a);i[c]={id:(0,hi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:d,document:l},o.add(a)}}return i}});var pi=b(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.load=Ya;Ut.save=Ja;function Ya(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function Ja(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var Vn=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.update=Xa;Bt.updateMultiple=el;var he=Q(),gi=B(),Rt=bt(),Lt=Ln(),j=R();function Xa(t,e,n,r,s){return(0,j.isAsyncFunction)(t.afterInsert)||(0,j.isAsyncFunction)(t.beforeInsert)||(0,j.isAsyncFunction)(t.afterRemove)||(0,j.isAsyncFunction)(t.beforeRemove)||(0,j.isAsyncFunction)(t.beforeUpdate)||(0,j.isAsyncFunction)(t.afterUpdate)?Za(t,e,n,r,s):Qa(t,e,n,r,s)}async function Za(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,he.runSingleHook)(t.beforeUpdate,t,e),await(0,Lt.remove)(t,e,r,s);let i=await(0,Rt.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,he.runSingleHook)(t.afterUpdate,t,i),i}function Qa(t,e,n,r,s){!s&&t.beforeUpdate&&(0,he.runSingleHook)(t.beforeUpdate,t,e),(0,Lt.remove)(t,e,r,s);let i=(0,Rt.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,he.runSingleHook)(t.afterUpdate,t,i),i}function el(t,e,n,r,s,i){return(0,j.isAsyncFunction)(t.afterInsert)||(0,j.isAsyncFunction)(t.beforeInsert)||(0,j.isAsyncFunction)(t.afterRemove)||(0,j.isAsyncFunction)(t.beforeRemove)||(0,j.isAsyncFunction)(t.beforeUpdate)||(0,j.isAsyncFunction)(t.afterUpdate)||(0,j.isAsyncFunction)(t.beforeUpdateMultiple)||(0,j.isAsyncFunction)(t.afterUpdateMultiple)||(0,j.isAsyncFunction)(t.beforeRemoveMultiple)||(0,j.isAsyncFunction)(t.afterRemoveMultiple)||(0,j.isAsyncFunction)(t.beforeInsertMultiple)||(0,j.isAsyncFunction)(t.afterInsertMultiple)?tl(t,e,n,r,s,i):nl(t,e,n,r,s,i)}async function tl(t,e,n,r,s,i){i||await(0,he.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.upsert=rl;Ct.upsertMultiple=ol;var pe=Q(),ke=B(),jt=bt(),Ft=Vn(),P=R();function rl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?sl(t,e,n,r,s):il(t,e,n,r,s)}async function sl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,ke.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,pe.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Ft.update)(t,i,e,n,r):c=await(0,jt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,pe.runSingleHook)(t.afterUpsert,t,c,e),c}function il(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,ke.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,pe.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Ft.update)(t,i,e,n,r):c=(0,jt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,pe.runSingleHook)(t.afterUpsert,t,c,e),c}function ol(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?cl(t,e,n,r,s):ul(t,e,n,r,s)}async function cl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,pe.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let d=0;d0){let d=await(0,Ft.updateMultiple)(t,u,c,n,r,s);a.push(...d)}if(o.length>0){let d=await(0,jt.innerInsertMultiple)(t,o,n,r,s);a.push(...d)}return!s&&t.afterUpsertMultiple&&await(0,pe.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function ul(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,pe.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let d=0;d0){let d=(0,Ft.updateMultiple)(t,u,c,n,r,s);a.push(...d)}if(o.length>0){let d=(0,jt.innerInsertMultiple)(t,o,n,r,s);a.push(...d)}return!s&&t.afterUpsertMultiple&&(0,pe.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var mi=b($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.AnswerSession=void 0;var qt=B(),al=Ke(),ll="orama-secure-proxy",Wn=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,qt.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,qt.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,al.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===ll)}let r=await n();if(!r)throw(0,qt.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,qt.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};$t.AnswerSession=Wn});var wi=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.kRemovals=K.kInsertions=K.MODE_VECTOR_SEARCH=K.MODE_HYBRID_SEARCH=K.MODE_FULLTEXT_SEARCH=void 0;var Hn=Bn();Object.defineProperty(K,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return Hn.MODE_FULLTEXT_SEARCH}});Object.defineProperty(K,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return Hn.MODE_HYBRID_SEARCH}});Object.defineProperty(K,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return Hn.MODE_VECTOR_SEARCH}});K.kInsertions=Symbol("orama.insertions");K.kRemovals=Symbol("orama.removals")});var _i=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var dl=ln();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return dl.boundedLevenshtein}});var ne=R();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return ne.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return ne.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return ne.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return ne.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return ne.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return ne.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return ne.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return ne.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return ne.setDifference}});var fl=yt();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return fl.normalizeToken}})});var Di=b(x=>{"use strict";var Si=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Si(e,t,n)},bi=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.utf8Count=_l;re.utf8EncodeJs=Mi;re.utf8EncodeTE=Oi;re.utf8Encode=Il;re.utf8DecodeJs=Pi;re.utf8DecodeTD=ki;re.utf8Decode=Tl;function _l(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var Sl=new TextEncoder,bl=50;function Oi(t,e,n){Sl.encodeInto(t,e.subarray(n))}function Il(t,e,n){t.length>bl?Oi(t,e,n):Mi(t,e,n)}var xl=4096;function Pi(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|l&1023),i.push(l)}else i.push(c);i.length>=xl&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var El=new TextDecoder,Al=200;function ki(t,e,n){let r=t.subarray(e,e+n);return El.decode(r)}function Tl(t,e,n){return n>Al?ki(t,e,n):Pi(t,e,n)}});var Gn=b(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.ExtData=void 0;var Kn=class{type;data;constructor(e,n){this.type=e,this.data=n}};Vt.ExtData=Kn});var Ht=b(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.DecodeError=void 0;var Yn=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Wt.DecodeError=Yn});var Kt=b(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.UINT32_MAX=void 0;ge.setUint64=vl;ge.setInt64=Dl;ge.getInt64=Ml;ge.getUint64=Ol;ge.UINT32_MAX=4294967295;function vl(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Dl(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Ml(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Ol(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var Jn=b(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.timestampExtension=G.EXT_TIMESTAMP=void 0;G.encodeTimeSpecToTimestamp=Ui;G.encodeDateToTimeSpec=Ri;G.encodeTimestampExtension=Li;G.decodeTimestampToTimeSpec=Bi;G.decodeTimestampExtension=ji;var Pl=Ht(),Ni=Kt();G.EXT_TIMESTAMP=-1;var kl=4294967296-1,Nl=17179869184-1;function Ui({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Nl)if(e===0&&t<=kl){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,Ni.setInt64)(r,4,t),n}}function Ri(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Li(t){if(t instanceof Date){let e=Ri(t);return Ui(e)}else return null}function Bi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,Ni.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Pl.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function ji(t){let e=Bi(t);return new Date(e.sec*1e3+e.nsec/1e6)}G.timestampExtension={type:G.EXT_TIMESTAMP,encode:Li,decode:ji}});var Jt=b(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.ExtensionCodec=void 0;var Gt=Gn(),Ul=Jn(),Xn=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Ul.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.ensureUint8Array=Ll;function Rl(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ll(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Rl(t)?new Uint8Array(t):Uint8Array.from(t)}});var tr=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.Encoder=X.DEFAULT_INITIAL_BUFFER_SIZE=X.DEFAULT_MAX_DEPTH=void 0;var Fi=zt(),Bl=Jt(),Ci=Kt(),jl=Qn();X.DEFAULT_MAX_DEPTH=100;X.DEFAULT_INITIAL_BUFFER_SIZE=2048;var er=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Bl.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??X.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??X.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Fi.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Fi.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,jl.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Ci.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Ci.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};X.Encoder=er});var qi=b(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.encode=Cl;var Fl=tr();function Cl(t,e){return new Fl.Encoder(e).encodeSharedRef(t)}});var $i=b(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.prettyByte=ql;function ql(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var zi=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.CachedKeyDecoder=void 0;var $l=zt(),zl=16,Vl=16,sr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=zl,n=Vl){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,$l.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};Xt.CachedKeyDecoder=sr});var Qt=b(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.Decoder=void 0;var ir=$i(),Wl=Jt(),Ie=Kt(),Hl=zt(),Vi=Qn(),Kl=zi(),se=Ht(),or="array",Xe="map_key",Hi="map_value",Gl=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new se.DecodeError("The type of key must be string or number but "+typeof t)},cr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=or,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=Xe,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===or){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Xe||e.type===Hi){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Je=-1,ar=new DataView(new ArrayBuffer(0)),Yl=new Uint8Array(ar.buffer);try{ar.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Wi=new RangeError("Insufficient data"),Jl=new Kl.CachedKeyDecoder,ur=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=ar;bytes=Yl;headByte=Je;stack=new cr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Wl.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ie.UINT32_MAX,this.maxBinLength=e?.maxBinLength??Ie.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??Ie.UINT32_MAX,this.maxMapLength=e?.maxMapLength??Ie.UINT32_MAX,this.maxExtLength=e?.maxExtLength??Ie.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Jl,this.mapKeyConverter=e?.mapKeyConverter??Gl}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Je,this.stack.reset()}setBuffer(e){let n=(0,Vi.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Je&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,Vi.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,ir.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new se.DecodeError(`Unrecognized type byte: ${(0,ir.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===or)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===Xe){if(n==="__proto__")throw new se.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=Hi;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=Xe;continue e}}return n}}readHeadByte(){return this.headByte===Je&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Je}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new se.DecodeError(`Unrecognized array type byte: ${(0,ir.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new se.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new se.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new se.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===Xe:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new se.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Wi;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new se.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,Ie.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,Ie.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};Zt.Decoder=ur});var Gi=b(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.decode=Xl;en.decodeMulti=Zl;var Ki=Qt();function Xl(t,e){return new Ki.Decoder(e).decode(t)}function Zl(t,e){return new Ki.Decoder(e).decodeMulti(t)}});var Xi=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.isAsyncIterable=Yi;Ze.asyncIterableFromStream=Ji;Ze.ensureAsyncIterable=Ql;function Yi(t){return t[Symbol.asyncIterator]!=null}async function*Ji(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function Ql(t){return Yi(t)?t:Ji(t)}});var Zi=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.decodeAsync=ed;Qe.decodeArrayStream=td;Qe.decodeMultiStream=nd;var lr=Qt(),dr=Xi();async function ed(t,e){let n=(0,dr.ensureAsyncIterable)(t);return new lr.Decoder(e).decodeAsync(n)}function td(t,e){let n=(0,dr.ensureAsyncIterable)(t);return new lr.Decoder(e).decodeArrayStream(n)}function nd(t,e){let n=(0,dr.ensureAsyncIterable)(t);return new lr.Decoder(e).decodeStream(n)}});var eo=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var rd=qi();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return rd.encode}});var Qi=Gi();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return Qi.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return Qi.decodeMulti}});var fr=Zi();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return fr.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return fr.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return fr.decodeMultiStream}});var sd=Qt();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return sd.Decoder}});var id=Ht();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return id.DecodeError}});var od=tr();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return od.Encoder}});var cd=Jt();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return cd.ExtensionCodec}});var ud=Gn();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return ud.ExtData}});var Ne=Jn();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Ne.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Ne.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Ne.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Ne.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return Ne.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return Ne.decodeTimestampExtension}})});var oo=b((yh,io)=>{"use strict";var q=require("fs"),Z=Di(),{encode:ad,decode:ld}=eo(),hr=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function to(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function dd(t){let e=to(t);return Z.create({schema:e})}function fd(t){for(let e of hr)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function hd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");fd(e);let n={};for(let r of hr)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return Z.insert(t,n)}async function pd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return no(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function no(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await Z.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await Z.removeMultiple(t,r)}function pr(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function gd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await Z.search(t,s)).hits.map(pr)}async function yd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await Z.search(t,i)).hits.map(pr)}async function md(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await Z.search(t,u)).hits.map(pr)}async function wd(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=Z.save(t),r={v:1,schema:t.schema,raw:n},s=ad(r),i=e+".tmp";q.writeFileSync(i,s),q.renameSync(i,e)}async function _d(t){if(!t)throw new Error("loadStore: storePath is required");if(!q.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=q.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=ld(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await Z.create({schema:n.schema});return Z.load(r,n.raw),r}var Sd=3e4,bd=50,Id=1e4;function xd(t){try{let e=q.openSync(t,"wx");return q.writeSync(e,String(process.pid)),q.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function Ed(t){return new Promise(e=>setTimeout(e,t))}async function ro(t){let e=Date.now()+Id;for(;;){if(xd(t))return;try{let n=q.statSync(t);if(Date.now()-n.mtimeMs>Sd){try{q.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await Ed(bd)}}function so(t){try{q.unlinkSync(t)}catch{}}async function Ad(t,e){await ro(t);try{return await e()}finally{so(t)}}var Td=["provider","model","dimensions","last_indexed","pending"];function vd(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";q.writeFileSync(r,JSON.stringify(n,null,2)+` -`,"utf8"),q.renameSync(r,t)}function Dd(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!q.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=q.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}io.exports={SCHEMA_FIELDS:hr,METADATA_FIELDS:Td,buildSchema:to,createStore:dd,insertDocument:hd,removeByIdentity:pd,removeByFilter:no,searchFulltext:gd,searchVector:yd,searchHybrid:md,saveStore:wd,loadStore:_d,acquireLock:ro,releaseLock:so,withLock:Ad,writeMetadata:vd,readMetadata:Dd}});var fo=b((mh,lo)=>{"use strict";var Md=/^\s*(```+|~~~+)/,co=/^---\s*$/;function Od(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` +`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function Nc(t,...e){let n=new Error((0,Oc.sprintf)(kc[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var Be=b(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.getDocumentProperties=void 0;W.formatElapsedTime=Lc;W.getDocumentIndexId=Rc;W.validateSchema=Yr;W.isGeoPointType=Cc;W.isVectorType=Jr;W.isArrayType=Xr;W.getInnerType=Zr;W.getVectorSize=Qr;var dt=j(),Gr=L(),Uc=L();Object.defineProperty(W,"getDocumentProperties",{enumerable:!0,get:function(){return Uc.getDocumentProperties}});function Lc(t){return{raw:Number(t),formatted:(0,Gr.formatNanoseconds)(t)}}function Rc(t){if(t.id){if(typeof t.id!="string")throw(0,dt.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,Gr.uniqueId)()}function Yr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.createInternalDocumentIDStore=Bc;be.save=es;be.load=ts;be.getInternalDocumentId=ns;be.getDocumentIdFromInternalId=qc;function Bc(){return{idToInternalId:new Map,internalIdToId:[],save:es,load:ts}}function es(t){return{internalIdToId:t.internalIdToId}}function ts(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?ns(t,e.toString()):e}function qc(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.create=rs;K.get=ss;K.getMultiple=is;K.getAll=os;K.store=cs;K.remove=us;K.count=as;K.load=ls;K.save=ds;K.createDocumentsStore=$c;var hn=$();function rs(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function ss(t,e){let n=(0,hn.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function is(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function as(t){return t.count}function ls(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function ds(t){return{docs:t.docs,count:t.count}}function $c(){return{create:rs,get:ss,getMultiple:is,getAll:os,store:cs,remove:us,count:as,load:ls,save:ds}}});var fs=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.AVAILABLE_PLUGIN_HOOKS=void 0;qe.getAllPluginsByHook=Vc;var zc=j();qe.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function Vc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.SINGLE_OR_ARRAY_COMPONENTS=z.FUNCTION_COMPONENTS=z.OBJECT_COMPONENTS=void 0;z.runSingleHook=Wc;z.runMultipleHook=Kc;z.runAfterSearch=Hc;z.runBeforeSearch=Gc;z.runAfterCreate=Yc;var $e=L();z.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];z.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];z.SINGLE_OR_ARRAY_COMPONENTS=[];function Wc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Kc(t,e,n){if(t.some($e.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function Hc(t,e,n,r,s){if(t.some($e.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function Gc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Yc(t,e){if(t.some($e.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var hs=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.AVLTree=Me.AVLNode=void 0;var ue=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Me.AVLNode=ue;var gn=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ue(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ue.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ue(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ue(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:l,node:d}=i[a];if(d.updateHeight(),u){let f=this.rebalanceNode(d);l?l.l===d?l.l=f:l.r===d&&(l.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Me.AVLTree=gn});var ps=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FlatTree=void 0;var yn=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ft.FlatTree=yn});var mn=b(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.boundedLevenshtein=Jc;ze.syncBoundedLevenshtein=Xc;ze.levenshtein=Zc;function gs(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function Jc(t,e,n){let r=gs(t,e,n);return{distance:r,isBounded:r>=0}}function Xc(t,e,n){let r=gs(t,e,n);return{distance:r,isBounded:r>=0}}function Zc(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var ms=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.RadixTree=Oe.RadixNode=void 0;var ys=mn(),wn=L(),Ve=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,wn.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,ys.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,wn.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let l of u)a.includes(l)||a.push(l)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:d,d:f}=c;if(d&&((0,ys.syncBoundedLevenshtein)(e,d,s).isBounded&&(i[d]=[]),(0,wn.getOwnProperty)(i,d)!==void 0&&f.size>0)){let p=new Set(i[d]);for(let g of f)p.add(g);i[d]=Array.from(p)}}if(u>=e.length)continue;let l=e[u];if(c.c.has(l)){let d=c.c.get(l);o.push({node:d,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[d,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),d!==l&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};Oe.RadixNode=Ve;var _n=class t extends Ve{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,Ve.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};Oe.RadixTree=_n});var ws=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.BKDTree=void 0;var Qc=2,eu=6371e3,ht=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},Sn=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ht(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%Qc===0)if(e.lon0;){let{node:a,depth:l}=c.pop();if(a==null)continue;let d=o(e,a.point);(r?d<=n:d>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:l+1}),a.right!=null&&c.push({node:a.right,depth:l+1})}return s&&u.sort((a,l)=>{let d=o(e,a.point),f=o(e,l.point);return s.toLowerCase()==="asc"?d-f:f-d}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let l=t.isPointInPolygon(e,u.point);(l&&n||!l&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,l)=>{let d=u(c,a.point),f=u(c,l.point);return r.toLowerCase()==="asc"?d-f:f-d})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ht.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(d-a)*(i-l)/(f-l)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return eu*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,l=Math.atan((1-s)*Math.tan(c)),d=Math.atan((1-s)*Math.tan(u)),f=Math.sin(l),p=Math.cos(l),g=Math.sin(d),y=Math.cos(d),h=a,m,w=1e3,S,_,I,v,D,A;do{let De=Math.sin(h),Ce=Math.cos(h);if(S=Math.sqrt(y*De*(y*De)+(p*g-f*y*Ce)*(p*g-f*y*Ce)),S===0)return 0;_=f*g+p*y*Ce,I=Math.atan2(S,_),v=p*y*De/S,D=1-v*v,A=_-2*f*g/D,isNaN(A)&&(A=0);let ln=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-ln)*s*v*(I+ln*S*(A+ln*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),Te=1+k/16384*(4096+k*(-768+k*(320-175*k))),Y=k/1024*(256+k*(-128+k*(74-47*k))),an=Y*S*(A+Y/4*(_*(-1+2*A*A)-Y/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*Te*(I-an)}};pt.BKDTree=Sn});var _s=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.BoolNode=void 0;var bn=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};gt.BoolNode=bn});var Ss=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.prioritizeTokenScores=nu;yt.BM25=ru;var tu=j();function nu(t,e,n=0,r){if(e===0)throw(0,tu.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let l=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];d=0}let f=l.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.VectorIndex=ae.DEFAULT_SIMILARITY=void 0;ae.getMagnitude=xn;ae.findSimilarVectors=bs;ae.DEFAULT_SIMILARITY=.8;var In=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=xn(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),bs(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};ae.VectorIndex=In;function xn(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var mt=b(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.insertDocumentScoreParameters=Os;R.insertTokenScoreParameters=Ps;R.removeDocumentScoreParameters=ks;R.removeTokenScoreParameters=Ns;R.create=vn;R.insert=Us;R.insertVector=Ls;R.remove=Rs;R.calculateResultScores=Tn;R.search=js;R.searchByWhereClause=We;R.getSearchableProperties=Fs;R.getSearchablePropertiesWithTypes=Cs;R.load=Bs;R.save=qs;R.createIndex=ou;R.searchByGeoWhereClause=uu;var Pe=j(),As=hs(),vs=ps(),Ts=ms(),Ke=ws(),Ds=_s(),ee=L(),su=Ss(),Ie=Be(),An=$(),Ms=En();function Os(t,e,n,r,s){let i=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function Ps(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function ks(t,e,n,r){let s=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function Ns(t,e,n){t.tokenOccurrences[e][n]--}function vn(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){vn(t,e,o,r,c);continue}if((0,Ie.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new Ms.VectorIndex((0,Ie.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new Ds.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new As.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new Ts.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new vs.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new Ke.BKDTree,isArray:u};break;default:throw(0,Pe.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function iu(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:l}=e.indexes[n];switch(a){case"Bool":{l[u?"true":"false"].add(r);break}case"AVL":{let d=c?.avlRebalanceThreshold??1;l.insert(u,r,d);break}case"Radix":{let d=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,d,o);for(let f of d)t.insertTokenScoreParameters(e,n,r,d,f),l.insert(f,r);break}case"Flat":{l.insert(u,r);break}case"BKD":{l.insert(u,[r]);break}}}}function Us(t,e,n,r,s,i,o,c,u,a,l){if((0,Ie.isVectorType)(o))return Ls(e,n,i,r,s);let d=iu(t,e,n,s,c,u,a,l);if(!(0,Ie.isArrayType)(o))return d(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let an=Y.length;for(let at=0;at[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(d===1)return m;if(d===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(v=>v===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([v])=>v===I)),_=Math.ceil(S.length*d);return[...w,...S.slice(0,_)]}return m}function We(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>We(t,e,u,r));return(0,ee.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>We(t,e,u,r)).reduce((u,a)=>(0,ee.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let l=1;l<=u.internalIdToId.length;l++)c.add(l);let a=We(t,e,o,r);return(0,ee.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,Pe.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:l}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,ee.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,ee.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=xs(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=xs(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=au(i[o],y)}}continue}let d=Object.keys(c);if(d.length>1)throw(0,Pe.createError)("INVALID_FILTER_OPERATION",d.length);if(a==="Flat"){let f=new Set(l?u.filterArr(c):u.filter(c));i[o]=(0,ee.setUnion)(i[o],f);continue}if(a==="AVL"){let f=d[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,Pe.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,ee.setUnion)(i[o],g)}}return(0,ee.setIntersection)(...Object.values(i))}function Fs(t){return t.searchableProperties}function Cs(t){return t.searchablePropertiesWithTypes}function Bs(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,l={},d={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":l[f]={type:"Radix",node:Ts.RadixTree.fromJSON(p),isArray:y};break;case"Flat":l[f]={type:"Flat",node:vs.FlatTree.fromJSON(p),isArray:y};break;case"AVL":l[f]={type:"AVL",node:As.AVLTree.fromJSON(p),isArray:y};break;case"BKD":l[f]={type:"BKD",node:Ke.BKDTree.fromJSON(p),isArray:y};break;case"Bool":l[f]={type:"Bool",node:Ds.BoolNode.fromJSON(p),isArray:y};break;default:l[f]=n[f]}}for(let f of Object.keys(r))d[f]={type:"Vector",isArray:!1,node:Ms.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:l,vectorIndexes:d,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function qs(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let d of Object.keys(n))a[d]=n[d].node.toJSON();let l={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:g}=e[d];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?l[d]={type:f,node:p.toJSON(),isArray:g}:(l[d]=e[d],l[d].node=l[d].node.toJSON())}return{indexes:l,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function ou(){return{create:vn,insert:Us,remove:Rs,insertDocumentScoreParameters:Os,insertTokenScoreParameters:Ps,removeDocumentScoreParameters:ks,removeTokenScoreParameters:Ns,calculateResultScores:Tn,search:js,searchByWhereClause:We,getSearchableProperties:Fs,getSearchablePropertiesWithTypes:Cs,load:Bs,save:qs}}function xs(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function cu(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function uu(t,e){let n=t,r=cu(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:l="m",inside:d=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,ee.convertDistanceToMeters)(u,l);return c=o.searchByRadius(p,g,d,"asc",f),Es(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:l=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",l);let d=Ke.BKDTree.calculatePolygonCentroid(u);return Es(c,d,l)}return null}function au(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.load=Vs;He.save=Ws;He.createSorter=Eu;var Dn=j(),lu=Be(),wt=$(),du=L(),fu=lt();function $s(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=$s(t,e,c,r,u);(0,du.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,lu.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,Dn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function hu(t,e,n,r){return r?.enabled!==!1?$s(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function pu(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&Mn(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function zs(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)wu(t,n);t.isSorted=!0}function gu(t,e,n){return e[1].localeCompare(n[1],(0,fu.getLocale)(t))}function yu(t,e){return t[1]-e[1]}function mu(t,e){return e[1]?-1:1}function wu(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=gu.bind(null,t.language);break;case"number":r=yu.bind(null);break;case"boolean":r=mu.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function Su(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function bu(t,e,n){if(!t.enabled)throw(0,Dn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,Dn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return Mn(t,r),zs(t),e.sort((o,c)=>{let u=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),l=typeof u<"u",d=typeof a<"u";return!l&&!d?0:l?d?s?a-u:u-a:-1:1}),e}function Iu(t){return t.enabled?t.sortableProperties:[]}function xu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Vs(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,l])=>[+a,l])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Ws(t){if(!t.enabled)return{enabled:!1};_u(t),zs(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function Eu(){return{create:hu,insert:pu,remove:Su,save:Ws,load:Vs,sortBy:bu,getSortableProperties:Iu,getSortablePropertiesWithTypes:xu}}});var Hs=b(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.replaceDiacritics=Du;var Ks=192,Au=383,vu=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Tu(t){return tAu?t:vu[t-Ks]||t}function Du(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.stemmer=Nu;var Mu={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Ou={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Pu="[^aeiou]",St="[aeiouy]",J=Pu+"[^aeiouy]*",Ge=St+"[aeiou]*",kn="^("+J+")?"+Ge+J,ku="^("+J+")?"+Ge+J+"("+Ge+")?$",_t="^("+J+")?"+Ge+J+Ge+J,Gs="^("+J+")?"+St;function Nu(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(kn),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(Gs),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+J+St+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Gs),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(kn),e&&r.test(e)&&(t=e+Mu[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(kn),e&&r.test(e)&&(t=e+Ou[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(_t),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(_t),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(_t),s=new RegExp(ku),i=new RegExp("^"+J+St+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(_t),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var It=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.normalizeToken=Un;bt.createTokenizer=ju;var xe=j(),Uu=Hs(),Xs=lt(),Lu=Ys();function Un(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,Uu.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function Ru(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function Js(t,e,n,r=!0){if(e&&e!==this.language)throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=Xs.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=Ru(i);return this.allowDuplicates?o:Array.from(new Set(o))}function ju(t={}){if(!t.language)t.language="english";else if(!Xs.SUPPORTED_LANGUAGES.includes(t.language))throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,xe.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=Lu.stemmer;else throw(0,xe.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Js,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Un,normalizationCache:new Map};return r.tokenize=Js.bind(r),r.normalizeToken=Un,r}});var Ln=b(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.getMatchingRules=Zs;ke.load=Qs;ke.save=ei;ke.createPinning=Ku;function Fu(t){return{sharedInternalDocumentStore:t,rules:new Map}}function Cu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function Bu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function qu(t,e){return t.rules.delete(e)}function $u(t,e){return t.rules.get(e)}function zu(t){return Array.from(t.rules.values())}function Vu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Wu(t,e){return t?e.conditions.every(n=>Vu(t,n)):!1}function Zs(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Wu(e,r)&&n.push(r);return n}function Qs(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function ei(t){return{rules:Array.from(t.rules.entries())}}function Ku(){return{create:Fu,addRule:Cu,updateRule:Bu,removeRule:qu,getRule:$u,getAllRules:zu,getMatchingRules:Zs,load:Qs,save:ei}}});var ri=b(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.create=ea;var xt=Be(),Hu=pn(),ti=fs(),Et=Q(),Gu=mt(),Yu=$(),Ju=On(),ni=It(),Xu=Ln(),At=j(),Zu=L();function Qu(t){let e={formatElapsedTime:xt.formatElapsedTime,getDocumentIndexId:xt.getDocumentIndexId,getDocumentProperties:xt.getDocumentProperties,validateSchema:xt.validateSchema};for(let n of Et.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,At.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Et.OBJECT_COMPONENTS.includes(n)&&!Et.FUNCTION_COMPONENTS.includes(n))throw(0,At.createError)("UNSUPPORTED_COMPONENT",n)}function ea({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,At.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,Zu.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,l=r.pinning;if(o?o.tokenize?o=o:o=(0,ni.createTokenizer)(o):o=(0,ni.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,At.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let d=(0,Yu.createInternalDocumentIDStore)();c||=(0,Gu.createIndex)(),a||=(0,Ju.createSorter)(),u||=(0,Hu.createDocumentsStore)(),l||=(0,Xu.createPinning)(),Qu(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:l,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:ta()};h.data={index:h.index.create(h,d,t),docs:h.documentsStore.create(h,d),sorting:h.sorter.create(h,d,t,e),pinning:h.pinning.create(d)};for(let w of ti.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,ti.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,Et.runAfterCreate)(m,h),h}function ta(){return"{{VERSION}}"}});var jn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getByID=na;vt.count=ra;function na(t,e){return t.documentsStore.get(t.data.docs,e)}function ra(t){return t.documentsStore.count(t.data.docs)}});var Fn=b(U=>{"use strict";var si=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sa=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ia=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&si(e,t,n)},Ye=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.insert=qn;Je.insertMultiple=fa;Je.innerInsertMultiple=ha;var Cn=Fn(),C=L(),Ne=Q(),Ue=j(),Bn=$();function qn(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Ue.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ua(t,e,n,r,s):aa(t,e,n,r,s)}var oa=new Set(["enum","enum[]"]),ca=new Set(["string","number"]);async function ua(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ii(y,h,p,g)}return await la(t,c,l,f,a,n,e,s),r||await(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function aa(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ii(y,h,p,g)}return da(t,c,l,f,a,n,e,s),r||(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function ii(t,e,n,r){if(!((0,Cn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,Cn.isVectorType)(e)&&Array.isArray(r))&&!((0,Cn.isArrayType)(e)&&Array.isArray(r))&&!(oa.has(e)&&ca.has(t))&&t!==e)throw(0,Ue.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function la(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l];await t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function da(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l],p=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function fa(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.afterInsertMultiple)||(0,C.isAsyncFunction)(t.beforeInsertMultiple)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?oi(t,e,n,r,s,i):ci(t,e,n,r,s,i)}async function oi(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let l=Math.min(a+n,e.length),d=e.slice(a,l);for(let f of d){let p={avlRebalanceThreshold:d.length},g=await qn(t,f,r,s,p);o.push(g)}return l};return await(async()=>{let a=0;for(;a0){let d=Date.now()-l,f=i-d;f>0&&(0,C.sleep)(f)}}})(),s||await(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ci(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let l=e.slice(c*n,(c+1)*n);if(l.length===0)return!1;for(let d of l){let f={avlRebalanceThreshold:l.length},p=qn(t,d,r,s,f);o.push(p)}return c++,!0}function a(){let l=Date.now();for(;u();)if(i>0){let f=Date.now()-l;if(f>=i){let p=i-f%i;p>0&&(0,C.sleep)(p)}}}return a(),s||(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ha(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?oi(t,e,n,r,s,i):ci(t,e,n,r,s,i)}});var ui=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.insertPin=pa;Ee.updatePin=ga;Ee.deletePin=ya;Ee.getPin=ma;Ee.getAllPins=wa;function pa(t,e){t.pinning.addRule(t.data.pinning,e)}function ga(t,e){t.pinning.updateRule(t.data.pinning,e)}function ya(t,e){return t.pinning.removeRule(t.data.pinning,e)}function ma(t,e){return t.pinning.getRule(t.data.pinning,e)}function wa(t){return t.pinning.getAllRules(t.data.pinning)}});var zn=b(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.remove=$n;Dt.removeMultiple=ba;var de=Q(),fe=$(),le=L();function $n(t,e,n,r){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)?_a(t,e,n,r):Sa(t,e,n,r)}async function _a(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||await(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Sa(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function ba(t,e,n,r,s){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)||(0,le.isAsyncFunction)(t.beforeRemoveMultiple)||(0,le.isAsyncFunction)(t.afterRemoveMultiple)?Ia(t,e,n,r,s):xa(t,e,n,r,s)}async function Ia(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function l(){let d=e.slice(a*n,++a*n);if(!d.length)return c();for(let f of d)try{await $n(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(l,0)}setTimeout(l,0)}),s||await(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function xa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let l of a)$n(t,l,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Vn=b(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.MODE_VECTOR_SEARCH=he.MODE_HYBRID_SEARCH=he.MODE_FULLTEXT_SEARCH=void 0;he.MODE_FULLTEXT_SEARCH="fulltext";he.MODE_HYBRID_SEARCH="hybrid";he.MODE_VECTOR_SEARCH="vector"});var Mt=b(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.getFacets=Ma;var Ea=j(),Aa=L();function va(t,e){return t[1]-e[1]}function Ta(t,e){return e[1]-t[1]}function Da(t="desc"){return t.toLowerCase()==="asc"?va:Ta}function Ma(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let l;if(c[a]==="number"){let{ranges:d}=n[a],f=d.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function li(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Ot=b(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.getGroups=ka;var di=j(),Kn=L(),Oa=$(),Pa={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},fi=["string","number","boolean"];function ka(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,di.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!fi.includes(i[w]))throw(0,di.createError)("INVALID_GROUP_BY_PROPERTY",w,fi.join(", "),i[w])}let o=e.map(([m])=>(0,Oa.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,l=[],d={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}l.push(Array.from(_)),d[w]=S}let f=hi(l),p=f.length,g=[];for(let m=0;mv-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),v=S.getInitialValue(w.indexes.length),D=_.reduce(I,v);h[m]={values:w.values,result:D}}return h}function hi(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=hi(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Kn.safeArrayPush)(c,o),s.push(c)}return s}});var Pt=b(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.applyPinningRules=La;var Na=$(),Ua=Ln();function La(t,e,n,r){let s=(0,Ua.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,Na.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),l=1e6,d=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?d.push([h,l-m]):t.documentsStore.get(t.data.docs,h)&&d.push([h,0]);d.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of d){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var Yn=b(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.defaultBM25Params=void 0;te.innerFullTextSearch=yi;te.fullTextSearch=Wa;var Ra=Mt(),ja=Ot(),pi=Q(),Fa=$(),Ca=mt(),Ba=Pt(),qa=j(),kt=L(),$a=jn(),gi=Xe();function yi(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let d=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>d[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let d of s)if(!o.includes(d))throw(0,qa.createError)("UNKNOWN_INDEX",d,o.join(", "));o=o.filter(d=>s.includes(d))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,l=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let d=(0,$a.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},Ka(e.relevance),d,u,l),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=Va(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${za(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let d=(0,Ca.searchByGeoWhereClause)(i,e.where);d?a=d:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function za(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Va(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Wa(t,e,n){let r=(0,kt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:l=0,distinctOn:d,includeVectors:f=!1}=e,p=e.preflight===!0,g=yi(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,Fa.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(kt.sortTokenScorePredicate);g=(0,Ba.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=d?(0,gi.fetchDocumentsWithDistinct)(t,g,l,a,d):(0,gi.fetchDocuments)(t,g,l,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,kt.removeVectorsFromHits)(h,c)),u){let m=(0,Ra.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,ja.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,kt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,pi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,pi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}te.defaultBM25Params={k:1.2,b:.75,d:.5};function Ka(t){let e=t??{};return e.k=e.k??te.defaultBM25Params.k,e.b=e.b??te.defaultBM25Params.b,e.d=e.d??te.defaultBM25Params.d,e}});var Rt=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.innerVectorSearch=wi;Lt.searchVector=Za;var Nt=L(),Ha=Mt(),Ut=j(),Ga=Ot(),Ya=$(),mi=Q(),Ja=En(),Xa=Pt();function wi(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Ut.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Ut.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Ut.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Ut.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??Ja.DEFAULT_SIMILARITY,c)}function Za(t,e,n="english"){let r=(0,Nt.getNanosecondsTime)();function s(){let c=wi(t,e,n).sort(Nt.sortTokenScorePredicate);c=(0,Xa.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,Ha.getFacets)(t,c,e.facets));let l=e.vector.property,d=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.innerHybridSearch=bi;Ft.hybridSearch=il;var jt=L(),Qa=Mt(),el=Ot(),tl=Xe(),nl=Yn(),rl=Rt(),_i=Q(),sl=Pt();function bi(t,e,n){let r=ol((0,nl.innerFullTextSearch)(t,e,n)),s=(0,rl.innerVectorSearch)(t,e,n),i=e.hybridWeights;return ul(r,s,e.term??"",i)}function il(t,e,n){let r=(0,jt.getNanosecondsTime)();function s(){let c=bi(t,e,n);c=(0,sl.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,Qa.getFacets)(t,c,e.facets));let l;e.groupBy&&(l=(0,el.getGroups)(t,c,e.groupBy));let d=e.offset??0,f=e.limit??10,p=(0,tl.fetchDocuments)(t,c,d,f).filter(Boolean),g=(0,jt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,jt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...l?{groups:l}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,jt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,_i.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,_i.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function Jn(t){return t[1]}function ol(t){let e=Math.max.apply(Math,t.map(Jn));return t.map(([n,r])=>[n,r/e])}function Si(t,e){return t/e}function cl(t,e){return(n,r)=>n*t+r*e}function ul(t,e,n,r){let s=Math.max.apply(Math,t.map(Jn)),i=Math.max.apply(Math,e.map(Jn)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:al(n),a=new Map,l=t.length,d=cl(c,u);for(let p=0;pg[1]-p[1])}function al(t){return{text:.5,vector:.5}}});var Xe=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.search=gl;Ze.fetchDocumentsWithDistinct=yl;Ze.fetchDocuments=ml;var xi=$(),ll=j(),dl=L(),Ct=Vn(),fl=Yn(),hl=Rt(),pl=Ii();function gl(t,e,n){let r=e.mode??Ct.MODE_FULLTEXT_SEARCH;if(r===Ct.MODE_FULLTEXT_SEARCH)return(0,fl.fullTextSearch)(t,e,n);if(r===Ct.MODE_VECTOR_SEARCH)return(0,hl.searchVector)(t,e);if(r===Ct.MODE_HYBRID_SEARCH)return(0,pl.hybridSearch)(t,e);throw(0,ll.createError)("INVALID_SEARCH_MODE",r)}function yl(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,l=0;for(let d=0;d"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,dl.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),l++,!(l<=n)&&(c.push({id:(0,xi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),l>=n+r)))break}return c}function ml(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,l]=u;if(!o.has(a)){let d=t.documentsStore.get(s,a);i[c]={id:(0,xi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:l,document:d},o.add(a)}}return i}});var Ei=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.load=wl;Bt.save=_l;function wl(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function _l(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var Xn=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.update=Sl;zt.updateMultiple=xl;var pe=Q(),Ai=j(),qt=Tt(),$t=zn(),F=L();function Sl(t,e,n,r,s){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)?bl(t,e,n,r,s):Il(t,e,n,r,s)}async function bl(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,pe.runSingleHook)(t.beforeUpdate,t,e),await(0,$t.remove)(t,e,r,s);let i=await(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function Il(t,e,n,r,s){!s&&t.beforeUpdate&&(0,pe.runSingleHook)(t.beforeUpdate,t,e),(0,$t.remove)(t,e,r,s);let i=(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function xl(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)||(0,F.isAsyncFunction)(t.beforeUpdateMultiple)||(0,F.isAsyncFunction)(t.afterUpdateMultiple)||(0,F.isAsyncFunction)(t.beforeRemoveMultiple)||(0,F.isAsyncFunction)(t.afterRemoveMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.afterInsertMultiple)?El(t,e,n,r,s,i):Al(t,e,n,r,s,i)}async function El(t,e,n,r,s,i){i||await(0,pe.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.upsert=vl;Kt.upsertMultiple=Ml;var ge=Q(),Le=j(),Vt=Tt(),Wt=Xn(),P=L();function vl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Tl(t,e,n,r,s):Dl(t,e,n,r,s)}async function Tl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Wt.update)(t,i,e,n,r):c=await(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Dl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Wt.update)(t,i,e,n,r):c=(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ml(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Ol(t,e,n,r,s):Pl(t,e,n,r,s)}async function Ol(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=await(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=await(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&await(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function Pl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var Ti=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AnswerSession=void 0;var Ht=j(),kl=Xe(),Nl="orama-secure-proxy",Zn=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,Ht.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,kl.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===Nl)}let r=await n();if(!r)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};Gt.AnswerSession=Zn});var Di=b(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.kRemovals=H.kInsertions=H.MODE_VECTOR_SEARCH=H.MODE_HYBRID_SEARCH=H.MODE_FULLTEXT_SEARCH=void 0;var Qn=Vn();Object.defineProperty(H,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_FULLTEXT_SEARCH}});Object.defineProperty(H,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_HYBRID_SEARCH}});Object.defineProperty(H,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_VECTOR_SEARCH}});H.kInsertions=Symbol("orama.insertions");H.kRemovals=Symbol("orama.removals")});var Mi=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var Ul=mn();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return Ul.boundedLevenshtein}});var ne=L();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return ne.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return ne.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return ne.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return ne.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return ne.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return ne.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return ne.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return ne.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return ne.setDifference}});var Ll=It();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return Ll.normalizeToken}})});var Fi=b(x=>{"use strict";var Oi=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Rl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Oi(e,t,n)},Pi=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.utf8Count=$l;re.utf8EncodeJs=Ci;re.utf8EncodeTE=Bi;re.utf8Encode=Wl;re.utf8DecodeJs=qi;re.utf8DecodeTD=$i;re.utf8Decode=Yl;function $l(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var zl=new TextEncoder,Vl=50;function Bi(t,e,n){zl.encodeInto(t,e.subarray(n))}function Wl(t,e,n){t.length>Vl?Bi(t,e,n):Ci(t,e,n)}var Kl=4096;function qi(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(c);i.length>=Kl&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var Hl=new TextDecoder,Gl=200;function $i(t,e,n){let r=t.subarray(e,e+n);return Hl.decode(r)}function Yl(t,e,n){return n>Gl?$i(t,e,n):qi(t,e,n)}});var tr=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.ExtData=void 0;var er=class{type;data;constructor(e,n){this.type=e,this.data=n}};Jt.ExtData=er});var Zt=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DecodeError=void 0;var nr=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Xt.DecodeError=nr});var Qt=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.UINT32_MAX=void 0;ye.setUint64=Jl;ye.setInt64=Xl;ye.getInt64=Zl;ye.getUint64=Ql;ye.UINT32_MAX=4294967295;function Jl(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xl(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zl(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Ql(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var rr=b(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.timestampExtension=G.EXT_TIMESTAMP=void 0;G.encodeTimeSpecToTimestamp=Vi;G.encodeDateToTimeSpec=Wi;G.encodeTimestampExtension=Ki;G.decodeTimestampToTimeSpec=Hi;G.decodeTimestampExtension=Gi;var ed=Zt(),zi=Qt();G.EXT_TIMESTAMP=-1;var td=4294967296-1,nd=17179869184-1;function Vi({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=nd)if(e===0&&t<=td){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,zi.setInt64)(r,4,t),n}}function Wi(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Ki(t){if(t instanceof Date){let e=Wi(t);return Vi(e)}else return null}function Hi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,zi.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ed.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Gi(t){let e=Hi(t);return new Date(e.sec*1e3+e.nsec/1e6)}G.timestampExtension={type:G.EXT_TIMESTAMP,encode:Ki,decode:Gi}});var nn=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ExtensionCodec=void 0;var en=tr(),rd=rr(),sr=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(rd.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.ensureUint8Array=id;function sd(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function id(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):sd(t)?new Uint8Array(t):Uint8Array.from(t)}});var ur=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.Encoder=X.DEFAULT_INITIAL_BUFFER_SIZE=X.DEFAULT_MAX_DEPTH=void 0;var Yi=Yt(),od=nn(),Ji=Qt(),cd=or();X.DEFAULT_MAX_DEPTH=100;X.DEFAULT_INITIAL_BUFFER_SIZE=2048;var cr=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??od.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??X.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??X.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Yi.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Yi.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,cd.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Ji.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Ji.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};X.Encoder=cr});var Xi=b(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.encode=ad;var ud=ur();function ad(t,e){return new ud.Encoder(e).encodeSharedRef(t)}});var Zi=b(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.prettyByte=ld;function ld(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var Qi=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CachedKeyDecoder=void 0;var dd=Yt(),fd=16,hd=16,dr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=fd,n=hd){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,dd.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};rn.CachedKeyDecoder=dr});var on=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.Decoder=void 0;var fr=Zi(),pd=nn(),Ae=Qt(),gd=Yt(),eo=or(),yd=Qi(),se=Zt(),hr="array",tt="map_key",no="map_value",md=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new se.DecodeError("The type of key must be string or number but "+typeof t)},pr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=hr,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=tt,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===hr){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===tt||e.type===no){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},et=-1,yr=new DataView(new ArrayBuffer(0)),wd=new Uint8Array(yr.buffer);try{yr.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var to=new RangeError("Insufficient data"),_d=new yd.CachedKeyDecoder,gr=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=yr;bytes=wd;headByte=et;stack=new pr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ae.UINT32_MAX,this.maxBinLength=e?.maxBinLength??Ae.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??Ae.UINT32_MAX,this.maxMapLength=e?.maxMapLength??Ae.UINT32_MAX,this.maxExtLength=e?.maxExtLength??Ae.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:_d,this.mapKeyConverter=e?.mapKeyConverter??md}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=et,this.stack.reset()}setBuffer(e){let n=(0,eo.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===et&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,eo.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,fr.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new se.DecodeError(`Unrecognized type byte: ${(0,fr.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===hr)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===tt){if(n==="__proto__")throw new se.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=no;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=tt;continue e}}return n}}readHeadByte(){return this.headByte===et&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=et}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new se.DecodeError(`Unrecognized array type byte: ${(0,fr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new se.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new se.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new se.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===tt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new se.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw to;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new se.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,Ae.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,Ae.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};sn.Decoder=gr});var so=b(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.decode=Sd;cn.decodeMulti=bd;var ro=on();function Sd(t,e){return new ro.Decoder(e).decode(t)}function bd(t,e){return new ro.Decoder(e).decodeMulti(t)}});var co=b(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.isAsyncIterable=io;nt.asyncIterableFromStream=oo;nt.ensureAsyncIterable=Id;function io(t){return t[Symbol.asyncIterator]!=null}async function*oo(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function Id(t){return io(t)?t:oo(t)}});var uo=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.decodeAsync=xd;rt.decodeArrayStream=Ed;rt.decodeMultiStream=Ad;var mr=on(),wr=co();async function xd(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeAsync(n)}function Ed(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeArrayStream(n)}function Ad(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeStream(n)}});var lo=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var vd=Xi();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return vd.encode}});var ao=so();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return ao.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return ao.decodeMulti}});var _r=uo();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return _r.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return _r.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return _r.decodeMultiStream}});var Td=on();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return Td.Decoder}});var Dd=Zt();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return Dd.DecodeError}});var Md=ur();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return Md.Encoder}});var Od=nn();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return Od.ExtensionCodec}});var Pd=tr();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return Pd.ExtData}});var Re=rr();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Re.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Re.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Re.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Re.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return Re.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return Re.decodeTimestampExtension}})});var Ir=b(($h,yo)=>{"use strict";var q=require("fs"),Z=Fi(),{encode:kd,decode:Nd}=lo(),Sr=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function fo(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function Ud(t){let e=fo(t);return Z.create({schema:e})}function Ld(t){for(let e of Sr)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function Rd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");Ld(e);let n={};for(let r of Sr)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return Z.insert(t,n)}async function jd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return ho(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function ho(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await Z.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await Z.removeMultiple(t,r)}function br(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function Fd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await Z.search(t,s)).hits.map(br)}async function Cd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await Z.search(t,i)).hits.map(br)}async function Bd(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await Z.search(t,u)).hits.map(br)}async function qd(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=Z.save(t),r={v:1,schema:t.schema,raw:n},s=kd(r),i=e+".tmp";q.writeFileSync(i,s),q.renameSync(i,e)}async function $d(t){if(!t)throw new Error("loadStore: storePath is required");if(!q.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=q.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=Nd(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await Z.create({schema:n.schema});return Z.load(r,n.raw),r}var zd=3e4,Vd=50,Wd=1e4;function Kd(t){try{let e=q.openSync(t,"wx");return q.writeSync(e,String(process.pid)),q.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function Hd(t){return new Promise(e=>setTimeout(e,t))}async function po(t){let e=Date.now()+Wd;for(;;){if(Kd(t))return;try{let n=q.statSync(t);if(Date.now()-n.mtimeMs>zd){try{q.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await Hd(Vd)}}function go(t){try{q.unlinkSync(t)}catch{}}async function Gd(t,e){await po(t);try{return await e()}finally{go(t)}}var Yd=["provider","model","dimensions","last_indexed","pending"];function Jd(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";q.writeFileSync(r,JSON.stringify(n,null,2)+` +`,"utf8"),q.renameSync(r,t)}function Xd(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!q.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=q.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}yo.exports={SCHEMA_FIELDS:Sr,METADATA_FIELDS:Yd,buildSchema:fo,createStore:Ud,insertDocument:Rd,removeByIdentity:jd,removeByFilter:ho,searchFulltext:Fd,searchVector:Cd,searchHybrid:Bd,saveStore:qd,loadStore:$d,acquireLock:po,releaseLock:go,withLock:Gd,writeMetadata:Jd,readMetadata:Xd}});var bo=b((zh,So)=>{"use strict";var Zd=/^\s*(```+|~~~+)/,mo=/^---\s*$/;function Qd(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` `).replace(/\r/g,` -`),d=c?Pd(a):a;if(d.trim()==="")return[];let l=d.split(` -`);if(l.length_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:ye(d)}];let h=kd(l,f,y),m=Nd(h,l,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=ye(l.slice(_.startLine,_.endLine+1).join(` -`)),T={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&uo(T))continue;let D=I.split(` -`);if(_.action==="regular"&&D.length>s){let A=Ud(T,r);for(let k of A)u&&uo(k)||S.push({content:k.text})}else S.push({content:I})}return S}function ye(t){return t.replace(/\s+$/,"")}function Pd(t){let e=t.split(` -`);if(e.length===0||!co.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let d=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),l=o.startLine,f=!0;for(let p of d)p.startLine>l&&(i.push({action:"regular",startLine:l,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),l=p.endLine+1;l<=o.endLine&&i.push({action:"regular",startLine:l,endLine:o.endLine,heading:"",headingLine:""})}return i}function Ud(t,e){let n=t.text.split(` -`),s=ao(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=ye(c.join(` -`));u.trim()!==""&&i.push({heading:t.heading,headingLine:t.headingLine,text:u})}for(let c=0;c_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:me(l)}];let h=tf(d,f,y),m=nf(h,d,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=me(d.slice(_.startLine,_.endLine+1).join(` +`)),v={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&wo(v))continue;let D=I.split(` +`);if(_.action==="regular"&&D.length>s){let A=rf(v,r);for(let k of A)u&&wo(k)||S.push({content:k.text})}else S.push({content:I})}return S}function me(t){return t.replace(/\s+$/,"")}function ef(t){let e=t.split(` +`);if(e.length===0||!mo.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let l=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),d=o.startLine,f=!0;for(let p of l)p.startLine>d&&(i.push({action:"regular",startLine:d,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),d=p.endLine+1;d<=o.endLine&&i.push({action:"regular",startLine:d,endLine:o.endLine,heading:"",headingLine:""})}return i}function rf(t,e){let n=t.text.split(` +`),s=_o(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=me(c.join(` +`));u.trim()!==""&&i.push({heading:t.heading,headingLine:t.headingLine,text:u})}for(let c=0;c{"use strict";var ho="stub";function Rd(t){let e=2166136261;for(let n=0;n>>0}function Ld(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var gr=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=Rd(n)||1,s=Ld(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var go="text-embedding-3-small",yo="https://api.openai.com/v1/embeddings",mr=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||go,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var wo=require("fs"),_o=require("path"),Bd=require("os"),{StubProvider:jd}=yr(),{OpenAIProvider:Fd}=wr(),So={similarity_threshold:.8,decay_months:6},_r=["stub","openai"];function bo(){return _o.join(Bd.homedir(),".config","workflows","config.json")}function Io(t){return _o.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Sr(t){if(!wo.existsSync(t))return null;let e;try{e=wo.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function Cd(t){let e=t&&t.systemPath||bo(),n=t&&t.projectPath||Io(),r=Sr(e),s=Sr(n),i=Object.assign({},So);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);if(i.api_key_env){let o=process.env[i.api_key_env];i._api_key=o&&o.trim()!==""?o:null}else i._api_key=null;return i}function qd(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new jd(n!=null?{dimensions:n}:void 0)}if(!_r.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${_r.join(", ")}`);return t._api_key&&e==="openai"?new Fd({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}xo.exports={DEFAULTS:So,AVAILABLE_PROVIDERS:_r,systemConfigPath:bo,projectConfigPath:Io,readConfigFile:Sr,loadConfig:Cd,resolveProvider:qd}});var v=require("fs"),C=require("path"),E=oo(),vo=fo(),{StubProvider:$d}=yr(),{OpenAIProvider:zd}=wr(),Ue=Eo(),Ir=["research","discussion","investigation","specification"],Vd=v.existsSync(C.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?C.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):C.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),tt=[1e3,2e3,4e3],Wd=5,xr=1536;function Do(t){let e=[],n={},r=0;for(;r [options] +`).trim()===""}So.exports={chunk:Qd}});var Er=b((Vh,xo)=>{"use strict";var Io="stub";function sf(t){let e=2166136261;for(let n=0;n>>0}function of(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var xr=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=sf(n)||1,s=of(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var Eo="text-embedding-3-small",Ao="https://api.openai.com/v1/embeddings",Ar=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||Eo,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var je=require("fs"),Dr=require("path"),cf=require("os"),{StubProvider:uf}=Er(),{OpenAIProvider:af}=un(),To={similarity_threshold:.8,decay_months:6},vr=["stub","openai"];function Do(){return Dr.join(cf.homedir(),".config","workflows","config.json")}function Mo(t){return Dr.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Tr(t){if(!je.existsSync(t))return null;let e;try{e=je.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function lf(t){let e=t&&t.systemPath||Do(),n=t&&t.projectPath||Mo(),r=Tr(e),s=Tr(n),i=Object.assign({},To);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);if(i.api_key_env){let o=process.env[i.api_key_env];i._api_key=o&&o.trim()!==""?o:null}else i._api_key=null;return i}function df(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new uf(n!=null?{dimensions:n}:void 0)}if(!vr.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${vr.join(", ")}`);return t._api_key&&e==="openai"?new af({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}function ff(t,e){if(!t)throw new Error("writeConfigFile: filePath is required");if(e==null||typeof e!="object"||!e.knowledge)throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key');let n=Dr.dirname(t);je.existsSync(n)||je.mkdirSync(n,{recursive:!0});let r=t+".tmp";je.writeFileSync(r,JSON.stringify(e,null,2)+` +`,"utf8"),je.renameSync(r,t)}Oo.exports={DEFAULTS:To,AVAILABLE_PROVIDERS:vr,systemConfigPath:Do,projectConfigPath:Mo,readConfigFile:Tr,loadConfig:lf,resolveProvider:df,writeConfigFile:ff}});var Ko=b((Hh,Wo)=>{"use strict";var we=require("fs"),_e=require("path"),hf=require("readline"),ie=Mr(),Or=Ir(),{OpenAIProvider:pf}=un(),Po="text-embedding-3-small",ko=1536,No="OPENAI_API_KEY",Uo=1536;function Lo(){process.stdin.isTTY||(process.stderr.write(`knowledge setup requires an interactive terminal. Run it directly, not through Claude or a pipe. +`),process.exit(1))}function Ro(){let t=hf.createInterface({input:process.stdin,output:process.stdout});return t.on("SIGINT",()=>{process.stderr.write(` +Setup cancelled. +`),t.close(),process.exit(130)}),t}function st(t,e,n){let r=n!=null&&n!==""?` [${n}]`:"";return new Promise(s=>{t.question(`${e}${r}: `,i=>{let o=(i||"").trim();s(o===""&&n!==void 0&&n!==null?String(n):o)})})}async function it(t,e,n){let r=n?"Y/n":"y/N";return new Promise(s=>{t.question(`${e} (${r}): `,i=>{let o=(i||"").trim().toLowerCase();if(o==="")return s(!!n);s(o==="y"||o==="yes")})})}function jo({model:t,dimensions:e,apiKeyEnv:n}){return{knowledge:{provider:"openai",model:t,dimensions:e,api_key_env:n,similarity_threshold:ie.DEFAULTS.similarity_threshold,decay_months:ie.DEFAULTS.decay_months}}}function Fo(){return{knowledge:{similarity_threshold:ie.DEFAULTS.similarity_threshold,decay_months:ie.DEFAULTS.decay_months}}}function Co(){return{knowledge:{}}}function Bo(t){if(!we.existsSync(t))return{exists:!1,valid:!1,knowledge:null};try{let e=we.readFileSync(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||!n.knowledge||typeof n.knowledge!="object"||Array.isArray(n.knowledge)?{exists:!0,valid:!1,knowledge:null,reason:'missing or invalid "knowledge" key'}:{exists:!0,valid:!0,knowledge:n.knowledge}}catch(e){return{exists:!0,valid:!1,knowledge:null,reason:e.message}}}function qo(t){let e=_e.join(t,"config.json"),n=_e.join(t,"store.msp"),r=_e.join(t,"metadata.json"),s=we.existsSync(t),i=we.existsSync(e),o=we.existsSync(n),c=we.existsSync(r);return{dirExists:s,configExists:i,storeExists:o,metadataExists:c,fullyInitialised:i&&o&&c,partiallyInitialised:s&&!(i&&o&&c)}}async function $o({apiKey:t,model:e,dimensions:n}){let s=await new pf({apiKey:t,model:e,dimensions:n}).embed("knowledge base setup test");if(!Array.isArray(s)||s.length!==n)throw new Error(`Expected a vector of length ${n}, got ${Array.isArray(s)?s.length:typeof s}`);return!0}async function zo(t){let e=ie.systemConfigPath(),n=Bo(e);if(n.exists&&n.valid){process.stdout.write(` +System config already exists at ${e} +`),process.stdout.write(` Current settings: +`);let l=n.knowledge;if(process.stdout.write(` provider: ${l.provider==null?"(none \u2014 stub mode)":l.provider} +`),l.model&&process.stdout.write(` model: ${l.model} +`),l.dimensions&&process.stdout.write(` dimensions: ${l.dimensions} +`),l.api_key_env&&process.stdout.write(` api_key_env: ${l.api_key_env} +`),process.stdout.write(` +`),!await it(t,"Reconfigure system settings?",!1))return process.stdout.write(`Keeping existing system config. +`),{provider:l.provider||null,previouslyStub:!l.provider}}else n.exists&&!n.valid?(process.stdout.write(` +System config at ${e} is not valid: ${n.reason} +`),await it(t,"Overwrite it?",!0)||(process.stdout.write(`Aborting setup so you can fix the file manually. +`),process.exit(1))):process.stdout.write(` +No system config found at ${e}. Creating a new one. +`);let r=n.exists&&n.valid&&!n.knowledge.provider;process.stdout.write(` +Embedding provider: +`),process.stdout.write(` openai \u2014 OpenAI embeddings API (requires an API key) +`),process.stdout.write(` skip \u2014 Stub mode (keyword-only search, no embeddings) + +`);let s;for(;s=(await st(t,"Provider (openai / skip)","openai")).toLowerCase(),!(s==="openai"||s==="skip");)process.stdout.write(`Unknown choice "${s}". Enter "openai" or "skip". +`);if(s==="skip")return ie.writeConfigFile(e,Fo()),process.stdout.write(` +Wrote stub-mode system config to ${e} +`),process.stdout.write("Stub mode uses keyword-only (BM25) search. Semantic search is disabled. Run `knowledge setup` again later to configure a provider.\n"),{provider:null,previouslyStub:r};let i=await st(t,"Embedding model",Po),o=await st(t,"Vector dimensions",String(ko)),c=parseInt(o,10);(!Number.isInteger(c)||c<=0)&&(process.stderr.write(`Invalid dimensions: "${o}". Must be a positive integer. +`),process.exit(1));let u=await st(t,"API key environment variable",No),a=process.env[u];if(a&&a.trim()!==""){process.stdout.write(` +Validating API key via a test embed... +`);try{await $o({apiKey:a.trim(),model:i,dimensions:c}),process.stdout.write(`API key works. +`)}catch(l){process.stdout.write(`API key validation failed: ${l.message} +`),await it(t,"Continue anyway (you can fix the key later)?",!0)||(process.stdout.write(`Aborting setup. +`),process.exit(1))}}else process.stdout.write(` +Environment variable ${u} is not set. Set it in your shell profile (e.g., ~/.zshrc) before using the knowledge base: + export ${u}="sk-..." +Setup will continue \u2014 the key is only needed at query/index time. +`);return ie.writeConfigFile(e,jo({model:i,dimensions:c,apiKeyEnv:u})),process.stdout.write(` +Wrote system config to ${e} +`),{provider:"openai",previouslyStub:r}}async function Vo(t){let e=_e.resolve(process.cwd(),".workflows",".knowledge"),n=_e.join(e,"config.json"),r=_e.join(e,"store.msp"),s=_e.join(e,"metadata.json"),i=qo(e);if(i.fullyInitialised){if(process.stdout.write(` +Project knowledge base already initialised at ${e} +`),!await it(t,"Reinitialise (destroys existing store)?",!1))return process.stdout.write(`Keeping existing project files. +`),{created:!1}}else i.partiallyInitialised?(process.stdout.write(` +Project knowledge base partially initialised at ${e} +`),process.stdout.write(` Missing files will be created. +`)):process.stdout.write(` +Initialising project knowledge base at ${e} +`);we.mkdirSync(e,{recursive:!0}),(!i.configExists||i.fullyInitialised)&&(ie.writeConfigFile(n,Co()),process.stdout.write(` config.json written +`));let o=ie.loadConfig(),c=o.provider||null,u=Number.isInteger(o.dimensions)&&o.dimensions>0?o.dimensions:Uo;if(!i.storeExists||i.fullyInitialised){let a=await Or.createStore(u);await Or.saveStore(a,r),process.stdout.write(` store.msp written (${u} dimensions) +`)}return(!i.metadataExists||i.fullyInitialised)&&(Or.writeMetadata(s,{provider:c||null,model:c&&o.model?o.model:null,dimensions:c?u:null,last_indexed:null,pending:[]}),process.stdout.write(` metadata.json written +`)),{created:!0,provider:c,dimensions:u}}async function gf(t,e){Lo();let n=_e.resolve(process.cwd(),".workflows");we.existsSync(n)||(process.stderr.write(`No .workflows/ directory found. Initialise a workflow project first. +`),process.exit(1));let r=Ro();try{process.stdout.write(` +Knowledge base setup +`),process.stdout.write(`==================== +`);let s=await zo(r);await Vo(r),process.stdout.write(` +Setup complete. +`),s.provider?s.previouslyStub&&process.stdout.write("\nUpgraded from stub mode to a configured provider. Run `knowledge rebuild` to re-index existing artifacts with embeddings.\n"):process.stdout.write(` +Stub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. Semantic search is disabled until you configure a provider. +`)}finally{r.close()}}Wo.exports={cmdSetup:gf,requireTTY:Lo,createPrompter:Ro,ask:st,askYesNo:it,buildSystemConfigOpenAI:jo,buildSystemConfigStub:Fo,buildProjectConfigEmpty:Co,detectSystemConfig:Bo,detectProjectInit:qo,validateApiKey:$o,runSystemConfigStep:zo,runProjectInitStep:Vo,KEYWORD_ONLY_DIMENSIONS:Uo,OPENAI_DEFAULT_MODEL:Po,OPENAI_DEFAULT_DIMENSIONS:ko,OPENAI_DEFAULT_ENV_VAR:No}});var T=require("fs"),B=require("path"),E=Ir(),Yo=bo(),{StubProvider:yf}=Er(),{OpenAIProvider:mf}=un(),Fe=Mr(),Jo=Ko(),kr=["research","discussion","investigation","specification"],wf=T.existsSync(B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):B.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),ct=[1e3,2e3,4e3],_f=5,Nr=1536;function Xo(t){let e=[],n={},r=0;for(;r [options] Commands: index Index a file or all pending artifacts @@ -41,57 +98,56 @@ Options: --phase Filter by phase --topic Filter by topic --limit Limit number of results - --dry-run Preview without making changes`;function ie(){return C.resolve(process.cwd(),".workflows",".knowledge")}function oe(){return C.join(ie(),"store.msp")}function me(){return C.join(ie(),"metadata.json")}function xe(){return C.join(ie(),".lock")}function Hd(t){return new Promise(e=>setTimeout(e,t))}async function nt(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||tt,s;for(let i=0;isetTimeout(e,t))}async function ut(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||ct,s;for(let i=0;iAr(s,o,n,r),{maxAttempts:3,backoff:tt});process.stdout.write(`Indexed ${c} chunks from ${s} -`),await No(n,r,Wd)}async function Ar(t,e,n,r){let s=Kd(e.workUnit),i=C.join(__dirname,"..","chunking",e.phase+".json");if(!v.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(v.readFileSync(i,"utf8")),c=C.resolve(t),u=v.readFileSync(c,"utf8"),a=vo.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let d=ie(),l=oe(),f=me(),p=xe();v.existsSync(d)||v.mkdirSync(d,{recursive:!0});let g,y,h=v.existsSync(l),m=v.existsSync(f);h&&(g=await E.loadStore(l)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=Oo(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||xr;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),T=o.confidence||"medium",D=a.map((A,k)=>{let Ee=String(k+1).padStart(3,"0"),Y={id:`${e.workUnit}-${e.phase}-${e.topic}-${Ee}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:T,source_file:t,timestamp:I};return _&&(Y.embedding=_[k]),Y});return await E.withLock(p,async()=>{h?g=await E.loadStore(l):v.existsSync(l)&&(g=await E.loadStore(l)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,l);let A=v.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function et(t){let{execFileSync:e}=require("child_process");return e("node",[Vd,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function Po(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function Tr(){let t=[],e;try{let n=et(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of Ir){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=et(["resolve",`${r}.${s}.${o}`]).trim();a&&v.existsSync(C.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function ko(t,e,n){let r=Tr(),s=ie(),i=oe();v.existsSync(s)||v.mkdirSync(s,{recursive:!0});let o=null;v.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let d of r){if(o&&await Po(o,d.workUnit,d.phase,d.topic)){a++;continue}try{let l={workUnit:d.workUnit,phase:d.phase,topic:d.topic},f=await nt(()=>Ar(d.file,l,e,n),{maxAttempts:3,backoff:tt});process.stdout.write(`Indexing ${d.file}... ${f} chunks -`),c++,u+=f,v.existsSync(i)&&(o=await E.loadStore(i))}catch(l){await Yd(d.file,l.message),process.stderr.write(`Failed to index ${d.file} after 3 attempts: ${l.message}. Added to pending queue. -`)}}await No(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. -`)}async function Yd(t,e){let n=me(),r=ie(),s=xe();v.existsSync(r)||v.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;v.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function br(t){let e=me(),n=xe();v.existsSync(e)&&await E.withLock(n,async()=>{if(!v.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function No(t,e,n){let r=me();if(!v.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=C.resolve(o.file);if(!v.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. -`),await br(o.file);continue}let u;try{u=Er(o.file)}catch{await br(o.file);continue}try{await nt(()=>Ar(o.file,u,t,e),{maxAttempts:3,backoff:tt}),await br(o.file)}catch{}}}var Jd={high:4,medium:3,"low-medium":2,low:1};function Xd(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function Zd(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Qd(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Jd[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function ef(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. + Current config has no provider configured.`)}async function If(t,e,n,r){if(t.length===0)return tc(e,n,r);let s=t[0],i=B.resolve(s);T.existsSync(i)||(process.stderr.write(`File not found: ${i} +`),process.exit(1));let o=Ur(s),c=await ut(()=>Lr(s,o,n,r),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexed ${c} chunks from ${s} +`),await nc(n,r,_f)}async function Lr(t,e,n,r){let s=bf(e.workUnit),i=B.join(__dirname,"..","chunking",e.phase+".json");if(!T.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(T.readFileSync(i,"utf8")),c=B.resolve(t),u=T.readFileSync(c,"utf8"),a=Yo.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let l=oe(),d=ce(),f=Se(),p=ve();T.existsSync(l)||T.mkdirSync(l,{recursive:!0});let g,y,h=T.existsSync(d),m=T.existsSync(f);h&&(g=await E.loadStore(d)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=Qo(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||Nr;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),v=o.confidence||"medium",D=a.map((A,k)=>{let Te=String(k+1).padStart(3,"0"),Y={id:`${e.workUnit}-${e.phase}-${e.topic}-${Te}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:v,source_file:t,timestamp:I};return _&&(Y.embedding=_[k]),Y});return await E.withLock(p,async()=>{h?g=await E.loadStore(d):T.existsSync(d)&&(g=await E.loadStore(d)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,d);let A=T.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function ot(t){let{execFileSync:e}=require("child_process");return e("node",[wf,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function ec(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function Rr(){let t=[],e;try{let n=ot(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of kr){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=ot(["resolve",`${r}.${s}.${o}`]).trim();a&&T.existsSync(B.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function tc(t,e,n){let r=Rr(),s=oe(),i=ce();T.existsSync(s)||T.mkdirSync(s,{recursive:!0});let o=null;T.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let l of r){if(o&&await ec(o,l.workUnit,l.phase,l.topic)){a++;continue}try{let d={workUnit:l.workUnit,phase:l.phase,topic:l.topic},f=await ut(()=>Lr(l.file,d,e,n),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexing ${l.file}... ${f} chunks +`),c++,u+=f,T.existsSync(i)&&(o=await E.loadStore(i))}catch(d){await xf(l.file,d.message),process.stderr.write(`Failed to index ${l.file} after 3 attempts: ${d.message}. Added to pending queue. +`)}}await nc(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. +`)}async function xf(t,e){let n=Se(),r=oe(),s=ve();T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;T.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function Pr(t){let e=Se(),n=ve();T.existsSync(e)&&await E.withLock(n,async()=>{if(!T.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function nc(t,e,n){let r=Se();if(!T.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=B.resolve(o.file);if(!T.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. +`),await Pr(o.file);continue}let u;try{u=Ur(o.file)}catch{await Pr(o.file);continue}try{await ut(()=>Lr(o.file,u,t,e),{maxAttempts:3,backoff:ct}),await Pr(o.file)}catch{}}}var Ef={high:4,medium:3,"low-medium":2,low:1};function Af(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function vf(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Tf(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Ef[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function Df(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store was indexed with: provider=${r}, model=${s} Current config has no provider configured.`);let o=n.model(),c=n.dimensions();if(r===e.provider&&s===o&&i===c)return{mode:"full",provider:n};throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store: provider=${r}, model=${s}, dimensions=${i} - Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function tf(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] -`),process.exit(1));let s=t,i=e.limit||10,o=oe(),c=me();if(!v.existsSync(o)){process.stdout.write(`[0 results] -`);return}let u=await E.loadStore(o),a="keyword-only",d=null,l=null;v.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=ef(f,n,r);a=p.mode,d=p.provider,a==="keyword-only"?l="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(l="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&d){let T=await nt(()=>d.embed(_),{maxAttempts:3,backoff:tt});I=await E.searchHybrid(u,{term:_,vector:T,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let T of I){let D=m.get(T.id);(!D||T.score>D.score)&&m.set(T.id,T)}}let w=Qd(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];l&&S.push(l),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=Zd(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` + Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function Mf(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] +`),process.exit(1));let s=t,i=e.limit||10,o=ce(),c=Se();if(!T.existsSync(o)){process.stdout.write(`[0 results] +`);return}let u=await E.loadStore(o),a="keyword-only",l=null,d=null;T.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=Df(f,n,r);a=p.mode,l=p.provider,a==="keyword-only"?d="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(d="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&l){let v=await ut(()=>l.embed(_),{maxAttempts:3,backoff:ct});I=await E.searchHybrid(u,{term:_,vector:v,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let v of I){let D=m.get(v.id);(!D||v.score>D.score)&&m.set(v.id,v)}}let w=Tf(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];d&&S.push(d),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=vf(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` `)+` -`)}async function nf(){let t=ie(),e=C.join(t,"config.json"),n=oe();if(!v.existsSync(t)){process.stdout.write(`not-ready -`);return}if(!v.existsSync(e)){process.stdout.write(`not-ready -`);return}if(!v.existsSync(n)){process.stdout.write(`not-ready +`)}async function Of(){let t=oe(),e=B.join(t,"config.json"),n=ce();if(!T.existsSync(t)){process.stdout.write(`not-ready +`);return}if(!T.existsSync(e)){process.stdout.write(`not-ready +`);return}if(!T.existsSync(n)){process.stdout.write(`not-ready `);return}try{await E.loadStore(n)}catch{process.stdout.write(`not-ready `);return}process.stdout.write(`ready -`)}async function rf(){let t=ie(),e=oe(),n=me(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!v.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` +`)}async function Pf(){let t=oe(),e=ce(),n=Se(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!T.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` `)+` -`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let d=(v.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${d} KB`),v.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Ue.loadConfig()}catch{m=null}if(m){let w=Ue.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let l=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),v.existsSync(C.resolve(h.source_file))||l.push(h.source_file));if(l.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${l.length} files`);for(let h of l)r.push(` ${h}`)}try{let h=Tr(),m=[];for(let w of h)await Po(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=Uo(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{et(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` +`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let l=(T.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${l} KB`),T.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Fe.loadConfig()}catch{m=null}if(m){let w=Fe.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let d=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),T.existsSync(B.resolve(h.source_file))||d.push(h.source_file));if(d.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${d.length} files`);for(let h of d)r.push(` ${h}`)}try{let h=Rr(),m=[];for(let w of h)await ec(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=rc(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{ot(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` `)+` -`)}async function sf(t,e,n,r){let s=oe(),i=me(),o=xe();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. +`)}async function kf(t,e,n,r){let s=ce(),i=Se(),o=ve();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. This is non-deterministic \u2014 the rebuilt index will differ from the original. -Type 'rebuild' to confirm: `),await of()!=="rebuild"&&(process.stderr.write(`Aborted. -`),process.exit(1)),Tr().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. +Type 'rebuild' to confirm: `),await Nf()!=="rebuild"&&(process.stderr.write(`Aborted. +`),process.exit(1)),Rr().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. (If you believe this is wrong, check that .workflows/ exists and that work units have items with status "completed".) -`),process.exit(1)),await E.withLock(o,async()=>{v.existsSync(s)&&v.unlinkSync(s),v.existsSync(i)&&v.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||xr,d=await E.createStore(a);await E.saveStore(d,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. -`),await ko(e,n,r)}function of(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function cf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] +`),process.exit(1)),await E.withLock(o,async()=>{T.existsSync(s)&&T.unlinkSync(s),T.existsSync(i)&&T.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||Nr,l=await E.createStore(a);await E.saveStore(l,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. +`),await tc(e,n,r)}function Nf(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function Uf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] `),process.exit(1)),e.topic&&!e.phase&&(process.stderr.write(`Error: --topic requires --phase -`),process.exit(1));let n=oe(),r=xe();if(!v.existsSync(n)){let o=To(e);process.stdout.write(`Removed 0 chunks for ${o} -`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=To(e);process.stdout.write(`Removed ${s} chunks for ${i} -`)}function To(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function Uo(t){try{let e=et(["get",t,"status"]).trim(),n=null;try{n=et(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function uf(t,e,n){let r=oe(),s=xe(),i=n&&n.decay_months!==void 0?n.decay_months:Ue.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled +`),process.exit(1));let n=ce(),r=ve();if(!T.existsSync(n)){let o=Go(e);process.stdout.write(`Removed 0 chunks for ${o} +`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=Go(e);process.stdout.write(`Removed ${s} chunks for ${i} +`)}function Go(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function rc(t){try{let e=ot(["get",t,"status"]).trim(),n=null;try{n=ot(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function Lf(t,e,n){let r=ce(),s=ve(),i=n&&n.decay_months!==void 0?n.decay_months:Fe.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled `);return}(!Number.isInteger(i)||i<0)&&(process.stderr.write(`Invalid decay_months: ${JSON.stringify(i)}. Expected false or a non-negative integer. -`),process.exit(1));let o=i;if(!v.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let d=await E.searchFulltext(c,{term:"",limit:1e5});if(d.length===0)return;let l={};for(let h of d)l[h.work_unit]||(l[h.work_unit]=[]),l[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(l)){let w=Uo(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=Xd(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let T=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:T});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` +`),process.exit(1));let o=i;if(!T.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let l=await E.searchFulltext(c,{term:"",limit:1e5});if(l.length===0)return;let d={};for(let h of l)d[h.work_unit]||(d[h.work_unit]=[]),d[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(d)){let w=rc(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=Af(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let v=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:v});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` `)+` `);return}await E.withLock(s,async()=>{let h=await E.loadStore(r),m=new Set;for(let w of p){let S=`${w.work_unit}|${w.phase}|${w.topic}`;m.has(S)||(m.add(S),await E.removeByIdentity(h,w))}await E.saveStore(h,r)});let y=[];y.push(`Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let h of f)y.push(` \u2022 ${h.workUnit}: ${h.count} chunks (${Array.from(h.phases).join(", ")})`);process.stdout.write(y.join(` `)+` -`)}function af(t){process.stderr.write(`Command "${t}" is not yet implemented. -`),process.exit(1)}async function Ro(){let t=process.argv.slice(2),{positional:e,flags:n}=Do(t),r=e[0],s=e.slice(1),i=Mo(n);r||(process.stderr.write(Ao+` -`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Ue.loadConfig(),c=Ue.resolveProvider(o)),r){case"index":await Gd(s,i,o,c);break;case"query":await tf(s,i,o,c);break;case"check":await nf(s,i,o,c);break;case"status":await rf();break;case"remove":await cf(s,i,o,c);break;case"compact":await uf(s,i,o,c);break;case"rebuild":await sf(s,i,o,c);break;case"setup":af("setup");break;default:process.stderr.write(`Unknown command "${r}". +`)}async function sc(){let t=process.argv.slice(2),{positional:e,flags:n}=Xo(t),r=e[0],s=e.slice(1),i=Zo(n);r||(process.stderr.write(Ho+` +`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Fe.loadConfig(),c=Fe.resolveProvider(o)),r){case"index":await If(s,i,o,c);break;case"query":await Mf(s,i,o,c);break;case"check":await Of(s,i,o,c);break;case"status":await Pf();break;case"remove":await Uf(s,i,o,c);break;case"compact":await Lf(s,i,o,c);break;case"rebuild":await kf(s,i,o,c);break;case"setup":await Jo.cmdSetup(s,i);break;default:process.stderr.write(`Unknown command "${r}". -${Ao} -`),process.exit(1)}}module.exports={parseArgs:Do,buildOptions:Mo,deriveIdentity:Er,resolveProviderState:Oo,withRetry:nt,main:Ro,StubProvider:$d,OpenAIProvider:zd,store:E,chunker:vo,config:Ue,knowledgeDir:ie,storePath:oe,metadataPath:me,lockFilePath:xe,INDEXED_PHASES:Ir,KEYWORD_ONLY_DIMENSIONS:xr};require.main===module&&Ro().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` +${Ho} +`),process.exit(1)}}module.exports={parseArgs:Xo,buildOptions:Zo,deriveIdentity:Ur,resolveProviderState:Qo,withRetry:ut,main:sc,StubProvider:yf,OpenAIProvider:mf,store:E,chunker:Yo,config:Fe,setup:Jo,knowledgeDir:oe,storePath:ce,metadataPath:Se,lockFilePath:ve,INDEXED_PHASES:kr,KEYWORD_ONLY_DIMENSIONS:Nr};require.main===module&&sc().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` `),process.exit(1)}); diff --git a/src/knowledge/config.js b/src/knowledge/config.js index 256239642..deff26229 100644 --- a/src/knowledge/config.js +++ b/src/knowledge/config.js @@ -176,6 +176,31 @@ function resolveProvider(config) { return null; } +/** + * Atomically write a config file. The payload is the full object as it + * should appear on disk (including the top-level `knowledge` wrapper). + * Writes to `.tmp` then renames — matches the manifest/store + * convention so a crash mid-write never leaves a truncated JSON file. + * + * @param {string} filePath Absolute path to write + * @param {object} payload Full JSON object (must include `knowledge` key) + */ +function writeConfigFile(filePath, payload) { + if (!filePath) throw new Error('writeConfigFile: filePath is required'); + if (payload == null || typeof payload !== 'object' || !payload.knowledge) { + throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key'); + } + + const dir = path.dirname(filePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + const tmp = filePath + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\n', 'utf8'); + fs.renameSync(tmp, filePath); +} + module.exports = { DEFAULTS, AVAILABLE_PROVIDERS, @@ -184,4 +209,5 @@ module.exports = { readConfigFile, loadConfig, resolveProvider, + writeConfigFile, }; diff --git a/src/knowledge/index.js b/src/knowledge/index.js index a22001256..3a5814111 100644 --- a/src/knowledge/index.js +++ b/src/knowledge/index.js @@ -13,6 +13,7 @@ const chunker = require('./chunker'); const { StubProvider } = require('./embeddings'); const { OpenAIProvider } = require('./providers/openai'); const config = require('./config'); +const setup = require('./setup'); // --------------------------------------------------------------------------- // Constants @@ -1474,15 +1475,6 @@ async function cmdCompact(_args, options, cfg) { process.stdout.write(out.join('\n') + '\n'); } -// --------------------------------------------------------------------------- -// Not-yet-implemented stub -// --------------------------------------------------------------------------- - -function notYetImplemented(name) { - process.stderr.write(`Command "${name}" is not yet implemented.\n`); - process.exit(1); -} - // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- @@ -1515,7 +1507,7 @@ async function main() { case 'remove': await cmdRemove(commandArgs, options, cfg, provider); break; case 'compact': await cmdCompact(commandArgs, options, cfg, provider); break; case 'rebuild': await cmdRebuild(commandArgs, options, cfg, provider); break; - case 'setup': notYetImplemented('setup'); break; + case 'setup': await setup.cmdSetup(commandArgs, options); break; default: process.stderr.write(`Unknown command "${command}".\n\n${USAGE}\n`); process.exit(1); @@ -1534,6 +1526,7 @@ module.exports = { store, chunker, config, + setup, knowledgeDir, storePath, metadataPath, diff --git a/src/knowledge/setup.js b/src/knowledge/setup.js new file mode 100644 index 000000000..03bd301a0 --- /dev/null +++ b/src/knowledge/setup.js @@ -0,0 +1,402 @@ +// Knowledge base interactive setup wizard. +// +// Human-only. Uses Node's built-in readline for prompts. Aborts cleanly +// on non-TTY invocation (Claude, pipes, CI). Idempotent — running on a +// fully configured project exits with "already set up". Running on a +// partial configuration completes the missing pieces. +// +// Wizard steps: +// 1. System config at ~/.config/workflows/config.json (provider, model, +// dimensions, api_key_env — or stub mode when the user skips). +// 2. Project init at .workflows/.knowledge/ (directory, config.json, +// empty store.msp, metadata.json). +// 3. Initial bulk indexing (wired in Task 2). + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const readline = require('readline'); + +const config = require('./config'); +const store = require('./store'); +const { OpenAIProvider } = require('./providers/openai'); + +const OPENAI_DEFAULT_MODEL = 'text-embedding-3-small'; +const OPENAI_DEFAULT_DIMENSIONS = 1536; +const OPENAI_DEFAULT_ENV_VAR = 'OPENAI_API_KEY'; + +// Used when creating the initial store in stub / keyword-only mode — +// Orama's schema requires a dimension parameter even when docs omit +// the embedding field. Matches KEYWORD_ONLY_DIMENSIONS in index.js. +const KEYWORD_ONLY_DIMENSIONS = 1536; + +// --------------------------------------------------------------------------- +// TTY guard — abort cleanly on non-interactive invocation +// --------------------------------------------------------------------------- + +function requireTTY() { + if (!process.stdin.isTTY) { + process.stderr.write( + 'knowledge setup requires an interactive terminal. ' + + 'Run it directly, not through Claude or a pipe.\n' + ); + process.exit(1); + } +} + +// --------------------------------------------------------------------------- +// Readline helpers +// --------------------------------------------------------------------------- + +function createPrompter() { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + rl.on('SIGINT', () => { + process.stderr.write('\nSetup cancelled.\n'); + rl.close(); + process.exit(130); + }); + + return rl; +} + +function ask(rl, prompt, defaultValue) { + const suffix = defaultValue !== undefined && defaultValue !== null && defaultValue !== '' + ? ` [${defaultValue}]` + : ''; + return new Promise((resolve) => { + rl.question(`${prompt}${suffix}: `, (answer) => { + const trimmed = (answer || '').trim(); + if (trimmed === '' && defaultValue !== undefined && defaultValue !== null) { + resolve(String(defaultValue)); + } else { + resolve(trimmed); + } + }); + }); +} + +async function askYesNo(rl, prompt, defaultYes) { + const hint = defaultYes ? 'Y/n' : 'y/N'; + return new Promise((resolve) => { + rl.question(`${prompt} (${hint}): `, (answer) => { + const trimmed = (answer || '').trim().toLowerCase(); + if (trimmed === '') return resolve(Boolean(defaultYes)); + resolve(trimmed === 'y' || trimmed === 'yes'); + }); + }); +} + +// --------------------------------------------------------------------------- +// Config shape builders — pure, unit-testable +// --------------------------------------------------------------------------- + +function buildSystemConfigOpenAI({ model, dimensions, apiKeyEnv }) { + return { + knowledge: { + provider: 'openai', + model, + dimensions, + api_key_env: apiKeyEnv, + similarity_threshold: config.DEFAULTS.similarity_threshold, + decay_months: config.DEFAULTS.decay_months, + }, + }; +} + +function buildSystemConfigStub() { + return { + knowledge: { + similarity_threshold: config.DEFAULTS.similarity_threshold, + decay_months: config.DEFAULTS.decay_months, + }, + }; +} + +function buildProjectConfigEmpty() { + return { knowledge: {} }; +} + +// --------------------------------------------------------------------------- +// Detection helpers +// --------------------------------------------------------------------------- + +function detectSystemConfig(sysPath) { + if (!fs.existsSync(sysPath)) { + return { exists: false, valid: false, knowledge: null }; + } + try { + const raw = fs.readFileSync(sysPath, 'utf8'); + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== 'object' || !parsed.knowledge || + typeof parsed.knowledge !== 'object' || Array.isArray(parsed.knowledge)) { + return { exists: true, valid: false, knowledge: null, reason: 'missing or invalid "knowledge" key' }; + } + return { exists: true, valid: true, knowledge: parsed.knowledge }; + } catch (e) { + return { exists: true, valid: false, knowledge: null, reason: e.message }; + } +} + +function detectProjectInit(projectDir) { + const configFile = path.join(projectDir, 'config.json'); + const storeFile = path.join(projectDir, 'store.msp'); + const metadataFile = path.join(projectDir, 'metadata.json'); + const dirExists = fs.existsSync(projectDir); + const configExists = fs.existsSync(configFile); + const storeExists = fs.existsSync(storeFile); + const metadataExists = fs.existsSync(metadataFile); + return { + dirExists, + configExists, + storeExists, + metadataExists, + fullyInitialised: configExists && storeExists && metadataExists, + partiallyInitialised: dirExists && !(configExists && storeExists && metadataExists), + }; +} + +// --------------------------------------------------------------------------- +// Test-embed validation — verify the API key actually works +// --------------------------------------------------------------------------- + +async function validateApiKey({ apiKey, model, dimensions }) { + const provider = new OpenAIProvider({ apiKey, model, dimensions }); + const vec = await provider.embed('knowledge base setup test'); + if (!Array.isArray(vec) || vec.length !== dimensions) { + throw new Error( + `Expected a vector of length ${dimensions}, got ${Array.isArray(vec) ? vec.length : typeof vec}` + ); + } + return true; +} + +// --------------------------------------------------------------------------- +// System config step +// --------------------------------------------------------------------------- + +async function runSystemConfigStep(rl) { + const sysPath = config.systemConfigPath(); + const existing = detectSystemConfig(sysPath); + + if (existing.exists && existing.valid) { + process.stdout.write(`\nSystem config already exists at ${sysPath}\n`); + process.stdout.write(' Current settings:\n'); + const k = existing.knowledge; + process.stdout.write(` provider: ${k.provider == null ? '(none — stub mode)' : k.provider}\n`); + if (k.model) process.stdout.write(` model: ${k.model}\n`); + if (k.dimensions) process.stdout.write(` dimensions: ${k.dimensions}\n`); + if (k.api_key_env) process.stdout.write(` api_key_env: ${k.api_key_env}\n`); + process.stdout.write('\n'); + + const reconfigure = await askYesNo(rl, 'Reconfigure system settings?', false); + if (!reconfigure) { + process.stdout.write('Keeping existing system config.\n'); + return { provider: k.provider || null, previouslyStub: !k.provider }; + } + } else if (existing.exists && !existing.valid) { + process.stdout.write(`\nSystem config at ${sysPath} is not valid: ${existing.reason}\n`); + const overwrite = await askYesNo(rl, 'Overwrite it?', true); + if (!overwrite) { + process.stdout.write('Aborting setup so you can fix the file manually.\n'); + process.exit(1); + } + } else { + process.stdout.write(`\nNo system config found at ${sysPath}. Creating a new one.\n`); + } + + // Detect stub-to-full upgrade scenario (used after provider choice). + const previouslyStub = existing.exists && existing.valid && !existing.knowledge.provider; + + // Prompt for provider. + process.stdout.write('\nEmbedding provider:\n'); + process.stdout.write(' openai — OpenAI embeddings API (requires an API key)\n'); + process.stdout.write(' skip — Stub mode (keyword-only search, no embeddings)\n\n'); + + let providerChoice; + while (true) { + providerChoice = (await ask(rl, 'Provider (openai / skip)', 'openai')).toLowerCase(); + if (providerChoice === 'openai' || providerChoice === 'skip') break; + process.stdout.write(`Unknown choice "${providerChoice}". Enter "openai" or "skip".\n`); + } + + if (providerChoice === 'skip') { + config.writeConfigFile(sysPath, buildSystemConfigStub()); + process.stdout.write(`\nWrote stub-mode system config to ${sysPath}\n`); + process.stdout.write( + 'Stub mode uses keyword-only (BM25) search. Semantic search is disabled. ' + + 'Run `knowledge setup` again later to configure a provider.\n' + ); + return { provider: null, previouslyStub }; + } + + // openai path. + const model = await ask(rl, 'Embedding model', OPENAI_DEFAULT_MODEL); + const dimsRaw = await ask(rl, 'Vector dimensions', String(OPENAI_DEFAULT_DIMENSIONS)); + const dimensions = parseInt(dimsRaw, 10); + if (!Number.isInteger(dimensions) || dimensions <= 0) { + process.stderr.write(`Invalid dimensions: "${dimsRaw}". Must be a positive integer.\n`); + process.exit(1); + } + const apiKeyEnv = await ask(rl, 'API key environment variable', OPENAI_DEFAULT_ENV_VAR); + + // Validate env var (non-blocking — warn only). + const apiKey = process.env[apiKeyEnv]; + if (apiKey && apiKey.trim() !== '') { + process.stdout.write(`\nValidating API key via a test embed...\n`); + try { + await validateApiKey({ apiKey: apiKey.trim(), model, dimensions }); + process.stdout.write('API key works.\n'); + } catch (err) { + process.stdout.write(`API key validation failed: ${err.message}\n`); + const cont = await askYesNo(rl, 'Continue anyway (you can fix the key later)?', true); + if (!cont) { + process.stdout.write('Aborting setup.\n'); + process.exit(1); + } + } + } else { + process.stdout.write( + `\nEnvironment variable ${apiKeyEnv} is not set. ` + + `Set it in your shell profile (e.g., ~/.zshrc) before using the knowledge base:\n` + + ` export ${apiKeyEnv}="sk-..."\n` + + `Setup will continue — the key is only needed at query/index time.\n` + ); + } + + config.writeConfigFile(sysPath, buildSystemConfigOpenAI({ model, dimensions, apiKeyEnv })); + process.stdout.write(`\nWrote system config to ${sysPath}\n`); + + return { provider: 'openai', previouslyStub }; +} + +// --------------------------------------------------------------------------- +// Project init step +// --------------------------------------------------------------------------- + +async function runProjectInitStep(rl) { + const projectDir = path.resolve(process.cwd(), '.workflows', '.knowledge'); + const projectConfigFile = path.join(projectDir, 'config.json'); + const storeFile = path.join(projectDir, 'store.msp'); + const metadataFile = path.join(projectDir, 'metadata.json'); + + const detected = detectProjectInit(projectDir); + + if (detected.fullyInitialised) { + process.stdout.write(`\nProject knowledge base already initialised at ${projectDir}\n`); + const reinit = await askYesNo(rl, 'Reinitialise (destroys existing store)?', false); + if (!reinit) { + process.stdout.write('Keeping existing project files.\n'); + return { created: false }; + } + } else if (detected.partiallyInitialised) { + process.stdout.write(`\nProject knowledge base partially initialised at ${projectDir}\n`); + process.stdout.write(' Missing files will be created.\n'); + } else { + process.stdout.write(`\nInitialising project knowledge base at ${projectDir}\n`); + } + + // mkdir -p equivalent — safe to run repeatedly. + fs.mkdirSync(projectDir, { recursive: true }); + + // Write project config (empty — inherits from system). + if (!detected.configExists || detected.fullyInitialised /* reinit path */) { + config.writeConfigFile(projectConfigFile, buildProjectConfigEmpty()); + process.stdout.write(` config.json written\n`); + } + + // Load merged config to resolve dimensions for the store. + const cfg = config.loadConfig(); + const provider = cfg.provider || null; + const dims = Number.isInteger(cfg.dimensions) && cfg.dimensions > 0 + ? cfg.dimensions + : KEYWORD_ONLY_DIMENSIONS; + + // Create empty store and save. + if (!detected.storeExists || detected.fullyInitialised) { + const db = await store.createStore(dims); + await store.saveStore(db, storeFile); + process.stdout.write(` store.msp written (${dims} dimensions)\n`); + } + + // Write initial metadata. + if (!detected.metadataExists || detected.fullyInitialised) { + store.writeMetadata(metadataFile, { + provider: provider || null, + model: provider && cfg.model ? cfg.model : null, + dimensions: provider ? dims : null, + last_indexed: null, + pending: [], + }); + process.stdout.write(` metadata.json written\n`); + } + + return { created: true, provider, dimensions: dims }; +} + +// --------------------------------------------------------------------------- +// Orchestrator +// --------------------------------------------------------------------------- + +async function cmdSetup(args, options) { + requireTTY(); + + // Guard: .workflows/ must exist. + const workflowsDir = path.resolve(process.cwd(), '.workflows'); + if (!fs.existsSync(workflowsDir)) { + process.stderr.write( + 'No .workflows/ directory found. Initialise a workflow project first.\n' + ); + process.exit(1); + } + + const rl = createPrompter(); + + try { + process.stdout.write('\nKnowledge base setup\n'); + process.stdout.write('====================\n'); + + const sysResult = await runSystemConfigStep(rl); + await runProjectInitStep(rl); + + process.stdout.write('\nSetup complete.\n'); + + if (!sysResult.provider) { + process.stdout.write( + '\nStub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. ' + + 'Semantic search is disabled until you configure a provider.\n' + ); + } else if (sysResult.previouslyStub) { + process.stdout.write( + '\nUpgraded from stub mode to a configured provider. ' + + 'Run `knowledge rebuild` to re-index existing artifacts with embeddings.\n' + ); + } + } finally { + rl.close(); + } +} + +module.exports = { + cmdSetup, + requireTTY, + createPrompter, + ask, + askYesNo, + buildSystemConfigOpenAI, + buildSystemConfigStub, + buildProjectConfigEmpty, + detectSystemConfig, + detectProjectInit, + validateApiKey, + runSystemConfigStep, + runProjectInitStep, + KEYWORD_ONLY_DIMENSIONS, + OPENAI_DEFAULT_MODEL, + OPENAI_DEFAULT_DIMENSIONS, + OPENAI_DEFAULT_ENV_VAR, +}; diff --git a/tests/scripts/test-knowledge-cli.sh b/tests/scripts/test-knowledge-cli.sh index e3ffd4a59..258e20f39 100644 --- a/tests/scripts/test-knowledge-cli.sh +++ b/tests/scripts/test-knowledge-cli.sh @@ -152,15 +152,13 @@ node "$BUNDLE" foobar 2>/dev/null || exit_code=$? assert_eq "exits with code 1" "1" "$exit_code" assert_eq "mentions unknown command" "true" "$(echo "$output" | grep -q 'Unknown command' && echo true || echo false)" -# --- Test 3: Not-yet-implemented commands exit 1 --- -echo "Test 3: Not-yet-implemented commands" -for cmd in setup; do - exit_code=0 - output=$(node "$BUNDLE" "$cmd" 2>&1 || true) - node "$BUNDLE" "$cmd" 2>/dev/null || exit_code=$? - assert_eq "$cmd exits with code 1" "1" "$exit_code" - assert_eq "$cmd mentions not yet implemented" "true" "$(echo "$output" | grep -q 'not yet implemented' && echo true || echo false)" -done +# --- Test 3: setup aborts when stdin is not a TTY --- +echo "Test 3: setup requires an interactive terminal" +exit_code=0 +output=$(echo '' | node "$BUNDLE" setup 2>&1 || true) +echo '' | node "$BUNDLE" setup 2>/dev/null || exit_code=$? +assert_eq "setup exits non-zero without a TTY" "1" "$exit_code" +assert_eq "setup mentions interactive terminal" "true" "$(echo "$output" | grep -q 'interactive terminal' && echo true || echo false)" # --- Test 4: Known Phase 3 commands dispatch without unknown-command error --- echo "Test 4: Phase 3 commands dispatch correctly" diff --git a/tests/scripts/test-knowledge-config.cjs b/tests/scripts/test-knowledge-config.cjs index 2e3214ba4..9a7734bc6 100644 --- a/tests/scripts/test-knowledge-config.cjs +++ b/tests/scripts/test-knowledge-config.cjs @@ -6,8 +6,15 @@ const fs = require('fs'); const path = require('path'); const os = require('os'); -const { loadConfig, readConfigFile, resolveProvider, DEFAULTS } = require('../../src/knowledge/config'); +const { loadConfig, readConfigFile, resolveProvider, writeConfigFile, DEFAULTS } = require('../../src/knowledge/config'); const { StubProvider } = require('../../src/knowledge/embeddings'); +const { + buildSystemConfigOpenAI, + buildSystemConfigStub, + buildProjectConfigEmpty, + detectSystemConfig, + detectProjectInit, +} = require('../../src/knowledge/setup'); let tmpDir; @@ -231,3 +238,192 @@ describe('resolveProvider', () => { assert.throws(() => resolveProvider(undefined), /config is required/); }); }); + +// --------------------------------------------------------------------------- +// writeConfigFile +// --------------------------------------------------------------------------- + +describe('writeConfigFile', () => { + beforeEach(setup); + afterEach(teardown); + + it('writes a well-formed JSON file with the knowledge wrapper', () => { + const filePath = path.join(tmpDir, 'nested', 'config.json'); + writeConfigFile(filePath, { knowledge: { provider: 'openai', dimensions: 1536 } }); + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + assert.deepStrictEqual(parsed, { knowledge: { provider: 'openai', dimensions: 1536 } }); + }); + + it('creates parent directories when they do not exist', () => { + const filePath = path.join(tmpDir, 'a', 'b', 'c', 'config.json'); + writeConfigFile(filePath, { knowledge: {} }); + assert.ok(fs.existsSync(filePath)); + }); + + it('uses atomic write (no .tmp left behind on success)', () => { + const filePath = path.join(tmpDir, 'config.json'); + writeConfigFile(filePath, { knowledge: {} }); + assert.ok(fs.existsSync(filePath)); + assert.ok(!fs.existsSync(filePath + '.tmp')); + }); + + it('rejects payloads missing the knowledge wrapper', () => { + const filePath = path.join(tmpDir, 'config.json'); + assert.throws(() => writeConfigFile(filePath, { provider: 'openai' }), /knowledge/); + }); + + it('overwrites an existing file', () => { + const filePath = path.join(tmpDir, 'config.json'); + writeConfigFile(filePath, { knowledge: { provider: 'stub' } }); + writeConfigFile(filePath, { knowledge: { provider: 'openai' } }); + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + assert.strictEqual(parsed.knowledge.provider, 'openai'); + }); +}); + +// --------------------------------------------------------------------------- +// Setup config builders +// --------------------------------------------------------------------------- + +describe('buildSystemConfigOpenAI', () => { + it('produces a config with provider, model, dimensions, api_key_env, and defaults', () => { + const cfg = buildSystemConfigOpenAI({ + model: 'text-embedding-3-small', + dimensions: 1536, + apiKeyEnv: 'OPENAI_API_KEY', + }); + assert.strictEqual(cfg.knowledge.provider, 'openai'); + assert.strictEqual(cfg.knowledge.model, 'text-embedding-3-small'); + assert.strictEqual(cfg.knowledge.dimensions, 1536); + assert.strictEqual(cfg.knowledge.api_key_env, 'OPENAI_API_KEY'); + assert.strictEqual(cfg.knowledge.similarity_threshold, DEFAULTS.similarity_threshold); + assert.strictEqual(cfg.knowledge.decay_months, DEFAULTS.decay_months); + }); +}); + +describe('buildSystemConfigStub', () => { + it('produces a stub-mode config with no provider field', () => { + const cfg = buildSystemConfigStub(); + assert.strictEqual(cfg.knowledge.provider, undefined); + assert.strictEqual(cfg.knowledge.model, undefined); + assert.strictEqual(cfg.knowledge.dimensions, undefined); + assert.strictEqual(cfg.knowledge.api_key_env, undefined); + assert.strictEqual(cfg.knowledge.similarity_threshold, DEFAULTS.similarity_threshold); + assert.strictEqual(cfg.knowledge.decay_months, DEFAULTS.decay_months); + }); + + it('round-trips through loadConfig as keyword-only (no provider)', () => { + // Writing the stub config to disk then loading it should produce a + // config where resolveProvider returns null — the keyword-only path. + const sysPath = path.join(tmpDir, 'sys.json'); + writeConfigFile(sysPath, buildSystemConfigStub()); + const cfg = loadConfig({ + systemPath: sysPath, + projectPath: path.join(tmpDir, 'proj.json'), + }); + assert.strictEqual(cfg.provider, undefined); + assert.strictEqual(resolveProvider(cfg), null); + }); +}); + +describe('buildProjectConfigEmpty', () => { + it('produces { knowledge: {} } for inheritance from system', () => { + const cfg = buildProjectConfigEmpty(); + assert.deepStrictEqual(cfg, { knowledge: {} }); + }); +}); + +// --------------------------------------------------------------------------- +// Detection helpers +// --------------------------------------------------------------------------- + +describe('detectSystemConfig', () => { + beforeEach(setup); + afterEach(teardown); + + it('reports exists=false when the file is missing', () => { + const result = detectSystemConfig(path.join(tmpDir, 'missing.json')); + assert.strictEqual(result.exists, false); + assert.strictEqual(result.valid, false); + assert.strictEqual(result.knowledge, null); + }); + + it('reports exists=true, valid=true for a well-formed config', () => { + const filePath = path.join(tmpDir, 'sys.json'); + writeJSON(filePath, { knowledge: { provider: 'openai' } }); + const result = detectSystemConfig(filePath); + assert.strictEqual(result.exists, true); + assert.strictEqual(result.valid, true); + assert.deepStrictEqual(result.knowledge, { provider: 'openai' }); + }); + + it('reports exists=true, valid=false for invalid JSON', () => { + const filePath = path.join(tmpDir, 'bad.json'); + fs.writeFileSync(filePath, '{not json', 'utf8'); + const result = detectSystemConfig(filePath); + assert.strictEqual(result.exists, true); + assert.strictEqual(result.valid, false); + assert.ok(result.reason); + }); + + it('reports exists=true, valid=false for missing knowledge wrapper', () => { + const filePath = path.join(tmpDir, 'nowrap.json'); + writeJSON(filePath, { provider: 'openai' }); + const result = detectSystemConfig(filePath); + assert.strictEqual(result.exists, true); + assert.strictEqual(result.valid, false); + }); + + it('reports exists=true, valid=false when knowledge is an array', () => { + const filePath = path.join(tmpDir, 'arr.json'); + writeJSON(filePath, { knowledge: [1, 2, 3] }); + const result = detectSystemConfig(filePath); + assert.strictEqual(result.valid, false); + }); +}); + +describe('detectProjectInit', () => { + beforeEach(setup); + afterEach(teardown); + + it('reports all-absent when the directory does not exist', () => { + const result = detectProjectInit(path.join(tmpDir, '.workflows', '.knowledge')); + assert.strictEqual(result.dirExists, false); + assert.strictEqual(result.configExists, false); + assert.strictEqual(result.storeExists, false); + assert.strictEqual(result.metadataExists, false); + assert.strictEqual(result.fullyInitialised, false); + assert.strictEqual(result.partiallyInitialised, false); + }); + + it('reports partiallyInitialised when the directory exists but files are missing', () => { + const dir = path.join(tmpDir, '.workflows', '.knowledge'); + fs.mkdirSync(dir, { recursive: true }); + const result = detectProjectInit(dir); + assert.strictEqual(result.dirExists, true); + assert.strictEqual(result.fullyInitialised, false); + assert.strictEqual(result.partiallyInitialised, true); + }); + + it('reports partiallyInitialised when only some files are present', () => { + const dir = path.join(tmpDir, '.workflows', '.knowledge'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'config.json'), '{}', 'utf8'); + const result = detectProjectInit(dir); + assert.strictEqual(result.configExists, true); + assert.strictEqual(result.storeExists, false); + assert.strictEqual(result.fullyInitialised, false); + assert.strictEqual(result.partiallyInitialised, true); + }); + + it('reports fullyInitialised when all three files exist', () => { + const dir = path.join(tmpDir, '.workflows', '.knowledge'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'config.json'), '{}', 'utf8'); + fs.writeFileSync(path.join(dir, 'store.msp'), '', 'utf8'); + fs.writeFileSync(path.join(dir, 'metadata.json'), '{}', 'utf8'); + const result = detectProjectInit(dir); + assert.strictEqual(result.fullyInitialised, true); + assert.strictEqual(result.partiallyInitialised, false); + }); +}); From 3275448ea5300098cc2c4f15501b9c44d8451622 Mon Sep 17 00:00:00 2001 From: Lee Overy Date: Sun, 19 Apr 2026 17:45:01 +0100 Subject: [PATCH 2/5] =?UTF-8?q?feat(knowledge):=20setup=20wizard=20?= =?UTF-8?q?=E2=80=94=20initial=20indexing=20+=20stub-to-full=20upgrade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wire the existing bulk index as the wizard's final step. cmdIndexBulk is dependency-injected into cmdSetup to avoid a circular require — esbuild's CJS wrapping breaks `require.main === module` on the entry when two modules require each other. Readline closes before indexing so a non-interactive long-running embed pass doesn't leave a lingering TTY handle. Indexing failures don't abort the setup — the project is initialised and the pending queue retains partial state. On stub-to-full upgrade, the wizard surfaces the rebuild instruction rather than auto-rebuilding. SKILL.md loses the "not yet implemented" wording. Co-Authored-By: Claude Opus 4.7 (1M context) --- .tick/tasks.jsonl | 4 +- skills/workflow-knowledge/SKILL.md | 2 +- .../workflow-knowledge/scripts/knowledge.cjs | 126 +++++++++--------- src/knowledge/index.js | 3 +- src/knowledge/setup.js | 59 +++++--- tests/scripts/test-knowledge-cli.sh | 6 + 6 files changed, 120 insertions(+), 80 deletions(-) diff --git a/.tick/tasks.jsonl b/.tick/tasks.jsonl index c3c7e7945..79e436d62 100644 --- a/.tick/tasks.jsonl +++ b/.tick/tasks.jsonl @@ -29,9 +29,9 @@ {"id":"tick-09d9ca","title":"Knowledge SKILL.md + Two-Step Retrieval Documentation","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-1"],"description":"Problem: The knowledge base CLI exists (Phases 1-4) and is wired into skills (Phase 5), but Claude has no documentation explaining what it is, how to use it, or when to query it. Without Layer 1, Layers 2 and 3 have nothing to reference for API details.\n\nSolution: Create the knowledge skill file (SKILL.md) that serves as the API documentation layer — what commands exist, how to call them, what the output looks like, and how the two-step retrieval pattern works.\n\nOutcome: A comprehensive skill file that any processing skill can reference for knowledge base API details, enabling Claude to query the knowledge base correctly.\n\nDo:\n- Create skills/workflow-knowledge/SKILL.md following the project's skill file conventions (see CLAUDE.md Skill File Structure section).\n- This is a model-invocable skill, not user-invocable. It is loaded by reference from Layer 2 usage references (Task 6-2). It is NOT directly invoked by users.\n- Content sections:\n\n PURPOSE:\n - What the knowledge base is: a RAG system storing all workflow artifacts at full fidelity for semantic search\n - Why it exists: cross-work-unit and intra-work-unit context surfacing\n - What it indexes: research, discussion, investigation, specification (not planning, implementation, review)\n\n QUERY COMMAND:\n - Single query: node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003csearch_term\u003e [flags]\n - Batch query: node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003cterm1\u003e \u003cterm2\u003e [termN...] [flags]\n Multiple positional arguments run separate searches, merge results, deduplicate by chunk ID (highest score kept), apply --limit to merged set. Efficient: one store load, multiple searches.\n - Flags: --work-type, --phase, --work-unit (re-ranking hint, not filter), --limit\n - Search modes: hybrid (default when provider configured), keyword-only (when no provider)\n - Query construction guidance: use natural language, not topic slugs. Descriptive queries produce better semantic matching. Multiple queries from different angles are encouraged.\n - Example queries showing good vs poor query construction\n\n OUTPUT FORMAT:\n - Document the exact format (from design doc lines 580-603):\n [N results]\n [phase | work_unit/topic | confidence | YYYY-MM-DD]\n chunk content verbatim\n Source: source_file_path\n - Result count header, provenance line, verbatim content, source path\n - Empty results: [0 results]\n - Stub mode note when applicable: [keyword-only mode — configure embedding provider for semantic search]\n\n CONFIDENCE TIERS:\n - Explain what confidence means and how to weigh it:\n specification (high) — validated decisions, what was decided and why\n investigation (medium) — diagnostic knowledge, tied to specific symptoms\n discussion (low-medium) — conversational, may contain corrected assumptions\n research (low) — exploratory, may contain dead ends and rejected paths\n - Low confidence is not low value — research that rejected an approach prevents re-exploring dead ends\n\n TWO-STEP RETRIEVAL PATTERN:\n - Step 1: query returns chunks with provenance (lightweight, lands in context)\n - Step 2: if a chunk looks relevant, read the actual source file (source_file in metadata) for full detail\n - This keeps context lean — surface-level awareness, deep dive on demand\n - Claude should NOT read source files for every result, only when a chunk warrants deeper investigation\n\n WHAT NOT TO DO:\n - Do not dump large result sets into context speculatively\n - Do not query using topic slugs as search terms (poor semantic signal)\n - Do not query during specification phase (explicitly excluded — spec turns decisions into a golden doc, cross-cutting concerns merge at planning time)\n - Do not prepend metadata to stored content (already in enum fields)\n\nAcceptance Criteria:\n- SKILL.md exists at skills/workflow-knowledge/SKILL.md\n- Documents both single and batch query invocation forms\n- Documents all query flags and their behaviour\n- Documents the exact output format with examples\n- Documents confidence tiers with guidance on how to weigh them\n- Documents the two-step retrieval pattern (query -\u003e read source file on demand)\n- Documents what NOT to do (spec exclusion, slug queries, speculative dumps)\n- Follows project skill file conventions from CLAUDE.md\n- Can be loaded by reference from Layer 2 files (Task 6-2)\n\nTests:\n- No automated tests — documentation task. Validation is manual:\n - Read the SKILL.md and verify it provides enough information to correctly construct and interpret knowledge queries\n - Verify it follows the project's skill file structure conventions\n\nEdge Cases:\n- The SKILL.md must describe BOTH hybrid and keyword-only modes without making keyword-only feel broken — it is a supported degraded mode\n- Must not duplicate the CLI help text verbatim — this is higher-level guidance about when and why, not just how\n- Must explain that --work-unit is a re-ranking hint, not a filter — this is a common misunderstanding that would produce wrong queries if not clear\n- Batch query section must explain deduplication and merged limit behaviour\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 1 description), Retrieved Context Format (lines 576-605, exact output format), Confidence Tiers (lines 514-525), Two-step retrieval pattern (lines 735-737), Query construction (line 737), Batch query (line 602-603, merged and deduplicated), Specification excluded from automatic retrieval (line 560)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T18:59:31Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:01:08Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:22:30Z","updated":"2026-04-18T19:01:08Z","closed":"2026-04-18T19:01:08Z"} {"id":"tick-c5a9f0","title":"Per-Phase Usage References + Contextual Query at Phase Start","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-2"],"description":"Problem: Layer 1 (SKILL.md) documents the API, but Claude needs phase-specific guidance on WHEN to query and WHY — the trigger heuristics contextualised for each phase's work. Without Layer 2, Claude has the capability but not the judgment to use it effectively. Additionally, Claude needs explicit guidance on how to handle query failures — the design doc mandates pausing the workflow, not silently proceeding.\n\nSolution: Create usage reference files loaded early in processing skills that describe when and why to query during each specific phase, how to handle failures, plus the contextual query at phase start for research, discussion, and investigation.\n\nOutcome: Every processing skill loads phase-appropriate querying guidance early in its flow, the three early phases perform a contextual query at phase start, and query failures are handled by pausing with user options rather than silently skipping.\n\nDo:\n\nUSAGE REFERENCE FILES (Layer 2):\n- Create reference files — either one shared file or per-phase files, depending on how much the guidance differs between phases. The design doc (line 720) says: may be shared if guidance is generic enough, or local per phase if each needs different emphasis.\n- Recommended approach: one shared reference at skills/workflow-shared/references/knowledge-usage.md that covers the common trigger heuristics, with phase-specific notes where needed. This avoids maintaining 8 near-identical files.\n- Content:\n - Load the knowledge SKILL.md (Layer 1, Task 6-1) by reference for API details\n - Trigger heuristics — when to query (from design doc lines 551-557):\n 1. At topic boundaries — conversation edges toward adjacent territory\n 2. Upstream/downstream dependencies — current topic may affect or be affected by other work\n 3. Unfamiliar territory — not sure whether something was explored before\n 4. User prompts — user asks to check for prior context\n - Encourage proactive querying — under-querying is the bigger risk (design doc line 1003)\n - Multiple queries from different angles are expected and encouraged\n - Query construction: use natural language derived from what is currently being discussed, not topic names\n - Two-step retrieval reminder: query first (lightweight), read source file only when a chunk warrants investigation\n\nQUERY FAILURE HANDLING (from design doc lines 767-776):\n- This is skill-level behavior, not CLI behavior. The CLI retries 3 times and then exits with a non-zero code and error message (Task 4-4). The SKILL must handle what happens next:\n 1. If knowledge query fails (non-zero exit): PAUSE the workflow. Do not silently proceed without context.\n 2. Present the error clearly: what failed, likely causes (API key expired, network down, store corrupted).\n 3. Offer the user two options: fix the issue and retry, or explicitly choose to proceed without knowledge context.\n 4. If the user chooses to proceed: continue the phase but note that knowledge retrieval was skipped. This note should be visible in the output so the user knows context may be missing.\n- The design doc is emphatic: the value of the knowledge base is too high to silently skip (line 776).\n- This failure handling guidance goes in the usage reference (Layer 2) so it applies to all phases that load it.\n\n- Phase-specific notes within the shared reference (or in separate files if warranted):\n - Research: query at start + throughout. Early phase, high chance of overlap with prior work.\n - Discussion: query at start + throughout. Decisions being made that may relate to prior decisions.\n - Investigation: query at start + throughout. Symptoms and root causes may have been seen before.\n - Specification: EXCLUDED from automatic retrieval. Explicit note: do not query during spec authoring. Cross-cutting concerns merge at planning time, not spec time (design doc line 560).\n - Scoping: query throughout. Quick-fix scoping benefits from knowing if the issue was discussed elsewhere.\n - Planning: query throughout, especially for cross-cutting context. The explicit cross-cutting query is handled separately (Task 6-3).\n - Implementation: query when hitting unfamiliar territory or when a task touches areas covered by prior work.\n - Review: query to verify decisions against prior context.\n\nCONTEXTUAL QUERY AT PHASE START:\n- Add to the processing skills for research, discussion, and investigation: at the beginning of the phase (after loading references, before the first substantive step), construct a natural language query from available context and search the knowledge base.\n- Available context for query construction (from design doc line 549): topic description, bootstrap answers, handoff context, problem statement — whatever is available at that point.\n- NOT the topic slug. The query must be descriptive: not auth-flow but user authentication flow using OAuth2 with PKCE for mobile and web clients.\n- Returns a small, focused result set. Zero cost if nothing comes back. High value when it catches prior work.\n- This is a single query, not a dump. If results come back, Claude reads them and proceeds with that context. If nothing comes back, proceed as normal.\n- Specification is EXCLUDED — no contextual query at spec phase start.\n\nLOAD DIRECTIVES IN PROCESSING SKILLS:\n- Add a load directive for the usage reference early in each processing skill (alongside where case conventions are loaded). The exact insertion point varies per skill — read each to find the right place.\n- Processing skills that need this:\n skills/workflow-research-process/SKILL.md\n skills/workflow-discussion-process/SKILL.md\n skills/workflow-investigation-process/SKILL.md\n skills/workflow-scoping-process/SKILL.md\n skills/workflow-planning-process/SKILL.md\n skills/workflow-implementation-process/SKILL.md\n skills/workflow-review-process/SKILL.md\n- Specification process does NOT load the usage reference (excluded from automatic retrieval).\n\nALLOWED-TOOLS FOR REMAINING PROCESSING SKILLS:\n- Add Bash(node .claude/skills/workflow-knowledge/scripts/knowledge.cjs) to:\n skills/workflow-planning-process/SKILL.md\n skills/workflow-implementation-process/SKILL.md\n skills/workflow-review-process/SKILL.md\n- These 3 were deferred from Phase 5 — now they need it for autonomous querying.\n- Scoping process already has it from Phase 5 Task 5-2. Research, discussion, investigation, specification process already have it from Task 5-2.\n\nAcceptance Criteria:\n- Usage reference file(s) exist with trigger heuristics and phase-specific guidance\n- Usage reference loads Layer 1 (SKILL.md) by reference for API details\n- Query failure handling documented: pause workflow, present error, offer user choice to proceed or fix\n- All 7 processing skills (except specification) load the usage reference early in their flow\n- Specification process does NOT load the usage reference\n- Research, discussion, and investigation processing skills perform a contextual query at phase start\n- Contextual query uses descriptive natural language, not topic slugs\n- allowed-tools added to planning, implementation, and review processing skills\n- Trigger heuristics match the design doc (topic boundaries, dependencies, unfamiliar territory, user prompts)\n\nTests:\n- No automated tests — skill file editing task. Validation is manual:\n - Start a discussion in a test project with existing indexed knowledge -\u003e verify contextual query runs and surfaces relevant prior work\n - Start a specification -\u003e verify no contextual query runs\n - Simulate query failure -\u003e verify workflow pauses with user options (not silent skip)\n - Verify all processing skills load the usage reference\n\nEdge Cases:\n- Contextual query with no prior knowledge indexed — returns [0 results], phase proceeds normally with no delay or noise\n- Phase start with very little context available (e.g., just a topic name) — construct the best query possible from what is available. A poor query that returns nothing is fine. The design doc accepts zero cost if nothing comes back.\n- Query failure during contextual query at phase start — same failure handling applies (pause, present, offer choice). The contextual query is not exempt from failure handling.\n- Shared vs per-phase reference: if a shared reference becomes unwieldy with too many phase-specific notes, split into per-phase files. Start shared, split if needed.\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 2 description), Autonomous querying trigger heuristics (lines 551-557), Contextual query at phase start (line 549), Specification excluded (line 560), Query Failures section (lines 767-776, pause workflow, present error, user choice), Autonomous query guardrails review finding #16 (line 1002)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T19:01:23Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:10:11Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:23:15Z","updated":"2026-04-18T19:10:11Z","closed":"2026-04-18T19:10:11Z"} {"id":"tick-2841d6","title":"Inline Callouts + Planning Entry Cross-Cutting Query","status":"done","priority":2,"type":"task","refs":["knowledge-base-6-3"],"description":"Problem: Layer 2 provides general guidance loaded once at the start of a phase, but Claude can lose awareness of the knowledge base as a conversation develops. Layer 3 addresses this with targeted nudges at specific moments where querying is most valuable. Additionally, the planning entry skill has an existing manual approach for cross-cutting context that should be replaced with a targeted semantic query.\n\nSolution: Add inline callouts at pertinent points in processing skills and replace the planning entry cross-cutting context approach with a knowledge base query.\n\nOutcome: Claude gets timely reminders to check the knowledge base at high-value moments, and planning entry uses semantic search instead of manually reading every cross-cutting spec.\n\nDo:\n\nINLINE CALLOUTS (Layer 3):\n- Add brief reminders within the step flow of processing skills at moments where the knowledge base is most valuable. These are nudges, not full reference loads — same pattern as existing callouts for review agents and commit reminders (design doc line 722).\n- Format: a short inline note like: Consider querying the knowledge base — this subtopic may have been explored in prior work. Or: If this constraint seems familiar, check the knowledge base for prior decisions.\n- Placement is judgment-based — read each processing skill and identify moments where:\n - A complex subtopic is being explored\n - A decision is being made that could conflict with prior work\n - An assumption is being introduced that may have been validated or rejected before\n - The conversation moves to adjacent territory\n- Processing skills to add callouts to (all except specification):\n skills/workflow-research-process/SKILL.md — when exploring new directions, before concluding\n skills/workflow-discussion-process/SKILL.md — when discussing options, before deciding\n skills/workflow-investigation-process/SKILL.md — when analysing root causes\n skills/workflow-scoping-process/SKILL.md — when scoping constraints\n skills/workflow-planning-process/SKILL.md — when designing phases/tasks that touch other areas\n skills/workflow-implementation-process/SKILL.md — when hitting unfamiliar code areas\n skills/workflow-review-process/SKILL.md — when verifying decisions against original intent\n- These are 1-2 line callouts embedded at specific step boundaries, NOT new steps or reference loads. They should feel natural, not interruptive.\n- Do NOT add callouts to the specification process — specification is excluded from automatic retrieval.\n\nPLANNING ENTRY CROSS-CUTTING QUERY:\n- This replaces existing functionality in skills/workflow-planning-entry/references/cross-cutting-context.md (design doc line 562).\n- The current approach: reads every cross-cutting specification and manually assesses relevance to the current topic. This is expensive (loads all cross-cutting specs into context) and keyword-dependent (misses semantic connections).\n- The replacement: a targeted semantic query filtered to work_type: cross-cutting.\n node .claude/skills/workflow-knowledge/scripts/knowledge.cjs query \u003ctopic_description\u003e --work-type cross-cutting --limit 10\n- The query term should be constructed from the current topic's specification summary or description — not the topic name.\n- Results are cross-cutting specs that are semantically relevant to the current plan. Claude reads the results, identifies applicable cross-cutting decisions, and incorporates them into the planning context.\n- This is a deterministic step replacing existing functionality, not a speculative search (design doc line 726).\n- Update or replace cross-cutting-context.md to use the knowledge query instead of manual spec reading.\n- Ensure skills/workflow-planning-entry/SKILL.md has allowed-tools for knowledge.cjs if not already present (it may have been added as an entry-point skill in Task 5-1, but planning-entry is a phase entry skill, not an entry-point skill — check).\n\nAcceptance Criteria:\n- Inline callouts exist at pertinent points in 7 processing skills (all except specification)\n- Callouts are brief nudges (1-2 lines), not full reference loads\n- Callouts are placed at high-value moments identified by reading each skill's flow\n- Specification process has NO callouts\n- Planning entry cross-cutting query replaces the manual approach in cross-cutting-context.md\n- Cross-cutting query uses --work-type cross-cutting filter\n- Cross-cutting query uses descriptive topic text, not topic slug\n- Planning entry has allowed-tools for knowledge.cjs\n\nTests:\n- No automated tests — skill file editing task. Validation is manual:\n - Read processing skills and verify callouts are placed at high-value moments\n - Start planning for a topic with existing cross-cutting specs indexed -\u003e verify the query surfaces relevant cross-cutting decisions\n - Verify the old manual cross-cutting spec reading approach is replaced, not duplicated\n\nEdge Cases:\n- Planning entry cross-cutting query when no cross-cutting specs are indexed — returns [0 results], planning proceeds without cross-cutting context (same as today when no cross-cutting specs exist)\n- Callout placement in skills with varying step structures — read each skill carefully, do not add callouts at the same structural position in every skill. Placement is semantic, not mechanical.\n- The planning-entry skill is a phase entry skill (internal, user-invocable: false), not an entry-point skill. It was NOT updated in Task 5-1 (which targeted start-*/continue-* skills). It needs allowed-tools for the cross-cutting query added here.\n\nSpec Reference: knowledge-base/design.md — Three-layer integration pattern (lines 716-724, Layer 3 description — inline callouts same pattern as review agents and commit reminders), Planning entry cross-cutting query (line 562, replaces existing manual approach, filtered to work_type: cross-cutting), and the note that this is a deterministic step replacing existing functionality (line 726)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-18T19:10:26Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-18T19:13:35Z","auto":false}],"parent":"tick-496c59","created":"2026-04-09T18:23:50Z","updated":"2026-04-18T19:13:35Z","closed":"2026-04-18T19:13:35Z"} -{"id":"tick-2e511f","title":"Phase 7: Setup Wizard","status":"in_progress","priority":2,"refs":["knowledge-base-7"],"transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:28:36Z","auto":true}],"parent":"tick-cbbd13","created":"2026-04-09T19:04:09Z","updated":"2026-04-19T16:28:36Z"} +{"id":"tick-2e511f","title":"Phase 7: Setup Wizard","status":"done","priority":2,"refs":["knowledge-base-7"],"transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:28:36Z","auto":true},{"from":"in_progress","to":"done","at":"2026-04-19T16:44:49Z","auto":true}],"parent":"tick-cbbd13","created":"2026-04-09T19:04:09Z","updated":"2026-04-19T16:44:49Z","closed":"2026-04-19T16:44:49Z"} {"id":"tick-78c1c7","title":"Setup Wizard: System Config + Project Init + Stub Mode","status":"done","priority":2,"type":"task","refs":["knowledge-base-7-1"],"description":"Problem: Users need a single entry point to configure the knowledge base for the first time. This involves system-level configuration (API keys, provider choice) that lives in the user's home directory and project-level initialisation that lives in .workflows/. Both must be handled in one flow so the user doesn't need to know the internal structure.\n\nSolution: Implement the knowledge setup command as an interactive wizard using Node's readline interface, handling system config, project init, and stub mode in one guided flow.\n\nOutcome: A user can run one command and have a fully configured knowledge base ready for use, with clear prompts at each step and graceful handling of partial or existing configuration.\n\nDo:\n- Implement the setup command handler in the CLI (invoked by Task 3-1 dispatch).\n- Invocation: knowledge setup (no arguments)\n- HUMAN-ONLY — uses interactive prompts throughout via Node readline interface (process.stdin/process.stdout). Claude cannot handle interactive terminals — this is the natural protection against accidental invocation (design doc line 632).\n\nSTEP 1: SYSTEM CONFIG (~/.config/workflows/config.json):\n- Check if system config already exists.\n - If it exists: read it, display current settings, ask if the user wants to reconfigure or skip. If skip, proceed to Step 2.\n - If it does not exist: create ~/.config/workflows/ directory if needed.\n- Prompt for provider:\n Which embedding provider? (openai / skip)\n - openai: proceed with OpenAI configuration\n - skip: stub mode (keyword-only search, no embeddings). Write config with no provider field. Display clear message about limitations. Proceed to Step 2.\n- If openai selected:\n - Prompt for model (default: text-embedding-3-small):\n Embedding model [text-embedding-3-small]:\n - Prompt for dimensions (default: 1536):\n Vector dimensions [1536]:\n - Prompt for API key env var name (default: OPENAI_API_KEY):\n API key environment variable [OPENAI_API_KEY]:\n - Check if the env var is set in the current environment:\n - If set: validate with a test embed call — embed a short test string and verify a vector is returned. If validation fails, display the error and ask the user to fix it or continue anyway.\n - If not set: warn the user and explain they need to set this env var in their shell profile before using the knowledge base. Do not block — they may be setting it up for later.\n- Write system config to ~/.config/workflows/config.json:\n { knowledge: { provider, model, dimensions, api_key_env, similarity_threshold: 0.8, decay_months: 6 } }\n- For stub mode (skip): write minimal config:\n { knowledge: { similarity_threshold: 0.8, decay_months: 6 } }\n\nSTEP 2: PROJECT INIT (.workflows/.knowledge/):\n- Check if project knowledge base directory already exists with config.json and store.msp.\n - If fully initialised: display status and ask to skip or reinitialise. If skip, proceed to Step 3.\n - If partially initialised (directory exists but missing files): complete the missing pieces.\n - If not initialised: create from scratch.\n- Create .workflows/.knowledge/ directory.\n- Write .workflows/.knowledge/config.json — project-level config. By default this is empty (inherits everything from system config):\n { knowledge: {} }\n The user can customise project-level overrides later by editing this file.\n- Create an empty Orama store and save it to .workflows/.knowledge/store.msp using createStore + saveStore from Phase 1. Use the dimensions from the resolved config (system + project merge).\n- Write .workflows/.knowledge/metadata.json with the provider/model/dimensions from the resolved config (or empty provider fields for stub mode).\n\nREADLINE INTERFACE:\n- Use Node built-in readline module (require('readline')).\n- Create interface with input: process.stdin, output: process.stdout.\n- Use rl.question() for prompts with defaults shown in brackets.\n- Close the interface when done.\n- If stdin is not a TTY (piped input, non-interactive environment): detect with process.stdin.isTTY and abort with message: knowledge setup requires an interactive terminal. Run it directly, not through Claude.\n\nAcceptance Criteria:\n- knowledge setup prompts for provider, model, dimensions, API key env var\n- System config is written to ~/.config/workflows/config.json\n- Project knowledge base is initialised at .workflows/.knowledge/ with config.json, store.msp, metadata.json\n- Test embed call validates the API key when configured\n- Stub mode writes config without provider, displays limitation message\n- Existing system config is detected and can be skipped or reconfigured\n- Existing project init is detected and can be skipped\n- Non-interactive terminal is detected and aborts with clear message\n- npm run build succeeds with the setup command included\n\nTests:\n- No automated tests for the interactive flow — it is inherently human-driven.\n- Unit tests for the non-interactive parts (tests/scripts/test-knowledge-config.cjs — extend from Task 3-1):\n - it creates a valid system config object from provider choices\n - it creates a valid stub-mode config object\n - it detects existing system config correctly\n - it detects existing project init correctly\n - it creates the project directory structure correctly\n\nEdge Cases:\n- ~/.config/workflows/ directory does not exist — create it (mkdir -p equivalent with { recursive: true })\n- .workflows/ directory does not exist — this means no workflow project exists. Display error: No .workflows/ directory found. Initialise a workflow project first.\n- System config file exists but is invalid JSON — display error, offer to overwrite\n- API key env var is set but the test embed call fails (wrong key, network error) — display error, offer to continue setup anyway (user may fix the key later)\n- User presses Ctrl+C during setup — readline handles SIGINT, process exits cleanly\n- Previous setup was stub mode, user re-runs with openai — detect existing store has no vectors, suggest knowledge rebuild after setup completes\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, interactive wizard flow, skip logic, stub mode), System config creation flow review finding #18 (line 1008), Configuration Hierarchy section (lines 258-301, system and project config schemas)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:28:36Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-19T16:36:59Z","auto":false}],"parent":"tick-2e511f","created":"2026-04-09T19:05:02Z","updated":"2026-04-19T16:36:59Z","closed":"2026-04-19T16:36:59Z"} -{"id":"tick-b4348b","title":"Setup Wizard: Initial Indexing + Idempotency + CLI Integration","status":"open","priority":2,"type":"task","refs":["knowledge-base-7-2"],"description":"Problem: After system config and project init (Task 7-1), the knowledge base is empty. Existing projects may have dozens of completed artifacts that need to be indexed. The setup wizard must automatically index everything as its final step, and re-running setup must be safe — skipping already-completed steps without duplicating work.\n\nSolution: Wire up the existing bulk index logic (Task 4-4) as the final step of the setup wizard, ensure the full setup flow is idempotent, and register setup in the CLI dispatch.\n\nOutcome: Running knowledge setup on a project with existing completed work populates the knowledge base immediately. Re-running setup on an already-configured project skips to indexing (or exits if everything is done).\n\nDo:\n\nINITIAL INDEXING (Step 3 of the setup wizard):\n- After system config (Step 1) and project init (Step 2) complete (or are skipped), run initial indexing.\n- This delegates to the existing knowledge index (no args) bulk index logic from Task 4-4.\n- The bulk index discovers all completed artifacts via manifest, diffs against the store (which is empty for first setup), and indexes everything.\n- Display progress as files are indexed (same output as the bulk index command).\n- Display a clear completion summary covering how many files and chunks were indexed.\n- If the store already has chunks (re-run scenario): the bulk index logic naturally skips already-indexed items and only processes missing ones. No special handling needed.\n- If indexing fails for some files: the retry/pending queue mechanism from Task 4-4 handles it. Inform the user that some files could not be indexed and were added to the pending queue for automatic retry on next use.\n\nIDEMPOTENCY:\n- The full setup flow must be safe to re-run at any point:\n - System config exists → display current settings, offer to skip or reconfigure\n - Project init exists → display status, offer to skip or reinitialise\n - Store has chunks → bulk index skips already-indexed, only processes new/missing\n - Everything is current → display a clear \"already set up\" message and exit.\n- This covers the design doc requirement (line 631): skips steps that are already done.\n- Also covers the interrupted-setup scenario (design doc finding #5, line 965): if setup was interrupted mid-indexing, re-running picks up where it left off via the pending queue.\n\nCLI INTEGRATION:\n- Register the setup command in the CLI dispatch from Task 3-1. Task 3-1 lists setup alongside other Phase 4+ commands with a \"not yet implemented\" placeholder — replace that placeholder with a real handler that calls the wizard flow from Task 7-1 followed by the initial indexing from this task.\n\nSTUB-TO-FULL UPGRADE PATH:\n- If the user previously ran setup in stub mode and now re-runs with an OpenAI provider:\n - System config is updated with the new provider settings.\n - The existing store has no vectors (keyword-only mode).\n - Inform the user that the previous setup was keyword-only and they should run knowledge rebuild to re-index with embeddings for full hybrid search.\n - Do NOT automatically rebuild — it is destructive and may take time. The user should run it explicitly.\n- This matches the design doc (line 329): upgrading from stub to full requires knowledge rebuild.\n\nAcceptance Criteria:\n- Setup wizard indexes all existing completed artifacts as its final step\n- Progress and summary output matches the bulk index command\n- Failed indexing files are logged to pending queue with a note to the user\n- Re-running setup on a fully configured project exits cleanly with an already-set-up message\n- Re-running setup after interrupted indexing picks up where it left off\n- Setup command registered in CLI dispatch, replacing the Task 3-1 not-yet-implemented placeholder\n- Stub-to-full upgrade detected and user informed about knowledge rebuild\n- npm run build succeeds\n\nTests:\n- Unit tests for idempotency logic (tests/scripts/test-knowledge-config.cjs — extend):\n - it detects fully configured state (system + project + indexed)\n - it detects partially configured state (system exists, project missing)\n - it detects empty store needing initial indexing\n- CLI dispatch test (tests/scripts/test-knowledge-cli.sh — extend):\n - it routes to setup command without error (non-interactive detection will abort, which is the expected behaviour in test)\n- Manual validation:\n - Run setup on a project with existing completed artifacts -\u003e verify all are indexed\n - Run setup again -\u003e verify it skips everything and exits cleanly\n - Run setup after interruption -\u003e verify pending queue items are processed\n\nEdge Cases:\n- Project with no completed work units — initial indexing indexes 0 files, which is correct. The knowledge base is ready but empty.\n- Project with hundreds of completed artifacts — initial indexing may take time (embedding API calls). Display progress so the user knows it is working.\n- Setup interrupted with Ctrl+C during indexing — indexed files are saved (each save is atomic), unindexed files go to pending queue. Re-run picks up.\n- System config points to a provider but the API key env var is not set — initial indexing will fail (provider cannot embed). The retry/pending queue catches this. Setup still completes — the project is initialised, indexing is pending.\n- Multiple projects sharing the same system config — this is normal. System config has provider/key, each project has its own .workflows/.knowledge/. Setup only modifies the current project.\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, initial indexing as final step, skip logic), Init/resumability finding #5 (line 965, interrupted setup, pending queue picks up), Upgrading from stub to full (line 329, requires rebuild)","parent":"tick-2e511f","created":"2026-04-09T19:05:40Z","updated":"2026-04-10T20:47:17Z"} +{"id":"tick-b4348b","title":"Setup Wizard: Initial Indexing + Idempotency + CLI Integration","status":"done","priority":2,"type":"task","refs":["knowledge-base-7-2"],"description":"Problem: After system config and project init (Task 7-1), the knowledge base is empty. Existing projects may have dozens of completed artifacts that need to be indexed. The setup wizard must automatically index everything as its final step, and re-running setup must be safe — skipping already-completed steps without duplicating work.\n\nSolution: Wire up the existing bulk index logic (Task 4-4) as the final step of the setup wizard, ensure the full setup flow is idempotent, and register setup in the CLI dispatch.\n\nOutcome: Running knowledge setup on a project with existing completed work populates the knowledge base immediately. Re-running setup on an already-configured project skips to indexing (or exits if everything is done).\n\nDo:\n\nINITIAL INDEXING (Step 3 of the setup wizard):\n- After system config (Step 1) and project init (Step 2) complete (or are skipped), run initial indexing.\n- This delegates to the existing knowledge index (no args) bulk index logic from Task 4-4.\n- The bulk index discovers all completed artifacts via manifest, diffs against the store (which is empty for first setup), and indexes everything.\n- Display progress as files are indexed (same output as the bulk index command).\n- Display a clear completion summary covering how many files and chunks were indexed.\n- If the store already has chunks (re-run scenario): the bulk index logic naturally skips already-indexed items and only processes missing ones. No special handling needed.\n- If indexing fails for some files: the retry/pending queue mechanism from Task 4-4 handles it. Inform the user that some files could not be indexed and were added to the pending queue for automatic retry on next use.\n\nIDEMPOTENCY:\n- The full setup flow must be safe to re-run at any point:\n - System config exists → display current settings, offer to skip or reconfigure\n - Project init exists → display status, offer to skip or reinitialise\n - Store has chunks → bulk index skips already-indexed, only processes new/missing\n - Everything is current → display a clear \"already set up\" message and exit.\n- This covers the design doc requirement (line 631): skips steps that are already done.\n- Also covers the interrupted-setup scenario (design doc finding #5, line 965): if setup was interrupted mid-indexing, re-running picks up where it left off via the pending queue.\n\nCLI INTEGRATION:\n- Register the setup command in the CLI dispatch from Task 3-1. Task 3-1 lists setup alongside other Phase 4+ commands with a \"not yet implemented\" placeholder — replace that placeholder with a real handler that calls the wizard flow from Task 7-1 followed by the initial indexing from this task.\n\nSTUB-TO-FULL UPGRADE PATH:\n- If the user previously ran setup in stub mode and now re-runs with an OpenAI provider:\n - System config is updated with the new provider settings.\n - The existing store has no vectors (keyword-only mode).\n - Inform the user that the previous setup was keyword-only and they should run knowledge rebuild to re-index with embeddings for full hybrid search.\n - Do NOT automatically rebuild — it is destructive and may take time. The user should run it explicitly.\n- This matches the design doc (line 329): upgrading from stub to full requires knowledge rebuild.\n\nAcceptance Criteria:\n- Setup wizard indexes all existing completed artifacts as its final step\n- Progress and summary output matches the bulk index command\n- Failed indexing files are logged to pending queue with a note to the user\n- Re-running setup on a fully configured project exits cleanly with an already-set-up message\n- Re-running setup after interrupted indexing picks up where it left off\n- Setup command registered in CLI dispatch, replacing the Task 3-1 not-yet-implemented placeholder\n- Stub-to-full upgrade detected and user informed about knowledge rebuild\n- npm run build succeeds\n\nTests:\n- Unit tests for idempotency logic (tests/scripts/test-knowledge-config.cjs — extend):\n - it detects fully configured state (system + project + indexed)\n - it detects partially configured state (system exists, project missing)\n - it detects empty store needing initial indexing\n- CLI dispatch test (tests/scripts/test-knowledge-cli.sh — extend):\n - it routes to setup command without error (non-interactive detection will abort, which is the expected behaviour in test)\n- Manual validation:\n - Run setup on a project with existing completed artifacts -\u003e verify all are indexed\n - Run setup again -\u003e verify it skips everything and exits cleanly\n - Run setup after interruption -\u003e verify pending queue items are processed\n\nEdge Cases:\n- Project with no completed work units — initial indexing indexes 0 files, which is correct. The knowledge base is ready but empty.\n- Project with hundreds of completed artifacts — initial indexing may take time (embedding API calls). Display progress so the user knows it is working.\n- Setup interrupted with Ctrl+C during indexing — indexed files are saved (each save is atomic), unindexed files go to pending queue. Re-run picks up.\n- System config points to a provider but the API key env var is not set — initial indexing will fail (provider cannot embed). The retry/pending queue catches this. Setup still completes — the project is initialised, indexing is pending.\n- Multiple projects sharing the same system config — this is normal. System config has provider/key, each project has its own .workflows/.knowledge/. Setup only modifies the current project.\n\nSpec Reference: knowledge-base/design.md — knowledge setup command (lines 626-633, initial indexing as final step, skip logic), Init/resumability finding #5 (line 965, interrupted setup, pending queue picks up), Upgrading from stub to full (line 329, requires rebuild)","transitions":[{"from":"open","to":"in_progress","at":"2026-04-19T16:37:13Z","auto":false},{"from":"in_progress","to":"done","at":"2026-04-19T16:44:49Z","auto":false}],"parent":"tick-2e511f","created":"2026-04-09T19:05:40Z","updated":"2026-04-19T16:44:49Z","closed":"2026-04-19T16:44:49Z"} {"id":"tick-74a599","title":"Phase 8: Release Process","status":"open","priority":2,"refs":["knowledge-base-8"],"parent":"tick-cbbd13","created":"2026-04-09T19:05:44Z","updated":"2026-04-09T19:05:44Z"} {"id":"tick-7f4725","title":"Release Script Build Integration","status":"open","priority":2,"type":"task","refs":["knowledge-base-8-1"],"description":"Problem: The knowledge CLI bundle (knowledge.cjs) must be committed to the repo before tagging because AGNTC installs from git tags with no build step. During Phases 1-7 development, the bundle was built and committed manually. For production releases, the build must be formalised into the release pipeline to prevent shipping stale bundles.\n\nSolution: Integrate the esbuild build step into the local release script so the bundle is always fresh when a release tag is created.\n\nOutcome: The release process automatically builds knowledge.cjs from source before tagging, ensuring every tagged release has an up-to-date bundle.\n\nDo:\n- Read the existing release script at the project root (./release) before editing. Study:\n 1. Where perform_release runs the dirty-tree gate (git status --porcelain check that aborts on any uncommitted changes)\n 2. Where perform_release currently stages/commits (note: this is gated inside an `if [[ \"$VERSION_STRATEGY\" != \"none\" ]]` block — the default \"none\" strategy currently performs no commit at all, only tag + push)\n 3. Where the annotated tag is created and pushed\n- The build step must sit AFTER the existing dirty-tree check and BEFORE the annotated tag is created. Placing it before the dirty-tree check would cause the gate to abort on a bundle rebuild; placing it after the tag would ship a stale bundle in the tagged commit.\n- The build step sequence:\n 1. Run `npm install` (ensure dev dependencies are available)\n 2. Run `npm run build` (esbuild bundles src/knowledge/ into skills/workflow-knowledge/scripts/knowledge.cjs)\n 3. Check whether the bundle changed (e.g., git diff on the bundle path)\n 4. If it changed: stage and commit the updated bundle. IMPORTANT: this commit must occur in ALL version strategies, including `VERSION_STRATEGY=\"none\"` — the existing `none` branch performs no commits, so this task is introducing a new commit point into a previously commit-free path. Do not hide the bundle commit inside the existing version-bump commit block; it is a distinct concern and must run regardless of version strategy.\n 5. If the bundle did not change: no commit needed, proceed.\n 6. Proceed with the existing tag + push flow.\n- Build failure (non-zero exit from `npm run build`) must abort the release — do not tag with a stale or missing bundle. Clean exit with a clear error.\n- The bundle commit is the only permitted mutation after the dirty-tree check passes. The dirty-tree check still protects against unrelated uncommitted user changes — the user's working tree must be clean entering the release, and the bundle commit is the only thing the release script itself adds on top.\n- DECISION POINT: the design doc (line 52) flags a choice between local build and CI build. This task implements the local-in-release-script path. Reasoning: the bundle must be committed BEFORE tagging (AGNTC installs from tags), and GitHub Actions runs AFTER tag push — too late to commit. Local build keeps the flow simple (build → commit → tag → push → CI validates). CI validates the committed bundle in Task 8-2 but does not rebuild it.\n- package.json already exists from Phase 1 (Task 1-1) with dev deps and build script. No changes needed to package.json.\n- node_modules/ is already gitignored from Phase 1. No changes needed.\n- The design doc also mentions (line 53) that GitHub releases may no longer be needed since AGNTC uses tags, not releases. Consider simplifying if trivial; defer if not. This is a note, not a requirement.\n\nAcceptance Criteria:\n- Release script runs `npm install` + `npm run build` between the dirty-tree check and the annotated tag\n- Updated bundle is committed before the tag is created\n- Bundle commit occurs in all version strategies, including `VERSION_STRATEGY=\"none\"` (previously commit-free)\n- Build failure aborts the release with a clear error message\n- Existing dirty-tree check still rejects unrelated uncommitted user changes\n- Existing release flow (version handling, tag, push) is preserved after the build step\n- Tagged releases contain the up-to-date knowledge.cjs bundle\n- node_modules/ remains gitignored\n\nTests:\n- Test file: tests/scripts/test-release-build.sh (shell test)\n- it runs the build step before tagging\n- it commits the updated bundle when the diff shows changes (in both default and `none` version strategies)\n- it skips the commit when the bundle is unchanged\n- it aborts release on build failure\n- it still rejects dirty working tree on entry\n- Manual validation:\n - Run release with modified source -\u003e verify bundle is rebuilt and committed before tag\n - Run release with no source changes -\u003e verify no unnecessary commit\n - Run release with `VERSION_STRATEGY=\"none\"` and modified source -\u003e verify bundle commit still happens\n\nEdge Cases:\n- First release after Phase 1 — bundle already exists and is committed. Build step rebuilds it (may or may not change depending on esbuild determinism). If unchanged, no commit.\n- npm install fails (network error, registry down) — abort release with clear error\n- Bundle size grows significantly in later phases — Task 1-1 sets a size threshold. If build produces a bundle over that, Task 1-1's test-knowledge-build.sh fails, which blocks CI in Task 8-2, which blocks the release.\n- Git working directory has uncommitted changes at script start — the existing dirty-tree gate aborts before any build step runs. User must commit or stash first.\n- Uncommitted bundle diff at script start — same as above, aborts on the dirty-tree gate. User handles manually.\n\nSpec Reference: knowledge-base/design.md — Release Process section (lines 45-54, build before tagging, bundle committed, local vs CI decision, GitHub releases simplification consideration), Build and Distribution section (lines 448-457, bundle committed to repo, release workflow change required). Script file to modify: ./release (perform_release function — dirty-tree check, VERSION_STRATEGY branch, tag creation).","parent":"tick-74a599","created":"2026-04-09T19:06:33Z","updated":"2026-04-10T20:47:18Z"} {"id":"tick-de9b1a","title":"CI Test Pipeline Update","status":"open","priority":2,"type":"task","refs":["knowledge-base-8-2"],"description":"Problem: The GitHub Actions release workflow runs tests on tag push but currently only runs migration tests and discovery tests. The knowledge base adds new test files (Node .cjs and shell .sh) that must be included in the CI pipeline to prevent regressions from reaching tagged releases. Additionally, test-workflow-manifest.sh (which will gain manifest resolve tests from Task 3-2) is NOT currently run in CI since it doesn't match the existing glob patterns.\n\nSolution: Update the GitHub Actions release workflow to include all knowledge base test files alongside the existing test suite, explicitly include test-workflow-manifest.sh, and ensure the Node version is 18+ as required by Orama.\n\nOutcome: Every tagged release runs the full test suite including all knowledge base tests and the manifest resolve test, catching regressions before the release is published.\n\nDo:\n- Read the existing GitHub Actions workflow at .github/workflows/release.yml to understand the current test structure. The current pipeline (from the explore agent findings):\n - Run discovery tests: for test in tests/scripts/test-discovery-*.cjs; do node --test test; done\n - Run migration tests: for test in tests/scripts/test-migration-*.sh; do /bin/bash test; done\n\n- Verify and update the Node version. Design doc line 453 requires Node 18 minimum (Orama requirement), Node 20+ recommended. Check the workflow's node-version setting. If it uses an older version or is unspecified, update it to 20.\n\n- Add npm install step BEFORE the test runs. Unit tests (test-knowledge-embeddings.cjs, test-knowledge-store.cjs, test-knowledge-chunker.cjs, test-knowledge-config.cjs) import from src/knowledge/ source files, which require @orama/orama and @msgpack/msgpack from node_modules. npm install provides these dev dependencies.\n\n- DO NOT add npm run build in CI. The bundle is committed before tagging (per Task 8-1's local build decision). CI validates the committed bundle — it does not rebuild. Rebuilding in CI could produce a different bundle if esbuild has any non-determinism, which would defeat the purpose of committing the bundle before tagging. The integration test (Task 1-5) imports from the committed bundle directly.\n\n- Add knowledge base test runs in the same pattern as existing tests:\n\n Knowledge Node tests:\n for test in tests/scripts/test-knowledge-*.cjs; do\n node --test \"$test\"\n done\n This glob covers all Node test files created across Phases 1-4 (embeddings, store, chunker, config, integration, retry, openai).\n\n Knowledge shell tests:\n for test in tests/scripts/test-knowledge-*.sh; do\n /bin/bash \"$test\"\n done\n This glob covers all shell test files created across Phases 1-4 (build, cli).\n\n- EXPLICITLY include test-workflow-manifest.sh. This file exists (pre-knowledge-base) and will gain manifest resolve tests from Task 3-2. It does NOT match test-discovery-*.cjs or test-migration-*.sh globs, so it is currently NOT run in CI. Add it as a direct invocation:\n /bin/bash tests/scripts/test-workflow-manifest.sh\n This is a pre-existing CI gap that Phase 8 is closing.\n\n- The test pipeline ordering should be:\n 1. checkout (existing)\n 2. setup-node with node-version: 20 (verify/update)\n 3. npm install (new — for unit test dev deps)\n 4. Run migration tests (existing)\n 5. Run discovery tests (existing)\n 6. Run test-workflow-manifest.sh (new — explicit)\n 7. Run knowledge Node tests (new)\n 8. Run knowledge shell tests (new)\n\n- The OpenAI integration test (test-knowledge-openai-integration.cjs) is opt-in — it only runs when OPENAI_API_KEY env var is present. In CI, this env var is NOT set by default (no API keys in CI). The test skips itself. If the repo owner wants to run it in CI, they can add the secret to GitHub Actions — but this is optional, not required.\n\nAcceptance Criteria:\n- GitHub Actions workflow uses Node 20+ (verified or updated)\n- GitHub Actions workflow runs npm install before tests (for unit test dev deps)\n- GitHub Actions workflow does NOT run npm run build (bundle is already committed per Task 8-1)\n- GitHub Actions workflow runs all test-knowledge-*.cjs tests\n- GitHub Actions workflow runs all test-knowledge-*.sh tests\n- GitHub Actions workflow explicitly runs tests/scripts/test-workflow-manifest.sh\n- All tests pass in CI (the integration test skips without API key)\n- Existing migration and discovery tests continue to run\n- Test failure blocks the release (non-zero exit fails the workflow)\n\nTests:\n- No separate test for this task — the CI pipeline IS the test. Validation:\n - Push a tag and verify the GitHub Actions workflow runs all knowledge tests + test-workflow-manifest.sh\n - Verify the integration test is skipped (no OPENAI_API_KEY in CI)\n - Verify a test failure would block the release\n\nEdge Cases:\n- npm install in CI takes time — consider caching node_modules across runs (GitHub Actions cache action). Not required but improves CI speed.\n- Knowledge shell tests may depend on node being in PATH to run the bundle — verify the CI environment has node available for shell test subprocesses.\n- Test file ordering — tests should be independent and not depend on execution order. If any knowledge test depends on state from another test, that is a bug in the test.\n- Committed bundle mismatch — if the committed bundle is stale (developer forgot to rebuild before tagging), CI tests against it will either pass (if the bundle is still functionally correct) or fail (if tests assume newer behavior). This is a content issue, not a CI configuration issue. Task 8-1's build-before-tag flow prevents this.\n\nSpec Reference: knowledge-base/design.md — Testing Strategy section (lines 463-475, test location conventions, CLI command tests against built bundle), Build and Distribution section (lines 448-457, bundle committed to repo, release workflow needs build step — implemented in Task 8-1), Node version requirement (line 453)","parent":"tick-74a599","created":"2026-04-09T19:08:28Z","updated":"2026-04-10T15:29:37Z"} diff --git a/skills/workflow-knowledge/SKILL.md b/skills/workflow-knowledge/SKILL.md index 6846ecaa2..27df96692 100644 --- a/skills/workflow-knowledge/SKILL.md +++ b/skills/workflow-knowledge/SKILL.md @@ -208,7 +208,7 @@ Skills do not call these directly during normal operation. Users run them manual ## `setup` — interactive wizard -Not yet implemented (stub — Phase 7 of the knowledge base rollout). When available, it will handle system config, project init, and initial indexing in one flow. **Human-only** — interactive prompts. If `knowledge check` returns `not-ready`, direct the user to run `knowledge setup` rather than trying to fix it programmatically. +One-shot first-time setup. Handles system config (`~/.config/workflows/config.json`), project init (`.workflows/.knowledge/`), and initial indexing of all completed artifacts in a single guided flow. **Human-only** — prompts throughout via readline. Non-TTY invocations (including Claude or piped input) abort with `knowledge setup requires an interactive terminal`. If `knowledge check` returns `not-ready`, direct the user to run `knowledge setup` rather than trying to fix it programmatically. Safe to re-run: per-step prompts detect existing state and offer skip or reconfigure; the bulk index at the end only processes missing artifacts. --- diff --git a/skills/workflow-knowledge/scripts/knowledge.cjs b/skills/workflow-knowledge/scripts/knowledge.cjs index 46151323b..6bc97f601 100644 --- a/skills/workflow-knowledge/scripts/knowledge.cjs +++ b/skills/workflow-knowledge/scripts/knowledge.cjs @@ -1,33 +1,33 @@ -"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=b(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SUPPORTED_LANGUAGES=V.SPLITTERS=V.STEMMERS=void 0;V.getLocale=ic;V.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};V.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};V.SUPPORTED_LANGUAGES=Object.keys(V.STEMMERS);function ic(t){return t!==void 0&&V.SUPPORTED_LANGUAGES.includes(t)?V.STEMMERS[t]:void 0}});var L=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=ac;O.sprintf=lc;O.formatBytes=dc;O.isInsideWebWorker=$r;O.isInsideNode=zr;O.getNanosecondTimeViaPerformance=dn;O.formatNanoseconds=fc;O.getNanosecondsTime=hc;O.uniqueId=pc;O.getOwnProperty=gc;O.getTokenFrequency=yc;O.insertSortedValue=mc;O.sortTokenScorePredicate=Vr;O.intersect=wc;O.getDocumentProperties=Wr;O.getNested=_c;O.flattenObject=Kr;O.convertDistanceToMeters=bc;O.removeVectorsFromHits=Ic;O.isPromise=xc;O.isAsyncFunction=Hr;O.setIntersection=Ec;O.setUnion=vc;O.setDifference=Tc;O.sleep=Dc;var oc=j(),cc=Date.now().toString().slice(5),uc=0,jr=1024,Fr=BigInt(1e3),Cr=BigInt(1e6),Br=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function ac(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[l,d]=s.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(a=a.toFixed(d)),typeof l=="number"&&l>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function dc(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(jr));return`${parseFloat((t/Math.pow(jr,s)).toFixed(n))} ${r[s]}`}function $r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function zr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function dn(){return BigInt(Math.floor(performance.now()*1e6))}function fc(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Vr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function wc(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Wr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function xc(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Hr(t){return Array.isArray(t)?t.some(e=>Hr(e)):t?.constructor?.name==="AsyncFunction"}var qr="intersection"in new Set;function Ec(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if(qr)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var j=b(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.createError=Nc;var Mc=lt(),Oc=L(),Pc=Mc.SUPPORTED_LANGUAGES.join(` - - `),kc={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. +"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=b(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SUPPORTED_LANGUAGES=V.SPLITTERS=V.STEMMERS=void 0;V.getLocale=oc;V.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};V.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};V.SUPPORTED_LANGUAGES=Object.keys(V.STEMMERS);function oc(t){return t!==void 0&&V.SUPPORTED_LANGUAGES.includes(t)?V.STEMMERS[t]:void 0}});var L=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=lc;O.sprintf=dc;O.formatBytes=fc;O.isInsideWebWorker=zr;O.isInsideNode=Vr;O.getNanosecondTimeViaPerformance=fn;O.formatNanoseconds=hc;O.getNanosecondsTime=pc;O.uniqueId=gc;O.getOwnProperty=yc;O.getTokenFrequency=mc;O.insertSortedValue=wc;O.sortTokenScorePredicate=Wr;O.intersect=_c;O.getDocumentProperties=Kr;O.getNested=Sc;O.flattenObject=Hr;O.convertDistanceToMeters=Ic;O.removeVectorsFromHits=xc;O.isPromise=Ec;O.isAsyncFunction=Gr;O.setIntersection=Ac;O.setUnion=Tc;O.setDifference=Dc;O.sleep=Mc;var cc=j(),uc=Date.now().toString().slice(5),ac=0,Fr=1024,Cr=BigInt(1e3),Br=BigInt(1e6),qr=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function lc(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[l,d]=s.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(a=a.toFixed(d)),typeof l=="number"&&l>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function fc(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(Fr));return`${parseFloat((t/Math.pow(Fr,s)).toFixed(n))} ${r[s]}`}function zr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Vr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function fn(){return BigInt(Math.floor(performance.now()*1e6))}function hc(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Wr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function _c(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Kr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function Ec(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Gr(t){return Array.isArray(t)?t.some(e=>Gr(e)):t?.constructor?.name==="AsyncFunction"}var $r="intersection"in new Set;function Ac(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if($r)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var j=b(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.createError=Uc;var Oc=lt(),Pc=L(),kc=Oc.SUPPORTED_LANGUAGES.join(` + - `),Nc={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. Supported languages are: - - ${Pc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. + - ${kc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance. Please install it before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy `,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration. Please provide a chat model before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy -`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function Nc(t,...e){let n=new Error((0,Oc.sprintf)(kc[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var Be=b(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.getDocumentProperties=void 0;W.formatElapsedTime=Lc;W.getDocumentIndexId=Rc;W.validateSchema=Yr;W.isGeoPointType=Cc;W.isVectorType=Jr;W.isArrayType=Xr;W.getInnerType=Zr;W.getVectorSize=Qr;var dt=j(),Gr=L(),Uc=L();Object.defineProperty(W,"getDocumentProperties",{enumerable:!0,get:function(){return Uc.getDocumentProperties}});function Lc(t){return{raw:Number(t),formatted:(0,Gr.formatNanoseconds)(t)}}function Rc(t){if(t.id){if(typeof t.id!="string")throw(0,dt.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,Gr.uniqueId)()}function Yr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.createInternalDocumentIDStore=Bc;be.save=es;be.load=ts;be.getInternalDocumentId=ns;be.getDocumentIdFromInternalId=qc;function Bc(){return{idToInternalId:new Map,internalIdToId:[],save:es,load:ts}}function es(t){return{internalIdToId:t.internalIdToId}}function ts(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?ns(t,e.toString()):e}function qc(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.create=rs;K.get=ss;K.getMultiple=is;K.getAll=os;K.store=cs;K.remove=us;K.count=as;K.load=ls;K.save=ds;K.createDocumentsStore=$c;var hn=$();function rs(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function ss(t,e){let n=(0,hn.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function is(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function as(t){return t.count}function ls(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function ds(t){return{docs:t.docs,count:t.count}}function $c(){return{create:rs,get:ss,getMultiple:is,getAll:os,store:cs,remove:us,count:as,load:ls,save:ds}}});var fs=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.AVAILABLE_PLUGIN_HOOKS=void 0;qe.getAllPluginsByHook=Vc;var zc=j();qe.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function Vc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.SINGLE_OR_ARRAY_COMPONENTS=z.FUNCTION_COMPONENTS=z.OBJECT_COMPONENTS=void 0;z.runSingleHook=Wc;z.runMultipleHook=Kc;z.runAfterSearch=Hc;z.runBeforeSearch=Gc;z.runAfterCreate=Yc;var $e=L();z.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];z.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];z.SINGLE_OR_ARRAY_COMPONENTS=[];function Wc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Kc(t,e,n){if(t.some($e.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function Hc(t,e,n,r,s){if(t.some($e.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function Gc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Yc(t,e){if(t.some($e.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var hs=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.AVLTree=Me.AVLNode=void 0;var ue=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Me.AVLNode=ue;var gn=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ue(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ue.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ue(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ue(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:l,node:d}=i[a];if(d.updateHeight(),u){let f=this.rebalanceNode(d);l?l.l===d?l.l=f:l.r===d&&(l.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Me.AVLTree=gn});var ps=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FlatTree=void 0;var yn=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ft.FlatTree=yn});var mn=b(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.boundedLevenshtein=Jc;ze.syncBoundedLevenshtein=Xc;ze.levenshtein=Zc;function gs(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function Jc(t,e,n){let r=gs(t,e,n);return{distance:r,isBounded:r>=0}}function Xc(t,e,n){let r=gs(t,e,n);return{distance:r,isBounded:r>=0}}function Zc(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var ms=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.RadixTree=Oe.RadixNode=void 0;var ys=mn(),wn=L(),Ve=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,wn.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,ys.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,wn.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let l of u)a.includes(l)||a.push(l)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:d,d:f}=c;if(d&&((0,ys.syncBoundedLevenshtein)(e,d,s).isBounded&&(i[d]=[]),(0,wn.getOwnProperty)(i,d)!==void 0&&f.size>0)){let p=new Set(i[d]);for(let g of f)p.add(g);i[d]=Array.from(p)}}if(u>=e.length)continue;let l=e[u];if(c.c.has(l)){let d=c.c.get(l);o.push({node:d,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[d,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),d!==l&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};Oe.RadixNode=Ve;var _n=class t extends Ve{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,Ve.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};Oe.RadixTree=_n});var ws=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.BKDTree=void 0;var Qc=2,eu=6371e3,ht=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},Sn=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ht(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%Qc===0)if(e.lon0;){let{node:a,depth:l}=c.pop();if(a==null)continue;let d=o(e,a.point);(r?d<=n:d>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:l+1}),a.right!=null&&c.push({node:a.right,depth:l+1})}return s&&u.sort((a,l)=>{let d=o(e,a.point),f=o(e,l.point);return s.toLowerCase()==="asc"?d-f:f-d}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let l=t.isPointInPolygon(e,u.point);(l&&n||!l&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,l)=>{let d=u(c,a.point),f=u(c,l.point);return r.toLowerCase()==="asc"?d-f:f-d})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ht.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(d-a)*(i-l)/(f-l)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return eu*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,l=Math.atan((1-s)*Math.tan(c)),d=Math.atan((1-s)*Math.tan(u)),f=Math.sin(l),p=Math.cos(l),g=Math.sin(d),y=Math.cos(d),h=a,m,w=1e3,S,_,I,v,D,A;do{let De=Math.sin(h),Ce=Math.cos(h);if(S=Math.sqrt(y*De*(y*De)+(p*g-f*y*Ce)*(p*g-f*y*Ce)),S===0)return 0;_=f*g+p*y*Ce,I=Math.atan2(S,_),v=p*y*De/S,D=1-v*v,A=_-2*f*g/D,isNaN(A)&&(A=0);let ln=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-ln)*s*v*(I+ln*S*(A+ln*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),Te=1+k/16384*(4096+k*(-768+k*(320-175*k))),Y=k/1024*(256+k*(-128+k*(74-47*k))),an=Y*S*(A+Y/4*(_*(-1+2*A*A)-Y/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*Te*(I-an)}};pt.BKDTree=Sn});var _s=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.BoolNode=void 0;var bn=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};gt.BoolNode=bn});var Ss=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.prioritizeTokenScores=nu;yt.BM25=ru;var tu=j();function nu(t,e,n=0,r){if(e===0)throw(0,tu.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let l=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];d=0}let f=l.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.VectorIndex=ae.DEFAULT_SIMILARITY=void 0;ae.getMagnitude=xn;ae.findSimilarVectors=bs;ae.DEFAULT_SIMILARITY=.8;var In=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=xn(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),bs(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};ae.VectorIndex=In;function xn(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var mt=b(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.insertDocumentScoreParameters=Os;R.insertTokenScoreParameters=Ps;R.removeDocumentScoreParameters=ks;R.removeTokenScoreParameters=Ns;R.create=vn;R.insert=Us;R.insertVector=Ls;R.remove=Rs;R.calculateResultScores=Tn;R.search=js;R.searchByWhereClause=We;R.getSearchableProperties=Fs;R.getSearchablePropertiesWithTypes=Cs;R.load=Bs;R.save=qs;R.createIndex=ou;R.searchByGeoWhereClause=uu;var Pe=j(),As=hs(),vs=ps(),Ts=ms(),Ke=ws(),Ds=_s(),ee=L(),su=Ss(),Ie=Be(),An=$(),Ms=En();function Os(t,e,n,r,s){let i=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function Ps(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function ks(t,e,n,r){let s=(0,An.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function Ns(t,e,n){t.tokenOccurrences[e][n]--}function vn(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){vn(t,e,o,r,c);continue}if((0,Ie.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new Ms.VectorIndex((0,Ie.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new Ds.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new As.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new Ts.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new vs.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new Ke.BKDTree,isArray:u};break;default:throw(0,Pe.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function iu(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:l}=e.indexes[n];switch(a){case"Bool":{l[u?"true":"false"].add(r);break}case"AVL":{let d=c?.avlRebalanceThreshold??1;l.insert(u,r,d);break}case"Radix":{let d=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,d,o);for(let f of d)t.insertTokenScoreParameters(e,n,r,d,f),l.insert(f,r);break}case"Flat":{l.insert(u,r);break}case"BKD":{l.insert(u,[r]);break}}}}function Us(t,e,n,r,s,i,o,c,u,a,l){if((0,Ie.isVectorType)(o))return Ls(e,n,i,r,s);let d=iu(t,e,n,s,c,u,a,l);if(!(0,Ie.isArrayType)(o))return d(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let an=Y.length;for(let at=0;at[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(d===1)return m;if(d===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(v=>v===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([v])=>v===I)),_=Math.ceil(S.length*d);return[...w,...S.slice(0,_)]}return m}function We(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>We(t,e,u,r));return(0,ee.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>We(t,e,u,r)).reduce((u,a)=>(0,ee.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let l=1;l<=u.internalIdToId.length;l++)c.add(l);let a=We(t,e,o,r);return(0,ee.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,Pe.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:l}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,ee.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,ee.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=xs(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=xs(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=au(i[o],y)}}continue}let d=Object.keys(c);if(d.length>1)throw(0,Pe.createError)("INVALID_FILTER_OPERATION",d.length);if(a==="Flat"){let f=new Set(l?u.filterArr(c):u.filter(c));i[o]=(0,ee.setUnion)(i[o],f);continue}if(a==="AVL"){let f=d[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,Pe.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,ee.setUnion)(i[o],g)}}return(0,ee.setIntersection)(...Object.values(i))}function Fs(t){return t.searchableProperties}function Cs(t){return t.searchablePropertiesWithTypes}function Bs(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,l={},d={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":l[f]={type:"Radix",node:Ts.RadixTree.fromJSON(p),isArray:y};break;case"Flat":l[f]={type:"Flat",node:vs.FlatTree.fromJSON(p),isArray:y};break;case"AVL":l[f]={type:"AVL",node:As.AVLTree.fromJSON(p),isArray:y};break;case"BKD":l[f]={type:"BKD",node:Ke.BKDTree.fromJSON(p),isArray:y};break;case"Bool":l[f]={type:"Bool",node:Ds.BoolNode.fromJSON(p),isArray:y};break;default:l[f]=n[f]}}for(let f of Object.keys(r))d[f]={type:"Vector",isArray:!1,node:Ms.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:l,vectorIndexes:d,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function qs(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let d of Object.keys(n))a[d]=n[d].node.toJSON();let l={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:g}=e[d];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?l[d]={type:f,node:p.toJSON(),isArray:g}:(l[d]=e[d],l[d].node=l[d].node.toJSON())}return{indexes:l,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function ou(){return{create:vn,insert:Us,remove:Rs,insertDocumentScoreParameters:Os,insertTokenScoreParameters:Ps,removeDocumentScoreParameters:ks,removeTokenScoreParameters:Ns,calculateResultScores:Tn,search:js,searchByWhereClause:We,getSearchableProperties:Fs,getSearchablePropertiesWithTypes:Cs,load:Bs,save:qs}}function xs(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function cu(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function uu(t,e){let n=t,r=cu(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:l="m",inside:d=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,ee.convertDistanceToMeters)(u,l);return c=o.searchByRadius(p,g,d,"asc",f),Es(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:l=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",l);let d=Ke.BKDTree.calculatePolygonCentroid(u);return Es(c,d,l)}return null}function au(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.load=Vs;He.save=Ws;He.createSorter=Eu;var Dn=j(),lu=Be(),wt=$(),du=L(),fu=lt();function $s(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=$s(t,e,c,r,u);(0,du.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,lu.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,Dn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function hu(t,e,n,r){return r?.enabled!==!1?$s(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function pu(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&Mn(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function zs(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)wu(t,n);t.isSorted=!0}function gu(t,e,n){return e[1].localeCompare(n[1],(0,fu.getLocale)(t))}function yu(t,e){return t[1]-e[1]}function mu(t,e){return e[1]?-1:1}function wu(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=gu.bind(null,t.language);break;case"number":r=yu.bind(null);break;case"boolean":r=mu.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function Su(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function bu(t,e,n){if(!t.enabled)throw(0,Dn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,Dn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return Mn(t,r),zs(t),e.sort((o,c)=>{let u=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),l=typeof u<"u",d=typeof a<"u";return!l&&!d?0:l?d?s?a-u:u-a:-1:1}),e}function Iu(t){return t.enabled?t.sortableProperties:[]}function xu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Vs(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,l])=>[+a,l])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Ws(t){if(!t.enabled)return{enabled:!1};_u(t),zs(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function Eu(){return{create:hu,insert:pu,remove:Su,save:Ws,load:Vs,sortBy:bu,getSortableProperties:Iu,getSortablePropertiesWithTypes:xu}}});var Hs=b(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.replaceDiacritics=Du;var Ks=192,Au=383,vu=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Tu(t){return tAu?t:vu[t-Ks]||t}function Du(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.stemmer=Nu;var Mu={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Ou={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Pu="[^aeiou]",St="[aeiouy]",J=Pu+"[^aeiouy]*",Ge=St+"[aeiou]*",kn="^("+J+")?"+Ge+J,ku="^("+J+")?"+Ge+J+"("+Ge+")?$",_t="^("+J+")?"+Ge+J+Ge+J,Gs="^("+J+")?"+St;function Nu(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(kn),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(Gs),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+J+St+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Gs),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(kn),e&&r.test(e)&&(t=e+Mu[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(kn),e&&r.test(e)&&(t=e+Ou[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(_t),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(_t),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(_t),s=new RegExp(ku),i=new RegExp("^"+J+St+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(_t),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var It=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.normalizeToken=Un;bt.createTokenizer=ju;var xe=j(),Uu=Hs(),Xs=lt(),Lu=Ys();function Un(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,Uu.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function Ru(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function Js(t,e,n,r=!0){if(e&&e!==this.language)throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=Xs.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=Ru(i);return this.allowDuplicates?o:Array.from(new Set(o))}function ju(t={}){if(!t.language)t.language="english";else if(!Xs.SUPPORTED_LANGUAGES.includes(t.language))throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,xe.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=Lu.stemmer;else throw(0,xe.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Js,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Un,normalizationCache:new Map};return r.tokenize=Js.bind(r),r.normalizeToken=Un,r}});var Ln=b(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.getMatchingRules=Zs;ke.load=Qs;ke.save=ei;ke.createPinning=Ku;function Fu(t){return{sharedInternalDocumentStore:t,rules:new Map}}function Cu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function Bu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function qu(t,e){return t.rules.delete(e)}function $u(t,e){return t.rules.get(e)}function zu(t){return Array.from(t.rules.values())}function Vu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Wu(t,e){return t?e.conditions.every(n=>Vu(t,n)):!1}function Zs(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Wu(e,r)&&n.push(r);return n}function Qs(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function ei(t){return{rules:Array.from(t.rules.entries())}}function Ku(){return{create:Fu,addRule:Cu,updateRule:Bu,removeRule:qu,getRule:$u,getAllRules:zu,getMatchingRules:Zs,load:Qs,save:ei}}});var ri=b(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.create=ea;var xt=Be(),Hu=pn(),ti=fs(),Et=Q(),Gu=mt(),Yu=$(),Ju=On(),ni=It(),Xu=Ln(),At=j(),Zu=L();function Qu(t){let e={formatElapsedTime:xt.formatElapsedTime,getDocumentIndexId:xt.getDocumentIndexId,getDocumentProperties:xt.getDocumentProperties,validateSchema:xt.validateSchema};for(let n of Et.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,At.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Et.OBJECT_COMPONENTS.includes(n)&&!Et.FUNCTION_COMPONENTS.includes(n))throw(0,At.createError)("UNSUPPORTED_COMPONENT",n)}function ea({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,At.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,Zu.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,l=r.pinning;if(o?o.tokenize?o=o:o=(0,ni.createTokenizer)(o):o=(0,ni.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,At.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let d=(0,Yu.createInternalDocumentIDStore)();c||=(0,Gu.createIndex)(),a||=(0,Ju.createSorter)(),u||=(0,Hu.createDocumentsStore)(),l||=(0,Xu.createPinning)(),Qu(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:l,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:ta()};h.data={index:h.index.create(h,d,t),docs:h.documentsStore.create(h,d),sorting:h.sorter.create(h,d,t,e),pinning:h.pinning.create(d)};for(let w of ti.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,ti.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,Et.runAfterCreate)(m,h),h}function ta(){return"{{VERSION}}"}});var jn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getByID=na;vt.count=ra;function na(t,e){return t.documentsStore.get(t.data.docs,e)}function ra(t){return t.documentsStore.count(t.data.docs)}});var Fn=b(U=>{"use strict";var si=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sa=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ia=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&si(e,t,n)},Ye=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.insert=qn;Je.insertMultiple=fa;Je.innerInsertMultiple=ha;var Cn=Fn(),C=L(),Ne=Q(),Ue=j(),Bn=$();function qn(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Ue.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ua(t,e,n,r,s):aa(t,e,n,r,s)}var oa=new Set(["enum","enum[]"]),ca=new Set(["string","number"]);async function ua(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ii(y,h,p,g)}return await la(t,c,l,f,a,n,e,s),r||await(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function aa(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ii(y,h,p,g)}return da(t,c,l,f,a,n,e,s),r||(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function ii(t,e,n,r){if(!((0,Cn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,Cn.isVectorType)(e)&&Array.isArray(r))&&!((0,Cn.isArrayType)(e)&&Array.isArray(r))&&!(oa.has(e)&&ca.has(t))&&t!==e)throw(0,Ue.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function la(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l];await t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function da(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l],p=(0,Bn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function fa(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.afterInsertMultiple)||(0,C.isAsyncFunction)(t.beforeInsertMultiple)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?oi(t,e,n,r,s,i):ci(t,e,n,r,s,i)}async function oi(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let l=Math.min(a+n,e.length),d=e.slice(a,l);for(let f of d){let p={avlRebalanceThreshold:d.length},g=await qn(t,f,r,s,p);o.push(g)}return l};return await(async()=>{let a=0;for(;a0){let d=Date.now()-l,f=i-d;f>0&&(0,C.sleep)(f)}}})(),s||await(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ci(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let l=e.slice(c*n,(c+1)*n);if(l.length===0)return!1;for(let d of l){let f={avlRebalanceThreshold:l.length},p=qn(t,d,r,s,f);o.push(p)}return c++,!0}function a(){let l=Date.now();for(;u();)if(i>0){let f=Date.now()-l;if(f>=i){let p=i-f%i;p>0&&(0,C.sleep)(p)}}}return a(),s||(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ha(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?oi(t,e,n,r,s,i):ci(t,e,n,r,s,i)}});var ui=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.insertPin=pa;Ee.updatePin=ga;Ee.deletePin=ya;Ee.getPin=ma;Ee.getAllPins=wa;function pa(t,e){t.pinning.addRule(t.data.pinning,e)}function ga(t,e){t.pinning.updateRule(t.data.pinning,e)}function ya(t,e){return t.pinning.removeRule(t.data.pinning,e)}function ma(t,e){return t.pinning.getRule(t.data.pinning,e)}function wa(t){return t.pinning.getAllRules(t.data.pinning)}});var zn=b(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.remove=$n;Dt.removeMultiple=ba;var de=Q(),fe=$(),le=L();function $n(t,e,n,r){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)?_a(t,e,n,r):Sa(t,e,n,r)}async function _a(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||await(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Sa(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function ba(t,e,n,r,s){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)||(0,le.isAsyncFunction)(t.beforeRemoveMultiple)||(0,le.isAsyncFunction)(t.afterRemoveMultiple)?Ia(t,e,n,r,s):xa(t,e,n,r,s)}async function Ia(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function l(){let d=e.slice(a*n,++a*n);if(!d.length)return c();for(let f of d)try{await $n(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(l,0)}setTimeout(l,0)}),s||await(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function xa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let l of a)$n(t,l,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Vn=b(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.MODE_VECTOR_SEARCH=he.MODE_HYBRID_SEARCH=he.MODE_FULLTEXT_SEARCH=void 0;he.MODE_FULLTEXT_SEARCH="fulltext";he.MODE_HYBRID_SEARCH="hybrid";he.MODE_VECTOR_SEARCH="vector"});var Mt=b(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.getFacets=Ma;var Ea=j(),Aa=L();function va(t,e){return t[1]-e[1]}function Ta(t,e){return e[1]-t[1]}function Da(t="desc"){return t.toLowerCase()==="asc"?va:Ta}function Ma(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let l;if(c[a]==="number"){let{ranges:d}=n[a],f=d.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function li(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Ot=b(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.getGroups=ka;var di=j(),Kn=L(),Oa=$(),Pa={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},fi=["string","number","boolean"];function ka(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,di.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!fi.includes(i[w]))throw(0,di.createError)("INVALID_GROUP_BY_PROPERTY",w,fi.join(", "),i[w])}let o=e.map(([m])=>(0,Oa.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,l=[],d={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}l.push(Array.from(_)),d[w]=S}let f=hi(l),p=f.length,g=[];for(let m=0;mv-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),v=S.getInitialValue(w.indexes.length),D=_.reduce(I,v);h[m]={values:w.values,result:D}}return h}function hi(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=hi(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Kn.safeArrayPush)(c,o),s.push(c)}return s}});var Pt=b(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.applyPinningRules=La;var Na=$(),Ua=Ln();function La(t,e,n,r){let s=(0,Ua.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,Na.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),l=1e6,d=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?d.push([h,l-m]):t.documentsStore.get(t.data.docs,h)&&d.push([h,0]);d.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of d){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var Yn=b(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.defaultBM25Params=void 0;te.innerFullTextSearch=yi;te.fullTextSearch=Wa;var Ra=Mt(),ja=Ot(),pi=Q(),Fa=$(),Ca=mt(),Ba=Pt(),qa=j(),kt=L(),$a=jn(),gi=Xe();function yi(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let d=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>d[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let d of s)if(!o.includes(d))throw(0,qa.createError)("UNKNOWN_INDEX",d,o.join(", "));o=o.filter(d=>s.includes(d))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,l=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let d=(0,$a.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},Ka(e.relevance),d,u,l),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=Va(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${za(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let d=(0,Ca.searchByGeoWhereClause)(i,e.where);d?a=d:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function za(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Va(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Wa(t,e,n){let r=(0,kt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:l=0,distinctOn:d,includeVectors:f=!1}=e,p=e.preflight===!0,g=yi(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,Fa.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(kt.sortTokenScorePredicate);g=(0,Ba.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=d?(0,gi.fetchDocumentsWithDistinct)(t,g,l,a,d):(0,gi.fetchDocuments)(t,g,l,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,kt.removeVectorsFromHits)(h,c)),u){let m=(0,Ra.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,ja.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,kt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,pi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,pi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}te.defaultBM25Params={k:1.2,b:.75,d:.5};function Ka(t){let e=t??{};return e.k=e.k??te.defaultBM25Params.k,e.b=e.b??te.defaultBM25Params.b,e.d=e.d??te.defaultBM25Params.d,e}});var Rt=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.innerVectorSearch=wi;Lt.searchVector=Za;var Nt=L(),Ha=Mt(),Ut=j(),Ga=Ot(),Ya=$(),mi=Q(),Ja=En(),Xa=Pt();function wi(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Ut.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Ut.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Ut.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Ut.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??Ja.DEFAULT_SIMILARITY,c)}function Za(t,e,n="english"){let r=(0,Nt.getNanosecondsTime)();function s(){let c=wi(t,e,n).sort(Nt.sortTokenScorePredicate);c=(0,Xa.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,Ha.getFacets)(t,c,e.facets));let l=e.vector.property,d=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.innerHybridSearch=bi;Ft.hybridSearch=il;var jt=L(),Qa=Mt(),el=Ot(),tl=Xe(),nl=Yn(),rl=Rt(),_i=Q(),sl=Pt();function bi(t,e,n){let r=ol((0,nl.innerFullTextSearch)(t,e,n)),s=(0,rl.innerVectorSearch)(t,e,n),i=e.hybridWeights;return ul(r,s,e.term??"",i)}function il(t,e,n){let r=(0,jt.getNanosecondsTime)();function s(){let c=bi(t,e,n);c=(0,sl.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,Qa.getFacets)(t,c,e.facets));let l;e.groupBy&&(l=(0,el.getGroups)(t,c,e.groupBy));let d=e.offset??0,f=e.limit??10,p=(0,tl.fetchDocuments)(t,c,d,f).filter(Boolean),g=(0,jt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,jt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...l?{groups:l}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,jt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,_i.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,_i.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function Jn(t){return t[1]}function ol(t){let e=Math.max.apply(Math,t.map(Jn));return t.map(([n,r])=>[n,r/e])}function Si(t,e){return t/e}function cl(t,e){return(n,r)=>n*t+r*e}function ul(t,e,n,r){let s=Math.max.apply(Math,t.map(Jn)),i=Math.max.apply(Math,e.map(Jn)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:al(n),a=new Map,l=t.length,d=cl(c,u);for(let p=0;pg[1]-p[1])}function al(t){return{text:.5,vector:.5}}});var Xe=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.search=gl;Ze.fetchDocumentsWithDistinct=yl;Ze.fetchDocuments=ml;var xi=$(),ll=j(),dl=L(),Ct=Vn(),fl=Yn(),hl=Rt(),pl=Ii();function gl(t,e,n){let r=e.mode??Ct.MODE_FULLTEXT_SEARCH;if(r===Ct.MODE_FULLTEXT_SEARCH)return(0,fl.fullTextSearch)(t,e,n);if(r===Ct.MODE_VECTOR_SEARCH)return(0,hl.searchVector)(t,e);if(r===Ct.MODE_HYBRID_SEARCH)return(0,pl.hybridSearch)(t,e);throw(0,ll.createError)("INVALID_SEARCH_MODE",r)}function yl(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,l=0;for(let d=0;d"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,dl.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),l++,!(l<=n)&&(c.push({id:(0,xi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),l>=n+r)))break}return c}function ml(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,l]=u;if(!o.has(a)){let d=t.documentsStore.get(s,a);i[c]={id:(0,xi.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:l,document:d},o.add(a)}}return i}});var Ei=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.load=wl;Bt.save=_l;function wl(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function _l(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var Xn=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.update=Sl;zt.updateMultiple=xl;var pe=Q(),Ai=j(),qt=Tt(),$t=zn(),F=L();function Sl(t,e,n,r,s){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)?bl(t,e,n,r,s):Il(t,e,n,r,s)}async function bl(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,pe.runSingleHook)(t.beforeUpdate,t,e),await(0,$t.remove)(t,e,r,s);let i=await(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function Il(t,e,n,r,s){!s&&t.beforeUpdate&&(0,pe.runSingleHook)(t.beforeUpdate,t,e),(0,$t.remove)(t,e,r,s);let i=(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function xl(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)||(0,F.isAsyncFunction)(t.beforeUpdateMultiple)||(0,F.isAsyncFunction)(t.afterUpdateMultiple)||(0,F.isAsyncFunction)(t.beforeRemoveMultiple)||(0,F.isAsyncFunction)(t.afterRemoveMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.afterInsertMultiple)?El(t,e,n,r,s,i):Al(t,e,n,r,s,i)}async function El(t,e,n,r,s,i){i||await(0,pe.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.upsert=vl;Kt.upsertMultiple=Ml;var ge=Q(),Le=j(),Vt=Tt(),Wt=Xn(),P=L();function vl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Tl(t,e,n,r,s):Dl(t,e,n,r,s)}async function Tl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Wt.update)(t,i,e,n,r):c=await(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Dl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Wt.update)(t,i,e,n,r):c=(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ml(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Ol(t,e,n,r,s):Pl(t,e,n,r,s)}async function Ol(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=await(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=await(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&await(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function Pl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var Ti=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AnswerSession=void 0;var Ht=j(),kl=Xe(),Nl="orama-secure-proxy",Zn=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,Ht.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,kl.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===Nl)}let r=await n();if(!r)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};Gt.AnswerSession=Zn});var Di=b(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.kRemovals=H.kInsertions=H.MODE_VECTOR_SEARCH=H.MODE_HYBRID_SEARCH=H.MODE_FULLTEXT_SEARCH=void 0;var Qn=Vn();Object.defineProperty(H,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_FULLTEXT_SEARCH}});Object.defineProperty(H,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_HYBRID_SEARCH}});Object.defineProperty(H,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return Qn.MODE_VECTOR_SEARCH}});H.kInsertions=Symbol("orama.insertions");H.kRemovals=Symbol("orama.removals")});var Mi=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var Ul=mn();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return Ul.boundedLevenshtein}});var ne=L();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return ne.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return ne.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return ne.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return ne.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return ne.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return ne.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return ne.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return ne.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return ne.setDifference}});var Ll=It();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return Ll.normalizeToken}})});var Fi=b(x=>{"use strict";var Oi=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Rl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Oi(e,t,n)},Pi=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.utf8Count=$l;re.utf8EncodeJs=Ci;re.utf8EncodeTE=Bi;re.utf8Encode=Wl;re.utf8DecodeJs=qi;re.utf8DecodeTD=$i;re.utf8Decode=Yl;function $l(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var zl=new TextEncoder,Vl=50;function Bi(t,e,n){zl.encodeInto(t,e.subarray(n))}function Wl(t,e,n){t.length>Vl?Bi(t,e,n):Ci(t,e,n)}var Kl=4096;function qi(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(c);i.length>=Kl&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var Hl=new TextDecoder,Gl=200;function $i(t,e,n){let r=t.subarray(e,e+n);return Hl.decode(r)}function Yl(t,e,n){return n>Gl?$i(t,e,n):qi(t,e,n)}});var tr=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.ExtData=void 0;var er=class{type;data;constructor(e,n){this.type=e,this.data=n}};Jt.ExtData=er});var Zt=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DecodeError=void 0;var nr=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Xt.DecodeError=nr});var Qt=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.UINT32_MAX=void 0;ye.setUint64=Jl;ye.setInt64=Xl;ye.getInt64=Zl;ye.getUint64=Ql;ye.UINT32_MAX=4294967295;function Jl(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xl(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zl(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Ql(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var rr=b(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.timestampExtension=G.EXT_TIMESTAMP=void 0;G.encodeTimeSpecToTimestamp=Vi;G.encodeDateToTimeSpec=Wi;G.encodeTimestampExtension=Ki;G.decodeTimestampToTimeSpec=Hi;G.decodeTimestampExtension=Gi;var ed=Zt(),zi=Qt();G.EXT_TIMESTAMP=-1;var td=4294967296-1,nd=17179869184-1;function Vi({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=nd)if(e===0&&t<=td){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,zi.setInt64)(r,4,t),n}}function Wi(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Ki(t){if(t instanceof Date){let e=Wi(t);return Vi(e)}else return null}function Hi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,zi.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ed.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Gi(t){let e=Hi(t);return new Date(e.sec*1e3+e.nsec/1e6)}G.timestampExtension={type:G.EXT_TIMESTAMP,encode:Ki,decode:Gi}});var nn=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ExtensionCodec=void 0;var en=tr(),rd=rr(),sr=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(rd.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.ensureUint8Array=id;function sd(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function id(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):sd(t)?new Uint8Array(t):Uint8Array.from(t)}});var ur=b(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.Encoder=X.DEFAULT_INITIAL_BUFFER_SIZE=X.DEFAULT_MAX_DEPTH=void 0;var Yi=Yt(),od=nn(),Ji=Qt(),cd=or();X.DEFAULT_MAX_DEPTH=100;X.DEFAULT_INITIAL_BUFFER_SIZE=2048;var cr=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??od.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??X.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??X.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Yi.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Yi.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,cd.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Ji.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Ji.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};X.Encoder=cr});var Xi=b(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.encode=ad;var ud=ur();function ad(t,e){return new ud.Encoder(e).encodeSharedRef(t)}});var Zi=b(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.prettyByte=ld;function ld(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var Qi=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CachedKeyDecoder=void 0;var dd=Yt(),fd=16,hd=16,dr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=fd,n=hd){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,dd.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};rn.CachedKeyDecoder=dr});var on=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.Decoder=void 0;var fr=Zi(),pd=nn(),Ae=Qt(),gd=Yt(),eo=or(),yd=Qi(),se=Zt(),hr="array",tt="map_key",no="map_value",md=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new se.DecodeError("The type of key must be string or number but "+typeof t)},pr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=hr,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=tt,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===hr){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===tt||e.type===no){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},et=-1,yr=new DataView(new ArrayBuffer(0)),wd=new Uint8Array(yr.buffer);try{yr.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var to=new RangeError("Insufficient data"),_d=new yd.CachedKeyDecoder,gr=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=yr;bytes=wd;headByte=et;stack=new pr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ae.UINT32_MAX,this.maxBinLength=e?.maxBinLength??Ae.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??Ae.UINT32_MAX,this.maxMapLength=e?.maxMapLength??Ae.UINT32_MAX,this.maxExtLength=e?.maxExtLength??Ae.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:_d,this.mapKeyConverter=e?.mapKeyConverter??md}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=et,this.stack.reset()}setBuffer(e){let n=(0,eo.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===et&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,eo.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,fr.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new se.DecodeError(`Unrecognized type byte: ${(0,fr.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===hr)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===tt){if(n==="__proto__")throw new se.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=no;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=tt;continue e}}return n}}readHeadByte(){return this.headByte===et&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=et}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new se.DecodeError(`Unrecognized array type byte: ${(0,fr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new se.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new se.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new se.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===tt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new se.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw to;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new se.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,Ae.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,Ae.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};sn.Decoder=gr});var so=b(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.decode=Sd;cn.decodeMulti=bd;var ro=on();function Sd(t,e){return new ro.Decoder(e).decode(t)}function bd(t,e){return new ro.Decoder(e).decodeMulti(t)}});var co=b(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.isAsyncIterable=io;nt.asyncIterableFromStream=oo;nt.ensureAsyncIterable=Id;function io(t){return t[Symbol.asyncIterator]!=null}async function*oo(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function Id(t){return io(t)?t:oo(t)}});var uo=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.decodeAsync=xd;rt.decodeArrayStream=Ed;rt.decodeMultiStream=Ad;var mr=on(),wr=co();async function xd(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeAsync(n)}function Ed(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeArrayStream(n)}function Ad(t,e){let n=(0,wr.ensureAsyncIterable)(t);return new mr.Decoder(e).decodeStream(n)}});var lo=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var vd=Xi();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return vd.encode}});var ao=so();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return ao.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return ao.decodeMulti}});var _r=uo();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return _r.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return _r.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return _r.decodeMultiStream}});var Td=on();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return Td.Decoder}});var Dd=Zt();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return Dd.DecodeError}});var Md=ur();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return Md.Encoder}});var Od=nn();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return Od.ExtensionCodec}});var Pd=tr();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return Pd.ExtData}});var Re=rr();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Re.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Re.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Re.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Re.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return Re.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return Re.decodeTimestampExtension}})});var Ir=b(($h,yo)=>{"use strict";var q=require("fs"),Z=Fi(),{encode:kd,decode:Nd}=lo(),Sr=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function fo(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function Ud(t){let e=fo(t);return Z.create({schema:e})}function Ld(t){for(let e of Sr)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function Rd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");Ld(e);let n={};for(let r of Sr)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return Z.insert(t,n)}async function jd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return ho(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function ho(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await Z.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await Z.removeMultiple(t,r)}function br(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function Fd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await Z.search(t,s)).hits.map(br)}async function Cd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await Z.search(t,i)).hits.map(br)}async function Bd(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await Z.search(t,u)).hits.map(br)}async function qd(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=Z.save(t),r={v:1,schema:t.schema,raw:n},s=kd(r),i=e+".tmp";q.writeFileSync(i,s),q.renameSync(i,e)}async function $d(t){if(!t)throw new Error("loadStore: storePath is required");if(!q.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=q.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=Nd(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await Z.create({schema:n.schema});return Z.load(r,n.raw),r}var zd=3e4,Vd=50,Wd=1e4;function Kd(t){try{let e=q.openSync(t,"wx");return q.writeSync(e,String(process.pid)),q.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function Hd(t){return new Promise(e=>setTimeout(e,t))}async function po(t){let e=Date.now()+Wd;for(;;){if(Kd(t))return;try{let n=q.statSync(t);if(Date.now()-n.mtimeMs>zd){try{q.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await Hd(Vd)}}function go(t){try{q.unlinkSync(t)}catch{}}async function Gd(t,e){await po(t);try{return await e()}finally{go(t)}}var Yd=["provider","model","dimensions","last_indexed","pending"];function Jd(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";q.writeFileSync(r,JSON.stringify(n,null,2)+` -`,"utf8"),q.renameSync(r,t)}function Xd(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!q.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=q.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}yo.exports={SCHEMA_FIELDS:Sr,METADATA_FIELDS:Yd,buildSchema:fo,createStore:Ud,insertDocument:Rd,removeByIdentity:jd,removeByFilter:ho,searchFulltext:Fd,searchVector:Cd,searchHybrid:Bd,saveStore:qd,loadStore:$d,acquireLock:po,releaseLock:go,withLock:Gd,writeMetadata:Jd,readMetadata:Xd}});var bo=b((zh,So)=>{"use strict";var Zd=/^\s*(```+|~~~+)/,mo=/^---\s*$/;function Qd(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` +`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function Uc(t,...e){let n=new Error((0,Pc.sprintf)(Nc[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var Be=b(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.getDocumentProperties=void 0;W.formatElapsedTime=Rc;W.getDocumentIndexId=jc;W.validateSchema=Jr;W.isGeoPointType=Bc;W.isVectorType=Xr;W.isArrayType=Zr;W.getInnerType=Qr;W.getVectorSize=es;var dt=j(),Yr=L(),Lc=L();Object.defineProperty(W,"getDocumentProperties",{enumerable:!0,get:function(){return Lc.getDocumentProperties}});function Rc(t){return{raw:Number(t),formatted:(0,Yr.formatNanoseconds)(t)}}function jc(t){if(t.id){if(typeof t.id!="string")throw(0,dt.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,Yr.uniqueId)()}function Jr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.createInternalDocumentIDStore=qc;be.save=ts;be.load=ns;be.getInternalDocumentId=rs;be.getDocumentIdFromInternalId=$c;function qc(){return{idToInternalId:new Map,internalIdToId:[],save:ts,load:ns}}function ts(t){return{internalIdToId:t.internalIdToId}}function ns(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?rs(t,e.toString()):e}function $c(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.create=ss;K.get=is;K.getMultiple=os;K.getAll=cs;K.store=us;K.remove=as;K.count=ls;K.load=ds;K.save=fs;K.createDocumentsStore=zc;var pn=$();function ss(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function is(t,e){let n=(0,pn.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function os(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function ls(t){return t.count}function ds(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function fs(t){return{docs:t.docs,count:t.count}}function zc(){return{create:ss,get:is,getMultiple:os,getAll:cs,store:us,remove:as,count:ls,load:ds,save:fs}}});var hs=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.AVAILABLE_PLUGIN_HOOKS=void 0;qe.getAllPluginsByHook=Wc;var Vc=j();qe.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function Wc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.SINGLE_OR_ARRAY_COMPONENTS=z.FUNCTION_COMPONENTS=z.OBJECT_COMPONENTS=void 0;z.runSingleHook=Kc;z.runMultipleHook=Hc;z.runAfterSearch=Gc;z.runBeforeSearch=Yc;z.runAfterCreate=Jc;var $e=L();z.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];z.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];z.SINGLE_OR_ARRAY_COMPONENTS=[];function Kc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Hc(t,e,n){if(t.some($e.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function Gc(t,e,n,r,s){if(t.some($e.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function Yc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Jc(t,e){if(t.some($e.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var ps=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.AVLTree=Me.AVLNode=void 0;var ue=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Me.AVLNode=ue;var yn=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ue(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ue.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ue(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ue(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:l,node:d}=i[a];if(d.updateHeight(),u){let f=this.rebalanceNode(d);l?l.l===d?l.l=f:l.r===d&&(l.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Me.AVLTree=yn});var gs=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FlatTree=void 0;var mn=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ft.FlatTree=mn});var wn=b(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.boundedLevenshtein=Xc;ze.syncBoundedLevenshtein=Zc;ze.levenshtein=Qc;function ys(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function Xc(t,e,n){let r=ys(t,e,n);return{distance:r,isBounded:r>=0}}function Zc(t,e,n){let r=ys(t,e,n);return{distance:r,isBounded:r>=0}}function Qc(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var ws=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.RadixTree=Oe.RadixNode=void 0;var ms=wn(),_n=L(),Ve=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,_n.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,ms.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,_n.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let l of u)a.includes(l)||a.push(l)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:d,d:f}=c;if(d&&((0,ms.syncBoundedLevenshtein)(e,d,s).isBounded&&(i[d]=[]),(0,_n.getOwnProperty)(i,d)!==void 0&&f.size>0)){let p=new Set(i[d]);for(let g of f)p.add(g);i[d]=Array.from(p)}}if(u>=e.length)continue;let l=e[u];if(c.c.has(l)){let d=c.c.get(l);o.push({node:d,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[d,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),d!==l&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};Oe.RadixNode=Ve;var Sn=class t extends Ve{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,Ve.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};Oe.RadixTree=Sn});var _s=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.BKDTree=void 0;var eu=2,tu=6371e3,ht=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},bn=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ht(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%eu===0)if(e.lon0;){let{node:a,depth:l}=c.pop();if(a==null)continue;let d=o(e,a.point);(r?d<=n:d>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:l+1}),a.right!=null&&c.push({node:a.right,depth:l+1})}return s&&u.sort((a,l)=>{let d=o(e,a.point),f=o(e,l.point);return s.toLowerCase()==="asc"?d-f:f-d}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let l=t.isPointInPolygon(e,u.point);(l&&n||!l&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,l)=>{let d=u(c,a.point),f=u(c,l.point);return r.toLowerCase()==="asc"?d-f:f-d})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ht.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(d-a)*(i-l)/(f-l)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return tu*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,l=Math.atan((1-s)*Math.tan(c)),d=Math.atan((1-s)*Math.tan(u)),f=Math.sin(l),p=Math.cos(l),g=Math.sin(d),y=Math.cos(d),h=a,m,w=1e3,S,_,I,v,D,A;do{let De=Math.sin(h),Ce=Math.cos(h);if(S=Math.sqrt(y*De*(y*De)+(p*g-f*y*Ce)*(p*g-f*y*Ce)),S===0)return 0;_=f*g+p*y*Ce,I=Math.atan2(S,_),v=p*y*De/S,D=1-v*v,A=_-2*f*g/D,isNaN(A)&&(A=0);let dn=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-dn)*s*v*(I+dn*S*(A+dn*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),Te=1+k/16384*(4096+k*(-768+k*(320-175*k))),J=k/1024*(256+k*(-128+k*(74-47*k))),ln=J*S*(A+J/4*(_*(-1+2*A*A)-J/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*Te*(I-ln)}};pt.BKDTree=bn});var Ss=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.BoolNode=void 0;var In=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};gt.BoolNode=In});var bs=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.prioritizeTokenScores=ru;yt.BM25=su;var nu=j();function ru(t,e,n=0,r){if(e===0)throw(0,nu.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let l=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];d=0}let f=l.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.VectorIndex=ae.DEFAULT_SIMILARITY=void 0;ae.getMagnitude=En;ae.findSimilarVectors=Is;ae.DEFAULT_SIMILARITY=.8;var xn=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=En(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),Is(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};ae.VectorIndex=xn;function En(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var mt=b(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.insertDocumentScoreParameters=Ps;R.insertTokenScoreParameters=ks;R.removeDocumentScoreParameters=Ns;R.removeTokenScoreParameters=Us;R.create=Tn;R.insert=Ls;R.insertVector=Rs;R.remove=js;R.calculateResultScores=Dn;R.search=Fs;R.searchByWhereClause=We;R.getSearchableProperties=Cs;R.getSearchablePropertiesWithTypes=Bs;R.load=qs;R.save=$s;R.createIndex=cu;R.searchByGeoWhereClause=au;var Pe=j(),vs=ps(),Ts=gs(),Ds=ws(),Ke=_s(),Ms=Ss(),te=L(),iu=bs(),Ie=Be(),vn=$(),Os=An();function Ps(t,e,n,r,s){let i=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function ks(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function Ns(t,e,n,r){let s=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function Us(t,e,n){t.tokenOccurrences[e][n]--}function Tn(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){Tn(t,e,o,r,c);continue}if((0,Ie.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new Os.VectorIndex((0,Ie.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new Ms.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new vs.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new Ds.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new Ts.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new Ke.BKDTree,isArray:u};break;default:throw(0,Pe.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function ou(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:l}=e.indexes[n];switch(a){case"Bool":{l[u?"true":"false"].add(r);break}case"AVL":{let d=c?.avlRebalanceThreshold??1;l.insert(u,r,d);break}case"Radix":{let d=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,d,o);for(let f of d)t.insertTokenScoreParameters(e,n,r,d,f),l.insert(f,r);break}case"Flat":{l.insert(u,r);break}case"BKD":{l.insert(u,[r]);break}}}}function Ls(t,e,n,r,s,i,o,c,u,a,l){if((0,Ie.isVectorType)(o))return Rs(e,n,i,r,s);let d=ou(t,e,n,s,c,u,a,l);if(!(0,Ie.isArrayType)(o))return d(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let ln=J.length;for(let at=0;at[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(d===1)return m;if(d===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(v=>v===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([v])=>v===I)),_=Math.ceil(S.length*d);return[...w,...S.slice(0,_)]}return m}function We(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>We(t,e,u,r));return(0,te.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>We(t,e,u,r)).reduce((u,a)=>(0,te.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let l=1;l<=u.internalIdToId.length;l++)c.add(l);let a=We(t,e,o,r);return(0,te.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,Pe.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:l}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,te.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,te.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=Es(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=Es(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=lu(i[o],y)}}continue}let d=Object.keys(c);if(d.length>1)throw(0,Pe.createError)("INVALID_FILTER_OPERATION",d.length);if(a==="Flat"){let f=new Set(l?u.filterArr(c):u.filter(c));i[o]=(0,te.setUnion)(i[o],f);continue}if(a==="AVL"){let f=d[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,Pe.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,te.setUnion)(i[o],g)}}return(0,te.setIntersection)(...Object.values(i))}function Cs(t){return t.searchableProperties}function Bs(t){return t.searchablePropertiesWithTypes}function qs(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,l={},d={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":l[f]={type:"Radix",node:Ds.RadixTree.fromJSON(p),isArray:y};break;case"Flat":l[f]={type:"Flat",node:Ts.FlatTree.fromJSON(p),isArray:y};break;case"AVL":l[f]={type:"AVL",node:vs.AVLTree.fromJSON(p),isArray:y};break;case"BKD":l[f]={type:"BKD",node:Ke.BKDTree.fromJSON(p),isArray:y};break;case"Bool":l[f]={type:"Bool",node:Ms.BoolNode.fromJSON(p),isArray:y};break;default:l[f]=n[f]}}for(let f of Object.keys(r))d[f]={type:"Vector",isArray:!1,node:Os.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:l,vectorIndexes:d,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function $s(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let d of Object.keys(n))a[d]=n[d].node.toJSON();let l={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:g}=e[d];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?l[d]={type:f,node:p.toJSON(),isArray:g}:(l[d]=e[d],l[d].node=l[d].node.toJSON())}return{indexes:l,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function cu(){return{create:Tn,insert:Ls,remove:js,insertDocumentScoreParameters:Ps,insertTokenScoreParameters:ks,removeDocumentScoreParameters:Ns,removeTokenScoreParameters:Us,calculateResultScores:Dn,search:Fs,searchByWhereClause:We,getSearchableProperties:Cs,getSearchablePropertiesWithTypes:Bs,load:qs,save:$s}}function Es(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function uu(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function au(t,e){let n=t,r=uu(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:l="m",inside:d=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,te.convertDistanceToMeters)(u,l);return c=o.searchByRadius(p,g,d,"asc",f),As(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:l=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",l);let d=Ke.BKDTree.calculatePolygonCentroid(u);return As(c,d,l)}return null}function lu(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.load=Ws;He.save=Ks;He.createSorter=Au;var Mn=j(),du=Be(),wt=$(),fu=L(),hu=lt();function zs(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=zs(t,e,c,r,u);(0,fu.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,du.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,Mn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function pu(t,e,n,r){return r?.enabled!==!1?zs(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function gu(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&On(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function Vs(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)_u(t,n);t.isSorted=!0}function yu(t,e,n){return e[1].localeCompare(n[1],(0,hu.getLocale)(t))}function mu(t,e){return t[1]-e[1]}function wu(t,e){return e[1]?-1:1}function _u(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=yu.bind(null,t.language);break;case"number":r=mu.bind(null);break;case"boolean":r=wu.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function bu(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function Iu(t,e,n){if(!t.enabled)throw(0,Mn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,Mn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return On(t,r),Vs(t),e.sort((o,c)=>{let u=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),l=typeof u<"u",d=typeof a<"u";return!l&&!d?0:l?d?s?a-u:u-a:-1:1}),e}function xu(t){return t.enabled?t.sortableProperties:[]}function Eu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Ws(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,l])=>[+a,l])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Ks(t){if(!t.enabled)return{enabled:!1};Su(t),Vs(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function Au(){return{create:pu,insert:gu,remove:bu,save:Ks,load:Ws,sortBy:Iu,getSortableProperties:xu,getSortablePropertiesWithTypes:Eu}}});var Gs=b(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.replaceDiacritics=Mu;var Hs=192,vu=383,Tu=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Du(t){return tvu?t:Tu[t-Hs]||t}function Mu(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.stemmer=Uu;var Ou={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Pu={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},ku="[^aeiou]",St="[aeiouy]",X=ku+"[^aeiouy]*",Ge=St+"[aeiou]*",Nn="^("+X+")?"+Ge+X,Nu="^("+X+")?"+Ge+X+"("+Ge+")?$",_t="^("+X+")?"+Ge+X+Ge+X,Ys="^("+X+")?"+St;function Uu(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(Nn),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(Ys),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+X+St+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Ys),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Nn),e&&r.test(e)&&(t=e+Ou[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Nn),e&&r.test(e)&&(t=e+Pu[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(_t),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(_t),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(_t),s=new RegExp(Nu),i=new RegExp("^"+X+St+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(_t),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var It=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.normalizeToken=Ln;bt.createTokenizer=Fu;var xe=j(),Lu=Gs(),Zs=lt(),Ru=Js();function Ln(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,Lu.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function ju(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function Xs(t,e,n,r=!0){if(e&&e!==this.language)throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=Zs.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=ju(i);return this.allowDuplicates?o:Array.from(new Set(o))}function Fu(t={}){if(!t.language)t.language="english";else if(!Zs.SUPPORTED_LANGUAGES.includes(t.language))throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,xe.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=Ru.stemmer;else throw(0,xe.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Xs,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Ln,normalizationCache:new Map};return r.tokenize=Xs.bind(r),r.normalizeToken=Ln,r}});var Rn=b(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.getMatchingRules=Qs;ke.load=ei;ke.save=ti;ke.createPinning=Hu;function Cu(t){return{sharedInternalDocumentStore:t,rules:new Map}}function Bu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function qu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function $u(t,e){return t.rules.delete(e)}function zu(t,e){return t.rules.get(e)}function Vu(t){return Array.from(t.rules.values())}function Wu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Ku(t,e){return t?e.conditions.every(n=>Wu(t,n)):!1}function Qs(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Ku(e,r)&&n.push(r);return n}function ei(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function ti(t){return{rules:Array.from(t.rules.entries())}}function Hu(){return{create:Cu,addRule:Bu,updateRule:qu,removeRule:$u,getRule:zu,getAllRules:Vu,getMatchingRules:Qs,load:ei,save:ti}}});var si=b(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.create=ta;var xt=Be(),Gu=gn(),ni=hs(),Et=ee(),Yu=mt(),Ju=$(),Xu=Pn(),ri=It(),Zu=Rn(),At=j(),Qu=L();function ea(t){let e={formatElapsedTime:xt.formatElapsedTime,getDocumentIndexId:xt.getDocumentIndexId,getDocumentProperties:xt.getDocumentProperties,validateSchema:xt.validateSchema};for(let n of Et.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,At.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Et.OBJECT_COMPONENTS.includes(n)&&!Et.FUNCTION_COMPONENTS.includes(n))throw(0,At.createError)("UNSUPPORTED_COMPONENT",n)}function ta({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,At.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,Qu.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,l=r.pinning;if(o?o.tokenize?o=o:o=(0,ri.createTokenizer)(o):o=(0,ri.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,At.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let d=(0,Ju.createInternalDocumentIDStore)();c||=(0,Yu.createIndex)(),a||=(0,Xu.createSorter)(),u||=(0,Gu.createDocumentsStore)(),l||=(0,Zu.createPinning)(),ea(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:l,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:na()};h.data={index:h.index.create(h,d,t),docs:h.documentsStore.create(h,d),sorting:h.sorter.create(h,d,t,e),pinning:h.pinning.create(d)};for(let w of ni.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,ni.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,Et.runAfterCreate)(m,h),h}function na(){return"{{VERSION}}"}});var Fn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getByID=ra;vt.count=sa;function ra(t,e){return t.documentsStore.get(t.data.docs,e)}function sa(t){return t.documentsStore.count(t.data.docs)}});var Cn=b(U=>{"use strict";var ii=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ia=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),oa=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ii(e,t,n)},Ye=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.insert=$n;Je.insertMultiple=ha;Je.innerInsertMultiple=pa;var Bn=Cn(),C=L(),Ne=ee(),Ue=j(),qn=$();function $n(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Ue.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?aa(t,e,n,r,s):la(t,e,n,r,s)}var ca=new Set(["enum","enum[]"]),ua=new Set(["string","number"]);async function aa(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];oi(y,h,p,g)}return await da(t,c,l,f,a,n,e,s),r||await(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function la(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];oi(y,h,p,g)}return fa(t,c,l,f,a,n,e,s),r||(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function oi(t,e,n,r){if(!((0,Bn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,Bn.isVectorType)(e)&&Array.isArray(r))&&!((0,Bn.isArrayType)(e)&&Array.isArray(r))&&!(ca.has(e)&&ua.has(t))&&t!==e)throw(0,Ue.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function da(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l];await t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function fa(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l],p=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function ha(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.afterInsertMultiple)||(0,C.isAsyncFunction)(t.beforeInsertMultiple)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ci(t,e,n,r,s,i):ui(t,e,n,r,s,i)}async function ci(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let l=Math.min(a+n,e.length),d=e.slice(a,l);for(let f of d){let p={avlRebalanceThreshold:d.length},g=await $n(t,f,r,s,p);o.push(g)}return l};return await(async()=>{let a=0;for(;a0){let d=Date.now()-l,f=i-d;f>0&&(0,C.sleep)(f)}}})(),s||await(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ui(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let l=e.slice(c*n,(c+1)*n);if(l.length===0)return!1;for(let d of l){let f={avlRebalanceThreshold:l.length},p=$n(t,d,r,s,f);o.push(p)}return c++,!0}function a(){let l=Date.now();for(;u();)if(i>0){let f=Date.now()-l;if(f>=i){let p=i-f%i;p>0&&(0,C.sleep)(p)}}}return a(),s||(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function pa(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ci(t,e,n,r,s,i):ui(t,e,n,r,s,i)}});var ai=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.insertPin=ga;Ee.updatePin=ya;Ee.deletePin=ma;Ee.getPin=wa;Ee.getAllPins=_a;function ga(t,e){t.pinning.addRule(t.data.pinning,e)}function ya(t,e){t.pinning.updateRule(t.data.pinning,e)}function ma(t,e){return t.pinning.removeRule(t.data.pinning,e)}function wa(t,e){return t.pinning.getRule(t.data.pinning,e)}function _a(t){return t.pinning.getAllRules(t.data.pinning)}});var Vn=b(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.remove=zn;Dt.removeMultiple=Ia;var de=ee(),fe=$(),le=L();function zn(t,e,n,r){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)?Sa(t,e,n,r):ba(t,e,n,r)}async function Sa(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||await(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function ba(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Ia(t,e,n,r,s){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)||(0,le.isAsyncFunction)(t.beforeRemoveMultiple)||(0,le.isAsyncFunction)(t.afterRemoveMultiple)?xa(t,e,n,r,s):Ea(t,e,n,r,s)}async function xa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function l(){let d=e.slice(a*n,++a*n);if(!d.length)return c();for(let f of d)try{await zn(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(l,0)}setTimeout(l,0)}),s||await(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function Ea(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let l of a)zn(t,l,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Wn=b(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.MODE_VECTOR_SEARCH=he.MODE_HYBRID_SEARCH=he.MODE_FULLTEXT_SEARCH=void 0;he.MODE_FULLTEXT_SEARCH="fulltext";he.MODE_HYBRID_SEARCH="hybrid";he.MODE_VECTOR_SEARCH="vector"});var Mt=b(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.getFacets=Oa;var Aa=j(),va=L();function Ta(t,e){return t[1]-e[1]}function Da(t,e){return e[1]-t[1]}function Ma(t="desc"){return t.toLowerCase()==="asc"?Ta:Da}function Oa(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let l;if(c[a]==="number"){let{ranges:d}=n[a],f=d.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function di(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Ot=b(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.getGroups=Na;var fi=j(),Hn=L(),Pa=$(),ka={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},hi=["string","number","boolean"];function Na(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,fi.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!hi.includes(i[w]))throw(0,fi.createError)("INVALID_GROUP_BY_PROPERTY",w,hi.join(", "),i[w])}let o=e.map(([m])=>(0,Pa.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,l=[],d={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}l.push(Array.from(_)),d[w]=S}let f=pi(l),p=f.length,g=[];for(let m=0;mv-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),v=S.getInitialValue(w.indexes.length),D=_.reduce(I,v);h[m]={values:w.values,result:D}}return h}function pi(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=pi(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Hn.safeArrayPush)(c,o),s.push(c)}return s}});var Pt=b(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.applyPinningRules=Ra;var Ua=$(),La=Rn();function Ra(t,e,n,r){let s=(0,La.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,Ua.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),l=1e6,d=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?d.push([h,l-m]):t.documentsStore.get(t.data.docs,h)&&d.push([h,0]);d.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of d){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var Jn=b(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.defaultBM25Params=void 0;ne.innerFullTextSearch=mi;ne.fullTextSearch=Ka;var ja=Mt(),Fa=Ot(),gi=ee(),Ca=$(),Ba=mt(),qa=Pt(),$a=j(),kt=L(),za=Fn(),yi=Xe();function mi(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let d=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>d[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let d of s)if(!o.includes(d))throw(0,$a.createError)("UNKNOWN_INDEX",d,o.join(", "));o=o.filter(d=>s.includes(d))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,l=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let d=(0,za.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},Ha(e.relevance),d,u,l),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=Wa(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${Va(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let d=(0,Ba.searchByGeoWhereClause)(i,e.where);d?a=d:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function Va(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wa(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Ka(t,e,n){let r=(0,kt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:l=0,distinctOn:d,includeVectors:f=!1}=e,p=e.preflight===!0,g=mi(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,Ca.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(kt.sortTokenScorePredicate);g=(0,qa.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=d?(0,yi.fetchDocumentsWithDistinct)(t,g,l,a,d):(0,yi.fetchDocuments)(t,g,l,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,kt.removeVectorsFromHits)(h,c)),u){let m=(0,ja.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,Fa.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,kt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,gi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,gi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}ne.defaultBM25Params={k:1.2,b:.75,d:.5};function Ha(t){let e=t??{};return e.k=e.k??ne.defaultBM25Params.k,e.b=e.b??ne.defaultBM25Params.b,e.d=e.d??ne.defaultBM25Params.d,e}});var Rt=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.innerVectorSearch=_i;Lt.searchVector=Qa;var Nt=L(),Ga=Mt(),Ut=j(),Ya=Ot(),Ja=$(),wi=ee(),Xa=An(),Za=Pt();function _i(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Ut.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Ut.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Ut.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Ut.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??Xa.DEFAULT_SIMILARITY,c)}function Qa(t,e,n="english"){let r=(0,Nt.getNanosecondsTime)();function s(){let c=_i(t,e,n).sort(Nt.sortTokenScorePredicate);c=(0,Za.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,Ga.getFacets)(t,c,e.facets));let l=e.vector.property,d=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.innerHybridSearch=Ii;Ft.hybridSearch=ol;var jt=L(),el=Mt(),tl=Ot(),nl=Xe(),rl=Jn(),sl=Rt(),Si=ee(),il=Pt();function Ii(t,e,n){let r=cl((0,rl.innerFullTextSearch)(t,e,n)),s=(0,sl.innerVectorSearch)(t,e,n),i=e.hybridWeights;return al(r,s,e.term??"",i)}function ol(t,e,n){let r=(0,jt.getNanosecondsTime)();function s(){let c=Ii(t,e,n);c=(0,il.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,el.getFacets)(t,c,e.facets));let l;e.groupBy&&(l=(0,tl.getGroups)(t,c,e.groupBy));let d=e.offset??0,f=e.limit??10,p=(0,nl.fetchDocuments)(t,c,d,f).filter(Boolean),g=(0,jt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,jt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...l?{groups:l}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,jt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,Si.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,Si.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function Xn(t){return t[1]}function cl(t){let e=Math.max.apply(Math,t.map(Xn));return t.map(([n,r])=>[n,r/e])}function bi(t,e){return t/e}function ul(t,e){return(n,r)=>n*t+r*e}function al(t,e,n,r){let s=Math.max.apply(Math,t.map(Xn)),i=Math.max.apply(Math,e.map(Xn)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:ll(n),a=new Map,l=t.length,d=ul(c,u);for(let p=0;pg[1]-p[1])}function ll(t){return{text:.5,vector:.5}}});var Xe=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.search=yl;Ze.fetchDocumentsWithDistinct=ml;Ze.fetchDocuments=wl;var Ei=$(),dl=j(),fl=L(),Ct=Wn(),hl=Jn(),pl=Rt(),gl=xi();function yl(t,e,n){let r=e.mode??Ct.MODE_FULLTEXT_SEARCH;if(r===Ct.MODE_FULLTEXT_SEARCH)return(0,hl.fullTextSearch)(t,e,n);if(r===Ct.MODE_VECTOR_SEARCH)return(0,pl.searchVector)(t,e);if(r===Ct.MODE_HYBRID_SEARCH)return(0,gl.hybridSearch)(t,e);throw(0,dl.createError)("INVALID_SEARCH_MODE",r)}function ml(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,l=0;for(let d=0;d"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,fl.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),l++,!(l<=n)&&(c.push({id:(0,Ei.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),l>=n+r)))break}return c}function wl(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,l]=u;if(!o.has(a)){let d=t.documentsStore.get(s,a);i[c]={id:(0,Ei.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:l,document:d},o.add(a)}}return i}});var Ai=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.load=_l;Bt.save=Sl;function _l(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function Sl(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var Zn=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.update=bl;zt.updateMultiple=El;var pe=ee(),vi=j(),qt=Tt(),$t=Vn(),F=L();function bl(t,e,n,r,s){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)?Il(t,e,n,r,s):xl(t,e,n,r,s)}async function Il(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,pe.runSingleHook)(t.beforeUpdate,t,e),await(0,$t.remove)(t,e,r,s);let i=await(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function xl(t,e,n,r,s){!s&&t.beforeUpdate&&(0,pe.runSingleHook)(t.beforeUpdate,t,e),(0,$t.remove)(t,e,r,s);let i=(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function El(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)||(0,F.isAsyncFunction)(t.beforeUpdateMultiple)||(0,F.isAsyncFunction)(t.afterUpdateMultiple)||(0,F.isAsyncFunction)(t.beforeRemoveMultiple)||(0,F.isAsyncFunction)(t.afterRemoveMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.afterInsertMultiple)?Al(t,e,n,r,s,i):vl(t,e,n,r,s,i)}async function Al(t,e,n,r,s,i){i||await(0,pe.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.upsert=Tl;Kt.upsertMultiple=Ol;var ge=ee(),Le=j(),Vt=Tt(),Wt=Zn(),P=L();function Tl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Dl(t,e,n,r,s):Ml(t,e,n,r,s)}async function Dl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Wt.update)(t,i,e,n,r):c=await(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ml(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Wt.update)(t,i,e,n,r):c=(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ol(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Pl(t,e,n,r,s):kl(t,e,n,r,s)}async function Pl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=await(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=await(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&await(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function kl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var Di=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AnswerSession=void 0;var Ht=j(),Nl=Xe(),Ul="orama-secure-proxy",Qn=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,Ht.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,Nl.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===Ul)}let r=await n();if(!r)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};Gt.AnswerSession=Qn});var Mi=b(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.kRemovals=H.kInsertions=H.MODE_VECTOR_SEARCH=H.MODE_HYBRID_SEARCH=H.MODE_FULLTEXT_SEARCH=void 0;var er=Wn();Object.defineProperty(H,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return er.MODE_FULLTEXT_SEARCH}});Object.defineProperty(H,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return er.MODE_HYBRID_SEARCH}});Object.defineProperty(H,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return er.MODE_VECTOR_SEARCH}});H.kInsertions=Symbol("orama.insertions");H.kRemovals=Symbol("orama.removals")});var Oi=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var Ll=wn();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return Ll.boundedLevenshtein}});var re=L();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return re.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return re.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return re.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return re.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return re.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return re.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return re.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return re.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return re.setDifference}});var Rl=It();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return Rl.normalizeToken}})});var Ci=b(x=>{"use strict";var Pi=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Fl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pi(e,t,n)},ki=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.utf8Count=zl;se.utf8EncodeJs=Bi;se.utf8EncodeTE=qi;se.utf8Encode=Kl;se.utf8DecodeJs=$i;se.utf8DecodeTD=zi;se.utf8Decode=Jl;function zl(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var Vl=new TextEncoder,Wl=50;function qi(t,e,n){Vl.encodeInto(t,e.subarray(n))}function Kl(t,e,n){t.length>Wl?qi(t,e,n):Bi(t,e,n)}var Hl=4096;function $i(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(c);i.length>=Hl&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var Gl=new TextDecoder,Yl=200;function zi(t,e,n){let r=t.subarray(e,e+n);return Gl.decode(r)}function Jl(t,e,n){return n>Yl?zi(t,e,n):$i(t,e,n)}});var nr=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.ExtData=void 0;var tr=class{type;data;constructor(e,n){this.type=e,this.data=n}};Jt.ExtData=tr});var Zt=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DecodeError=void 0;var rr=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Xt.DecodeError=rr});var Qt=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.UINT32_MAX=void 0;ye.setUint64=Xl;ye.setInt64=Zl;ye.getInt64=Ql;ye.getUint64=ed;ye.UINT32_MAX=4294967295;function Xl(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zl(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Ql(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function ed(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var sr=b(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.timestampExtension=G.EXT_TIMESTAMP=void 0;G.encodeTimeSpecToTimestamp=Wi;G.encodeDateToTimeSpec=Ki;G.encodeTimestampExtension=Hi;G.decodeTimestampToTimeSpec=Gi;G.decodeTimestampExtension=Yi;var td=Zt(),Vi=Qt();G.EXT_TIMESTAMP=-1;var nd=4294967296-1,rd=17179869184-1;function Wi({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=rd)if(e===0&&t<=nd){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,Vi.setInt64)(r,4,t),n}}function Ki(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Hi(t){if(t instanceof Date){let e=Ki(t);return Wi(e)}else return null}function Gi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,Vi.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new td.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Yi(t){let e=Gi(t);return new Date(e.sec*1e3+e.nsec/1e6)}G.timestampExtension={type:G.EXT_TIMESTAMP,encode:Hi,decode:Yi}});var nn=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ExtensionCodec=void 0;var en=nr(),sd=sr(),ir=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(sd.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.ensureUint8Array=od;function id(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function od(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):id(t)?new Uint8Array(t):Uint8Array.from(t)}});var ar=b(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.Encoder=Z.DEFAULT_INITIAL_BUFFER_SIZE=Z.DEFAULT_MAX_DEPTH=void 0;var Ji=Yt(),cd=nn(),Xi=Qt(),ud=cr();Z.DEFAULT_MAX_DEPTH=100;Z.DEFAULT_INITIAL_BUFFER_SIZE=2048;var ur=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??cd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Z.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??Z.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Ji.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Ji.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,ud.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Xi.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Xi.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};Z.Encoder=ur});var Zi=b(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.encode=ld;var ad=ar();function ld(t,e){return new ad.Encoder(e).encodeSharedRef(t)}});var Qi=b(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.prettyByte=dd;function dd(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var eo=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CachedKeyDecoder=void 0;var fd=Yt(),hd=16,pd=16,fr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=hd,n=pd){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,fd.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};rn.CachedKeyDecoder=fr});var on=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.Decoder=void 0;var hr=Qi(),gd=nn(),Ae=Qt(),yd=Yt(),to=cr(),md=eo(),ie=Zt(),pr="array",tt="map_key",ro="map_value",wd=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ie.DecodeError("The type of key must be string or number but "+typeof t)},gr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=pr,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=tt,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===pr){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===tt||e.type===ro){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},et=-1,mr=new DataView(new ArrayBuffer(0)),_d=new Uint8Array(mr.buffer);try{mr.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var no=new RangeError("Insufficient data"),Sd=new md.CachedKeyDecoder,yr=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=mr;bytes=_d;headByte=et;stack=new gr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??gd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ae.UINT32_MAX,this.maxBinLength=e?.maxBinLength??Ae.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??Ae.UINT32_MAX,this.maxMapLength=e?.maxMapLength??Ae.UINT32_MAX,this.maxExtLength=e?.maxExtLength??Ae.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Sd,this.mapKeyConverter=e?.mapKeyConverter??wd}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=et,this.stack.reset()}setBuffer(e){let n=(0,to.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===et&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,to.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,hr.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new ie.DecodeError(`Unrecognized type byte: ${(0,hr.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===pr)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===tt){if(n==="__proto__")throw new ie.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=ro;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=tt;continue e}}return n}}readHeadByte(){return this.headByte===et&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=et}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ie.DecodeError(`Unrecognized array type byte: ${(0,hr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ie.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ie.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new ie.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===tt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new ie.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw no;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new ie.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,Ae.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,Ae.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};sn.Decoder=yr});var io=b(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.decode=bd;cn.decodeMulti=Id;var so=on();function bd(t,e){return new so.Decoder(e).decode(t)}function Id(t,e){return new so.Decoder(e).decodeMulti(t)}});var uo=b(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.isAsyncIterable=oo;nt.asyncIterableFromStream=co;nt.ensureAsyncIterable=xd;function oo(t){return t[Symbol.asyncIterator]!=null}async function*co(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function xd(t){return oo(t)?t:co(t)}});var ao=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.decodeAsync=Ed;rt.decodeArrayStream=Ad;rt.decodeMultiStream=vd;var wr=on(),_r=uo();async function Ed(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeAsync(n)}function Ad(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeArrayStream(n)}function vd(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeStream(n)}});var fo=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var Td=Zi();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return Td.encode}});var lo=io();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return lo.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return lo.decodeMulti}});var Sr=ao();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return Sr.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return Sr.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return Sr.decodeMultiStream}});var Dd=on();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return Dd.Decoder}});var Md=Zt();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return Md.DecodeError}});var Od=ar();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return Od.Encoder}});var Pd=nn();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return Pd.ExtensionCodec}});var kd=nr();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return kd.ExtData}});var Re=sr();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Re.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Re.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Re.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Re.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return Re.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return Re.decodeTimestampExtension}})});var xr=b((zh,mo)=>{"use strict";var q=require("fs"),Q=Ci(),{encode:Nd,decode:Ud}=fo(),br=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function ho(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function Ld(t){let e=ho(t);return Q.create({schema:e})}function Rd(t){for(let e of br)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function jd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");Rd(e);let n={};for(let r of br)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return Q.insert(t,n)}async function Fd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return po(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function po(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await Q.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await Q.removeMultiple(t,r)}function Ir(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function Cd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await Q.search(t,s)).hits.map(Ir)}async function Bd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await Q.search(t,i)).hits.map(Ir)}async function qd(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await Q.search(t,u)).hits.map(Ir)}async function $d(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=Q.save(t),r={v:1,schema:t.schema,raw:n},s=Nd(r),i=e+".tmp";q.writeFileSync(i,s),q.renameSync(i,e)}async function zd(t){if(!t)throw new Error("loadStore: storePath is required");if(!q.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=q.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=Ud(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await Q.create({schema:n.schema});return Q.load(r,n.raw),r}var Vd=3e4,Wd=50,Kd=1e4;function Hd(t){try{let e=q.openSync(t,"wx");return q.writeSync(e,String(process.pid)),q.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function Gd(t){return new Promise(e=>setTimeout(e,t))}async function go(t){let e=Date.now()+Kd;for(;;){if(Hd(t))return;try{let n=q.statSync(t);if(Date.now()-n.mtimeMs>Vd){try{q.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await Gd(Wd)}}function yo(t){try{q.unlinkSync(t)}catch{}}async function Yd(t,e){await go(t);try{return await e()}finally{yo(t)}}var Jd=["provider","model","dimensions","last_indexed","pending"];function Xd(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";q.writeFileSync(r,JSON.stringify(n,null,2)+` +`,"utf8"),q.renameSync(r,t)}function Zd(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!q.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=q.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}mo.exports={SCHEMA_FIELDS:br,METADATA_FIELDS:Jd,buildSchema:ho,createStore:Ld,insertDocument:jd,removeByIdentity:Fd,removeByFilter:po,searchFulltext:Cd,searchVector:Bd,searchHybrid:qd,saveStore:$d,loadStore:zd,acquireLock:go,releaseLock:yo,withLock:Yd,writeMetadata:Xd,readMetadata:Zd}});var Io=b((Vh,bo)=>{"use strict";var Qd=/^\s*(```+|~~~+)/,wo=/^---\s*$/;function ef(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` `).replace(/\r/g,` -`),l=c?ef(a):a;if(l.trim()==="")return[];let d=l.split(` -`);if(d.length_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:me(l)}];let h=tf(d,f,y),m=nf(h,d,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=me(d.slice(_.startLine,_.endLine+1).join(` -`)),v={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&wo(v))continue;let D=I.split(` -`);if(_.action==="regular"&&D.length>s){let A=rf(v,r);for(let k of A)u&&wo(k)||S.push({content:k.text})}else S.push({content:I})}return S}function me(t){return t.replace(/\s+$/,"")}function ef(t){let e=t.split(` -`);if(e.length===0||!mo.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:me(l)}];let h=nf(d,f,y),m=rf(h,d,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=me(d.slice(_.startLine,_.endLine+1).join(` +`)),v={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&_o(v))continue;let D=I.split(` +`);if(_.action==="regular"&&D.length>s){let A=sf(v,r);for(let k of A)u&&_o(k)||S.push({content:k.text})}else S.push({content:I})}return S}function me(t){return t.replace(/\s+$/,"")}function tf(t){let e=t.split(` +`);if(e.length===0||!wo.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let l=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),d=o.startLine,f=!0;for(let p of l)p.startLine>d&&(i.push({action:"regular",startLine:d,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),d=p.endLine+1;d<=o.endLine&&i.push({action:"regular",startLine:d,endLine:o.endLine,heading:"",headingLine:""})}return i}function rf(t,e){let n=t.text.split(` -`),s=_o(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=me(c.join(` +`))})}return s}function rf(t,e,n,r,s){let i=[];for(let o of t){let c=o.heading?o.heading.trim():"",u=r[c];if(u){i.push({action:u,startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let a=s.filter(p=>{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let l=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),d=o.startLine,f=!0;for(let p of l)p.startLine>d&&(i.push({action:"regular",startLine:d,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),d=p.endLine+1;d<=o.endLine&&i.push({action:"regular",startLine:d,endLine:o.endLine,heading:"",headingLine:""})}return i}function sf(t,e){let n=t.text.split(` +`),s=So(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=me(c.join(` `));u.trim()!==""&&i.push({heading:t.heading,headingLine:t.headingLine,text:u})}for(let c=0;c{"use strict";var Io="stub";function sf(t){let e=2166136261;for(let n=0;n>>0}function of(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var xr=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=sf(n)||1,s=of(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var Eo="text-embedding-3-small",Ao="https://api.openai.com/v1/embeddings",Ar=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||Eo,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var je=require("fs"),Dr=require("path"),cf=require("os"),{StubProvider:uf}=Er(),{OpenAIProvider:af}=un(),To={similarity_threshold:.8,decay_months:6},vr=["stub","openai"];function Do(){return Dr.join(cf.homedir(),".config","workflows","config.json")}function Mo(t){return Dr.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Tr(t){if(!je.existsSync(t))return null;let e;try{e=je.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function lf(t){let e=t&&t.systemPath||Do(),n=t&&t.projectPath||Mo(),r=Tr(e),s=Tr(n),i=Object.assign({},To);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);if(i.api_key_env){let o=process.env[i.api_key_env];i._api_key=o&&o.trim()!==""?o:null}else i._api_key=null;return i}function df(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new uf(n!=null?{dimensions:n}:void 0)}if(!vr.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${vr.join(", ")}`);return t._api_key&&e==="openai"?new af({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}function ff(t,e){if(!t)throw new Error("writeConfigFile: filePath is required");if(e==null||typeof e!="object"||!e.knowledge)throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key');let n=Dr.dirname(t);je.existsSync(n)||je.mkdirSync(n,{recursive:!0});let r=t+".tmp";je.writeFileSync(r,JSON.stringify(e,null,2)+` -`,"utf8"),je.renameSync(r,t)}Oo.exports={DEFAULTS:To,AVAILABLE_PROVIDERS:vr,systemConfigPath:Do,projectConfigPath:Mo,readConfigFile:Tr,loadConfig:lf,resolveProvider:df,writeConfigFile:ff}});var Ko=b((Hh,Wo)=>{"use strict";var we=require("fs"),_e=require("path"),hf=require("readline"),ie=Mr(),Or=Ir(),{OpenAIProvider:pf}=un(),Po="text-embedding-3-small",ko=1536,No="OPENAI_API_KEY",Uo=1536;function Lo(){process.stdin.isTTY||(process.stderr.write(`knowledge setup requires an interactive terminal. Run it directly, not through Claude or a pipe. -`),process.exit(1))}function Ro(){let t=hf.createInterface({input:process.stdin,output:process.stdout});return t.on("SIGINT",()=>{process.stderr.write(` +`).trim()===""}bo.exports={chunk:ef}});var Ar=b((Wh,Eo)=>{"use strict";var xo="stub";function of(t){let e=2166136261;for(let n=0;n>>0}function cf(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var Er=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=of(n)||1,s=cf(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var Ao="text-embedding-3-small",vo="https://api.openai.com/v1/embeddings",vr=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||Ao,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var je=require("fs"),Mr=require("path"),uf=require("os"),{StubProvider:af}=Ar(),{OpenAIProvider:lf}=un(),Do={similarity_threshold:.8,decay_months:6},Tr=["stub","openai"];function Mo(){return Mr.join(uf.homedir(),".config","workflows","config.json")}function Oo(t){return Mr.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Dr(t){if(!je.existsSync(t))return null;let e;try{e=je.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function df(t){let e=t&&t.systemPath||Mo(),n=t&&t.projectPath||Oo(),r=Dr(e),s=Dr(n),i=Object.assign({},Do);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);if(i.api_key_env){let o=process.env[i.api_key_env];i._api_key=o&&o.trim()!==""?o:null}else i._api_key=null;return i}function ff(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new af(n!=null?{dimensions:n}:void 0)}if(!Tr.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${Tr.join(", ")}`);return t._api_key&&e==="openai"?new lf({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}function hf(t,e){if(!t)throw new Error("writeConfigFile: filePath is required");if(e==null||typeof e!="object"||!e.knowledge)throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key');let n=Mr.dirname(t);je.existsSync(n)||je.mkdirSync(n,{recursive:!0});let r=t+".tmp";je.writeFileSync(r,JSON.stringify(e,null,2)+` +`,"utf8"),je.renameSync(r,t)}Po.exports={DEFAULTS:Do,AVAILABLE_PROVIDERS:Tr,systemConfigPath:Mo,projectConfigPath:Oo,readConfigFile:Dr,loadConfig:df,resolveProvider:ff,writeConfigFile:hf}});var Go=b((Gh,Ho)=>{"use strict";var we=require("fs"),_e=require("path"),pf=require("readline"),Y=Or(),Pr=xr(),{OpenAIProvider:gf}=un(),ko="text-embedding-3-small",No=1536,Uo="OPENAI_API_KEY",Lo=1536;function Ro(){process.stdin.isTTY||(process.stderr.write(`knowledge setup requires an interactive terminal. Run it directly, not through Claude or a pipe. +`),process.exit(1))}function jo(){let t=pf.createInterface({input:process.stdin,output:process.stdout});return t.on("SIGINT",()=>{process.stderr.write(` Setup cancelled. -`),t.close(),process.exit(130)}),t}function st(t,e,n){let r=n!=null&&n!==""?` [${n}]`:"";return new Promise(s=>{t.question(`${e}${r}: `,i=>{let o=(i||"").trim();s(o===""&&n!==void 0&&n!==null?String(n):o)})})}async function it(t,e,n){let r=n?"Y/n":"y/N";return new Promise(s=>{t.question(`${e} (${r}): `,i=>{let o=(i||"").trim().toLowerCase();if(o==="")return s(!!n);s(o==="y"||o==="yes")})})}function jo({model:t,dimensions:e,apiKeyEnv:n}){return{knowledge:{provider:"openai",model:t,dimensions:e,api_key_env:n,similarity_threshold:ie.DEFAULTS.similarity_threshold,decay_months:ie.DEFAULTS.decay_months}}}function Fo(){return{knowledge:{similarity_threshold:ie.DEFAULTS.similarity_threshold,decay_months:ie.DEFAULTS.decay_months}}}function Co(){return{knowledge:{}}}function Bo(t){if(!we.existsSync(t))return{exists:!1,valid:!1,knowledge:null};try{let e=we.readFileSync(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||!n.knowledge||typeof n.knowledge!="object"||Array.isArray(n.knowledge)?{exists:!0,valid:!1,knowledge:null,reason:'missing or invalid "knowledge" key'}:{exists:!0,valid:!0,knowledge:n.knowledge}}catch(e){return{exists:!0,valid:!1,knowledge:null,reason:e.message}}}function qo(t){let e=_e.join(t,"config.json"),n=_e.join(t,"store.msp"),r=_e.join(t,"metadata.json"),s=we.existsSync(t),i=we.existsSync(e),o=we.existsSync(n),c=we.existsSync(r);return{dirExists:s,configExists:i,storeExists:o,metadataExists:c,fullyInitialised:i&&o&&c,partiallyInitialised:s&&!(i&&o&&c)}}async function $o({apiKey:t,model:e,dimensions:n}){let s=await new pf({apiKey:t,model:e,dimensions:n}).embed("knowledge base setup test");if(!Array.isArray(s)||s.length!==n)throw new Error(`Expected a vector of length ${n}, got ${Array.isArray(s)?s.length:typeof s}`);return!0}async function zo(t){let e=ie.systemConfigPath(),n=Bo(e);if(n.exists&&n.valid){process.stdout.write(` +`),t.close(),process.exit(130)}),t}function st(t,e,n){let r=n!=null&&n!==""?` [${n}]`:"";return new Promise(s=>{t.question(`${e}${r}: `,i=>{let o=(i||"").trim();s(o===""&&n!==void 0&&n!==null?String(n):o)})})}async function it(t,e,n){let r=n?"Y/n":"y/N";return new Promise(s=>{t.question(`${e} (${r}): `,i=>{let o=(i||"").trim().toLowerCase();if(o==="")return s(!!n);s(o==="y"||o==="yes")})})}function Fo({model:t,dimensions:e,apiKeyEnv:n}){return{knowledge:{provider:"openai",model:t,dimensions:e,api_key_env:n,similarity_threshold:Y.DEFAULTS.similarity_threshold,decay_months:Y.DEFAULTS.decay_months}}}function Co(){return{knowledge:{similarity_threshold:Y.DEFAULTS.similarity_threshold,decay_months:Y.DEFAULTS.decay_months}}}function Bo(){return{knowledge:{}}}function qo(t){if(!we.existsSync(t))return{exists:!1,valid:!1,knowledge:null};try{let e=we.readFileSync(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||!n.knowledge||typeof n.knowledge!="object"||Array.isArray(n.knowledge)?{exists:!0,valid:!1,knowledge:null,reason:'missing or invalid "knowledge" key'}:{exists:!0,valid:!0,knowledge:n.knowledge}}catch(e){return{exists:!0,valid:!1,knowledge:null,reason:e.message}}}function $o(t){let e=_e.join(t,"config.json"),n=_e.join(t,"store.msp"),r=_e.join(t,"metadata.json"),s=we.existsSync(t),i=we.existsSync(e),o=we.existsSync(n),c=we.existsSync(r);return{dirExists:s,configExists:i,storeExists:o,metadataExists:c,fullyInitialised:i&&o&&c,partiallyInitialised:s&&!(i&&o&&c)}}async function zo({apiKey:t,model:e,dimensions:n}){let s=await new gf({apiKey:t,model:e,dimensions:n}).embed("knowledge base setup test");if(!Array.isArray(s)||s.length!==n)throw new Error(`Expected a vector of length ${n}, got ${Array.isArray(s)?s.length:typeof s}`);return!0}async function Vo(t){let e=Y.systemConfigPath(),n=qo(e);if(n.exists&&n.valid){process.stdout.write(` System config already exists at ${e} `),process.stdout.write(` Current settings: `);let l=n.knowledge;if(process.stdout.write(` provider: ${l.provider==null?"(none \u2014 stub mode)":l.provider} @@ -47,21 +47,21 @@ Embedding provider: `),process.stdout.write(` skip \u2014 Stub mode (keyword-only search, no embeddings) `);let s;for(;s=(await st(t,"Provider (openai / skip)","openai")).toLowerCase(),!(s==="openai"||s==="skip");)process.stdout.write(`Unknown choice "${s}". Enter "openai" or "skip". -`);if(s==="skip")return ie.writeConfigFile(e,Fo()),process.stdout.write(` +`);if(s==="skip")return Y.writeConfigFile(e,Co()),process.stdout.write(` Wrote stub-mode system config to ${e} -`),process.stdout.write("Stub mode uses keyword-only (BM25) search. Semantic search is disabled. Run `knowledge setup` again later to configure a provider.\n"),{provider:null,previouslyStub:r};let i=await st(t,"Embedding model",Po),o=await st(t,"Vector dimensions",String(ko)),c=parseInt(o,10);(!Number.isInteger(c)||c<=0)&&(process.stderr.write(`Invalid dimensions: "${o}". Must be a positive integer. -`),process.exit(1));let u=await st(t,"API key environment variable",No),a=process.env[u];if(a&&a.trim()!==""){process.stdout.write(` +`),process.stdout.write("Stub mode uses keyword-only (BM25) search. Semantic search is disabled. Run `knowledge setup` again later to configure a provider.\n"),{provider:null,previouslyStub:r};let i=await st(t,"Embedding model",ko),o=await st(t,"Vector dimensions",String(No)),c=parseInt(o,10);(!Number.isInteger(c)||c<=0)&&(process.stderr.write(`Invalid dimensions: "${o}". Must be a positive integer. +`),process.exit(1));let u=await st(t,"API key environment variable",Uo),a=process.env[u];if(a&&a.trim()!==""){process.stdout.write(` Validating API key via a test embed... -`);try{await $o({apiKey:a.trim(),model:i,dimensions:c}),process.stdout.write(`API key works. +`);try{await zo({apiKey:a.trim(),model:i,dimensions:c}),process.stdout.write(`API key works. `)}catch(l){process.stdout.write(`API key validation failed: ${l.message} `),await it(t,"Continue anyway (you can fix the key later)?",!0)||(process.stdout.write(`Aborting setup. `),process.exit(1))}}else process.stdout.write(` Environment variable ${u} is not set. Set it in your shell profile (e.g., ~/.zshrc) before using the knowledge base: export ${u}="sk-..." Setup will continue \u2014 the key is only needed at query/index time. -`);return ie.writeConfigFile(e,jo({model:i,dimensions:c,apiKeyEnv:u})),process.stdout.write(` +`);return Y.writeConfigFile(e,Fo({model:i,dimensions:c,apiKeyEnv:u})),process.stdout.write(` Wrote system config to ${e} -`),{provider:"openai",previouslyStub:r}}async function Vo(t){let e=_e.resolve(process.cwd(),".workflows",".knowledge"),n=_e.join(e,"config.json"),r=_e.join(e,"store.msp"),s=_e.join(e,"metadata.json"),i=qo(e);if(i.fullyInitialised){if(process.stdout.write(` +`),{provider:"openai",previouslyStub:r}}async function Wo(t){let e=_e.resolve(process.cwd(),".workflows",".knowledge"),n=_e.join(e,"config.json"),r=_e.join(e,"store.msp"),s=_e.join(e,"metadata.json"),i=$o(e);if(i.fullyInitialised){if(process.stdout.write(` Project knowledge base already initialised at ${e} `),!await it(t,"Reinitialise (destroys existing store)?",!1))return process.stdout.write(`Keeping existing project files. `),{created:!1}}else i.partiallyInitialised?(process.stdout.write(` @@ -69,18 +69,24 @@ Project knowledge base partially initialised at ${e} `),process.stdout.write(` Missing files will be created. `)):process.stdout.write(` Initialising project knowledge base at ${e} -`);we.mkdirSync(e,{recursive:!0}),(!i.configExists||i.fullyInitialised)&&(ie.writeConfigFile(n,Co()),process.stdout.write(` config.json written -`));let o=ie.loadConfig(),c=o.provider||null,u=Number.isInteger(o.dimensions)&&o.dimensions>0?o.dimensions:Uo;if(!i.storeExists||i.fullyInitialised){let a=await Or.createStore(u);await Or.saveStore(a,r),process.stdout.write(` store.msp written (${u} dimensions) -`)}return(!i.metadataExists||i.fullyInitialised)&&(Or.writeMetadata(s,{provider:c||null,model:c&&o.model?o.model:null,dimensions:c?u:null,last_indexed:null,pending:[]}),process.stdout.write(` metadata.json written -`)),{created:!0,provider:c,dimensions:u}}async function gf(t,e){Lo();let n=_e.resolve(process.cwd(),".workflows");we.existsSync(n)||(process.stderr.write(`No .workflows/ directory found. Initialise a workflow project first. -`),process.exit(1));let r=Ro();try{process.stdout.write(` +`);we.mkdirSync(e,{recursive:!0}),(!i.configExists||i.fullyInitialised)&&(Y.writeConfigFile(n,Bo()),process.stdout.write(` config.json written +`));let o=Y.loadConfig(),c=o.provider||null,u=Number.isInteger(o.dimensions)&&o.dimensions>0?o.dimensions:Lo;if(!i.storeExists||i.fullyInitialised){let a=await Pr.createStore(u);await Pr.saveStore(a,r),process.stdout.write(` store.msp written (${u} dimensions) +`)}return(!i.metadataExists||i.fullyInitialised)&&(Pr.writeMetadata(s,{provider:c||null,model:c&&o.model?o.model:null,dimensions:c?u:null,last_indexed:null,pending:[]}),process.stdout.write(` metadata.json written +`)),{created:!0,provider:c,dimensions:u}}async function Ko(t,e){let n=Y.loadConfig(),r=Y.resolveProvider(n);process.stdout.write(` +Initial indexing +`),process.stdout.write(`---------------- +`);try{await t(e||{},n,r)}catch(s){process.stderr.write(` +Initial indexing hit an error: ${s.message} +Project is initialised; run \`knowledge index\` later to retry. +`)}}async function yf(t,e,n){Ro();let r=_e.resolve(process.cwd(),".workflows");we.existsSync(r)||(process.stderr.write(`No .workflows/ directory found. Initialise a workflow project first. +`),process.exit(1));let s=jo(),i;try{process.stdout.write(` Knowledge base setup `),process.stdout.write(`==================== -`);let s=await zo(r);await Vo(r),process.stdout.write(` +`),i=await Vo(s),await Wo(s)}finally{s.close()}await Ko(t,n),process.stdout.write(` Setup complete. -`),s.provider?s.previouslyStub&&process.stdout.write("\nUpgraded from stub mode to a configured provider. Run `knowledge rebuild` to re-index existing artifacts with embeddings.\n"):process.stdout.write(` +`),i.provider?i.previouslyStub&&process.stdout.write("\nUpgraded from stub mode to a configured provider. The existing store was indexed in keyword-only mode \u2014 run `knowledge rebuild` to re-index with embeddings for full hybrid search.\n"):process.stdout.write(` Stub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. Semantic search is disabled until you configure a provider. -`)}finally{r.close()}}Wo.exports={cmdSetup:gf,requireTTY:Lo,createPrompter:Ro,ask:st,askYesNo:it,buildSystemConfigOpenAI:jo,buildSystemConfigStub:Fo,buildProjectConfigEmpty:Co,detectSystemConfig:Bo,detectProjectInit:qo,validateApiKey:$o,runSystemConfigStep:zo,runProjectInitStep:Vo,KEYWORD_ONLY_DIMENSIONS:Uo,OPENAI_DEFAULT_MODEL:Po,OPENAI_DEFAULT_DIMENSIONS:ko,OPENAI_DEFAULT_ENV_VAR:No}});var T=require("fs"),B=require("path"),E=Ir(),Yo=bo(),{StubProvider:yf}=Er(),{OpenAIProvider:mf}=un(),Fe=Mr(),Jo=Ko(),kr=["research","discussion","investigation","specification"],wf=T.existsSync(B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):B.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),ct=[1e3,2e3,4e3],_f=5,Nr=1536;function Xo(t){let e=[],n={},r=0;for(;r [options] +`)}Ho.exports={cmdSetup:yf,requireTTY:Ro,createPrompter:jo,ask:st,askYesNo:it,buildSystemConfigOpenAI:Fo,buildSystemConfigStub:Co,buildProjectConfigEmpty:Bo,detectSystemConfig:qo,detectProjectInit:$o,validateApiKey:zo,runSystemConfigStep:Vo,runProjectInitStep:Wo,runInitialIndexStep:Ko,KEYWORD_ONLY_DIMENSIONS:Lo,OPENAI_DEFAULT_MODEL:ko,OPENAI_DEFAULT_DIMENSIONS:No,OPENAI_DEFAULT_ENV_VAR:Uo}});var T=require("fs"),B=require("path"),E=xr(),Xo=Io(),{StubProvider:mf}=Ar(),{OpenAIProvider:wf}=un(),Fe=Or(),Zo=Go(),Nr=["research","discussion","investigation","specification"],_f=T.existsSync(B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):B.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),ct=[1e3,2e3,4e3],Sf=5,Ur=1536;function Qo(t){let e=[],n={},r=0;for(;r [options] Commands: index Index a file or all pending artifacts @@ -98,56 +104,56 @@ Options: --phase Filter by phase --topic Filter by topic --limit Limit number of results - --dry-run Preview without making changes`;function oe(){return B.resolve(process.cwd(),".workflows",".knowledge")}function ce(){return B.join(oe(),"store.msp")}function Se(){return B.join(oe(),"metadata.json")}function ve(){return B.join(oe(),".lock")}function Sf(t){return new Promise(e=>setTimeout(e,t))}async function ut(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||ct,s;for(let i=0;isetTimeout(e,t))}async function ut(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||ct,s;for(let i=0;iLr(s,o,n,r),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexed ${c} chunks from ${s} -`),await nc(n,r,_f)}async function Lr(t,e,n,r){let s=bf(e.workUnit),i=B.join(__dirname,"..","chunking",e.phase+".json");if(!T.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(T.readFileSync(i,"utf8")),c=B.resolve(t),u=T.readFileSync(c,"utf8"),a=Yo.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let l=oe(),d=ce(),f=Se(),p=ve();T.existsSync(l)||T.mkdirSync(l,{recursive:!0});let g,y,h=T.existsSync(d),m=T.existsSync(f);h&&(g=await E.loadStore(d)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=Qo(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||Nr;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),v=o.confidence||"medium",D=a.map((A,k)=>{let Te=String(k+1).padStart(3,"0"),Y={id:`${e.workUnit}-${e.phase}-${e.topic}-${Te}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:v,source_file:t,timestamp:I};return _&&(Y.embedding=_[k]),Y});return await E.withLock(p,async()=>{h?g=await E.loadStore(d):T.existsSync(d)&&(g=await E.loadStore(d)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,d);let A=T.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function ot(t){let{execFileSync:e}=require("child_process");return e("node",[wf,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function ec(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function Rr(){let t=[],e;try{let n=ot(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of kr){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=ot(["resolve",`${r}.${s}.${o}`]).trim();a&&T.existsSync(B.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function tc(t,e,n){let r=Rr(),s=oe(),i=ce();T.existsSync(s)||T.mkdirSync(s,{recursive:!0});let o=null;T.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let l of r){if(o&&await ec(o,l.workUnit,l.phase,l.topic)){a++;continue}try{let d={workUnit:l.workUnit,phase:l.phase,topic:l.topic},f=await ut(()=>Lr(l.file,d,e,n),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexing ${l.file}... ${f} chunks -`),c++,u+=f,T.existsSync(i)&&(o=await E.loadStore(i))}catch(d){await xf(l.file,d.message),process.stderr.write(`Failed to index ${l.file} after 3 attempts: ${d.message}. Added to pending queue. -`)}}await nc(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. -`)}async function xf(t,e){let n=Se(),r=oe(),s=ve();T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;T.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function Pr(t){let e=Se(),n=ve();T.existsSync(e)&&await E.withLock(n,async()=>{if(!T.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function nc(t,e,n){let r=Se();if(!T.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=B.resolve(o.file);if(!T.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. -`),await Pr(o.file);continue}let u;try{u=Ur(o.file)}catch{await Pr(o.file);continue}try{await ut(()=>Lr(o.file,u,t,e),{maxAttempts:3,backoff:ct}),await Pr(o.file)}catch{}}}var Ef={high:4,medium:3,"low-medium":2,low:1};function Af(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function vf(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Tf(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Ef[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function Df(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. + Current config has no provider configured.`)}async function xf(t,e,n,r){if(t.length===0)return an(e,n,r);let s=t[0],i=B.resolve(s);T.existsSync(i)||(process.stderr.write(`File not found: ${i} +`),process.exit(1));let o=Lr(s),c=await ut(()=>Rr(s,o,n,r),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexed ${c} chunks from ${s} +`),await rc(n,r,Sf)}async function Rr(t,e,n,r){let s=If(e.workUnit),i=B.join(__dirname,"..","chunking",e.phase+".json");if(!T.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(T.readFileSync(i,"utf8")),c=B.resolve(t),u=T.readFileSync(c,"utf8"),a=Xo.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let l=oe(),d=ce(),f=Se(),p=ve();T.existsSync(l)||T.mkdirSync(l,{recursive:!0});let g,y,h=T.existsSync(d),m=T.existsSync(f);h&&(g=await E.loadStore(d)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=tc(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||Ur;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),v=o.confidence||"medium",D=a.map((A,k)=>{let Te=String(k+1).padStart(3,"0"),J={id:`${e.workUnit}-${e.phase}-${e.topic}-${Te}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:v,source_file:t,timestamp:I};return _&&(J.embedding=_[k]),J});return await E.withLock(p,async()=>{h?g=await E.loadStore(d):T.existsSync(d)&&(g=await E.loadStore(d)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,d);let A=T.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function ot(t){let{execFileSync:e}=require("child_process");return e("node",[_f,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function nc(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function jr(){let t=[],e;try{let n=ot(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of Nr){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=ot(["resolve",`${r}.${s}.${o}`]).trim();a&&T.existsSync(B.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function an(t,e,n){let r=jr(),s=oe(),i=ce();T.existsSync(s)||T.mkdirSync(s,{recursive:!0});let o=null;T.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let l of r){if(o&&await nc(o,l.workUnit,l.phase,l.topic)){a++;continue}try{let d={workUnit:l.workUnit,phase:l.phase,topic:l.topic},f=await ut(()=>Rr(l.file,d,e,n),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexing ${l.file}... ${f} chunks +`),c++,u+=f,T.existsSync(i)&&(o=await E.loadStore(i))}catch(d){await Ef(l.file,d.message),process.stderr.write(`Failed to index ${l.file} after 3 attempts: ${d.message}. Added to pending queue. +`)}}await rc(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. +`)}async function Ef(t,e){let n=Se(),r=oe(),s=ve();T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;T.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function kr(t){let e=Se(),n=ve();T.existsSync(e)&&await E.withLock(n,async()=>{if(!T.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function rc(t,e,n){let r=Se();if(!T.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=B.resolve(o.file);if(!T.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. +`),await kr(o.file);continue}let u;try{u=Lr(o.file)}catch{await kr(o.file);continue}try{await ut(()=>Rr(o.file,u,t,e),{maxAttempts:3,backoff:ct}),await kr(o.file)}catch{}}}var Af={high:4,medium:3,"low-medium":2,low:1};function vf(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function Tf(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Df(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Af[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function Mf(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store was indexed with: provider=${r}, model=${s} Current config has no provider configured.`);let o=n.model(),c=n.dimensions();if(r===e.provider&&s===o&&i===c)return{mode:"full",provider:n};throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store: provider=${r}, model=${s}, dimensions=${i} - Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function Mf(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] + Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function Of(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] `),process.exit(1));let s=t,i=e.limit||10,o=ce(),c=Se();if(!T.existsSync(o)){process.stdout.write(`[0 results] -`);return}let u=await E.loadStore(o),a="keyword-only",l=null,d=null;T.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=Df(f,n,r);a=p.mode,l=p.provider,a==="keyword-only"?d="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(d="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&l){let v=await ut(()=>l.embed(_),{maxAttempts:3,backoff:ct});I=await E.searchHybrid(u,{term:_,vector:v,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let v of I){let D=m.get(v.id);(!D||v.score>D.score)&&m.set(v.id,v)}}let w=Tf(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];d&&S.push(d),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=vf(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` +`);return}let u=await E.loadStore(o),a="keyword-only",l=null,d=null;T.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=Mf(f,n,r);a=p.mode,l=p.provider,a==="keyword-only"?d="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(d="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&l){let v=await ut(()=>l.embed(_),{maxAttempts:3,backoff:ct});I=await E.searchHybrid(u,{term:_,vector:v,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let v of I){let D=m.get(v.id);(!D||v.score>D.score)&&m.set(v.id,v)}}let w=Df(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];d&&S.push(d),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=Tf(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` `)+` -`)}async function Of(){let t=oe(),e=B.join(t,"config.json"),n=ce();if(!T.existsSync(t)){process.stdout.write(`not-ready +`)}async function Pf(){let t=oe(),e=B.join(t,"config.json"),n=ce();if(!T.existsSync(t)){process.stdout.write(`not-ready `);return}if(!T.existsSync(e)){process.stdout.write(`not-ready `);return}if(!T.existsSync(n)){process.stdout.write(`not-ready `);return}try{await E.loadStore(n)}catch{process.stdout.write(`not-ready `);return}process.stdout.write(`ready -`)}async function Pf(){let t=oe(),e=ce(),n=Se(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!T.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` +`)}async function kf(){let t=oe(),e=ce(),n=Se(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!T.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` `)+` -`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let l=(T.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${l} KB`),T.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Fe.loadConfig()}catch{m=null}if(m){let w=Fe.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let d=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),T.existsSync(B.resolve(h.source_file))||d.push(h.source_file));if(d.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${d.length} files`);for(let h of d)r.push(` ${h}`)}try{let h=Rr(),m=[];for(let w of h)await ec(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=rc(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{ot(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` +`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let l=(T.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${l} KB`),T.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Fe.loadConfig()}catch{m=null}if(m){let w=Fe.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let d=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),T.existsSync(B.resolve(h.source_file))||d.push(h.source_file));if(d.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${d.length} files`);for(let h of d)r.push(` ${h}`)}try{let h=jr(),m=[];for(let w of h)await nc(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=sc(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{ot(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` `)+` -`)}async function kf(t,e,n,r){let s=ce(),i=Se(),o=ve();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. +`)}async function Nf(t,e,n,r){let s=ce(),i=Se(),o=ve();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. This is non-deterministic \u2014 the rebuilt index will differ from the original. -Type 'rebuild' to confirm: `),await Nf()!=="rebuild"&&(process.stderr.write(`Aborted. -`),process.exit(1)),Rr().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. +Type 'rebuild' to confirm: `),await Uf()!=="rebuild"&&(process.stderr.write(`Aborted. +`),process.exit(1)),jr().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. (If you believe this is wrong, check that .workflows/ exists and that work units have items with status "completed".) -`),process.exit(1)),await E.withLock(o,async()=>{T.existsSync(s)&&T.unlinkSync(s),T.existsSync(i)&&T.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||Nr,l=await E.createStore(a);await E.saveStore(l,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. -`),await tc(e,n,r)}function Nf(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function Uf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] +`),process.exit(1)),await E.withLock(o,async()=>{T.existsSync(s)&&T.unlinkSync(s),T.existsSync(i)&&T.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||Ur,l=await E.createStore(a);await E.saveStore(l,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. +`),await an(e,n,r)}function Uf(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function Lf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] `),process.exit(1)),e.topic&&!e.phase&&(process.stderr.write(`Error: --topic requires --phase -`),process.exit(1));let n=ce(),r=ve();if(!T.existsSync(n)){let o=Go(e);process.stdout.write(`Removed 0 chunks for ${o} -`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=Go(e);process.stdout.write(`Removed ${s} chunks for ${i} -`)}function Go(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function rc(t){try{let e=ot(["get",t,"status"]).trim(),n=null;try{n=ot(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function Lf(t,e,n){let r=ce(),s=ve(),i=n&&n.decay_months!==void 0?n.decay_months:Fe.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled +`),process.exit(1));let n=ce(),r=ve();if(!T.existsSync(n)){let o=Jo(e);process.stdout.write(`Removed 0 chunks for ${o} +`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=Jo(e);process.stdout.write(`Removed ${s} chunks for ${i} +`)}function Jo(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function sc(t){try{let e=ot(["get",t,"status"]).trim(),n=null;try{n=ot(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function Rf(t,e,n){let r=ce(),s=ve(),i=n&&n.decay_months!==void 0?n.decay_months:Fe.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled `);return}(!Number.isInteger(i)||i<0)&&(process.stderr.write(`Invalid decay_months: ${JSON.stringify(i)}. Expected false or a non-negative integer. -`),process.exit(1));let o=i;if(!T.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let l=await E.searchFulltext(c,{term:"",limit:1e5});if(l.length===0)return;let d={};for(let h of l)d[h.work_unit]||(d[h.work_unit]=[]),d[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(d)){let w=rc(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=Af(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let v=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:v});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` +`),process.exit(1));let o=i;if(!T.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let l=await E.searchFulltext(c,{term:"",limit:1e5});if(l.length===0)return;let d={};for(let h of l)d[h.work_unit]||(d[h.work_unit]=[]),d[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(d)){let w=sc(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=vf(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let v=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:v});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` `)+` `);return}await E.withLock(s,async()=>{let h=await E.loadStore(r),m=new Set;for(let w of p){let S=`${w.work_unit}|${w.phase}|${w.topic}`;m.has(S)||(m.add(S),await E.removeByIdentity(h,w))}await E.saveStore(h,r)});let y=[];y.push(`Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let h of f)y.push(` \u2022 ${h.workUnit}: ${h.count} chunks (${Array.from(h.phases).join(", ")})`);process.stdout.write(y.join(` `)+` -`)}async function sc(){let t=process.argv.slice(2),{positional:e,flags:n}=Xo(t),r=e[0],s=e.slice(1),i=Zo(n);r||(process.stderr.write(Ho+` -`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Fe.loadConfig(),c=Fe.resolveProvider(o)),r){case"index":await If(s,i,o,c);break;case"query":await Mf(s,i,o,c);break;case"check":await Of(s,i,o,c);break;case"status":await Pf();break;case"remove":await Uf(s,i,o,c);break;case"compact":await Lf(s,i,o,c);break;case"rebuild":await kf(s,i,o,c);break;case"setup":await Jo.cmdSetup(s,i);break;default:process.stderr.write(`Unknown command "${r}". +`)}async function ic(){let t=process.argv.slice(2),{positional:e,flags:n}=Qo(t),r=e[0],s=e.slice(1),i=ec(n);r||(process.stderr.write(Yo+` +`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Fe.loadConfig(),c=Fe.resolveProvider(o)),r){case"index":await xf(s,i,o,c);break;case"query":await Of(s,i,o,c);break;case"check":await Pf(s,i,o,c);break;case"status":await kf();break;case"remove":await Lf(s,i,o,c);break;case"compact":await Rf(s,i,o,c);break;case"rebuild":await Nf(s,i,o,c);break;case"setup":await Zo.cmdSetup(an,s,i);break;default:process.stderr.write(`Unknown command "${r}". -${Ho} -`),process.exit(1)}}module.exports={parseArgs:Xo,buildOptions:Zo,deriveIdentity:Ur,resolveProviderState:Qo,withRetry:ut,main:sc,StubProvider:yf,OpenAIProvider:mf,store:E,chunker:Yo,config:Fe,setup:Jo,knowledgeDir:oe,storePath:ce,metadataPath:Se,lockFilePath:ve,INDEXED_PHASES:kr,KEYWORD_ONLY_DIMENSIONS:Nr};require.main===module&&sc().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` +${Yo} +`),process.exit(1)}}module.exports={parseArgs:Qo,buildOptions:ec,deriveIdentity:Lr,resolveProviderState:tc,withRetry:ut,main:ic,cmdIndexBulk:an,StubProvider:mf,OpenAIProvider:wf,store:E,chunker:Xo,config:Fe,setup:Zo,knowledgeDir:oe,storePath:ce,metadataPath:Se,lockFilePath:ve,INDEXED_PHASES:Nr,KEYWORD_ONLY_DIMENSIONS:Ur};require.main===module&&ic().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` `),process.exit(1)}); diff --git a/src/knowledge/index.js b/src/knowledge/index.js index 3a5814111..5db99ddbe 100644 --- a/src/knowledge/index.js +++ b/src/knowledge/index.js @@ -1507,7 +1507,7 @@ async function main() { case 'remove': await cmdRemove(commandArgs, options, cfg, provider); break; case 'compact': await cmdCompact(commandArgs, options, cfg, provider); break; case 'rebuild': await cmdRebuild(commandArgs, options, cfg, provider); break; - case 'setup': await setup.cmdSetup(commandArgs, options); break; + case 'setup': await setup.cmdSetup(cmdIndexBulk, commandArgs, options); break; default: process.stderr.write(`Unknown command "${command}".\n\n${USAGE}\n`); process.exit(1); @@ -1521,6 +1521,7 @@ module.exports = { resolveProviderState, withRetry, main, + cmdIndexBulk, StubProvider, OpenAIProvider, store, diff --git a/src/knowledge/setup.js b/src/knowledge/setup.js index 03bd301a0..9f61fe64c 100644 --- a/src/knowledge/setup.js +++ b/src/knowledge/setup.js @@ -342,7 +342,28 @@ async function runProjectInitStep(rl) { // Orchestrator // --------------------------------------------------------------------------- -async function cmdSetup(args, options) { +async function runInitialIndexStep(cmdIndexBulk, options) { + const cfg = config.loadConfig(); + const provider = config.resolveProvider(cfg); + + process.stdout.write('\nInitial indexing\n'); + process.stdout.write('----------------\n'); + try { + await cmdIndexBulk(options || {}, cfg, provider); + } catch (err) { + // Indexing failures don't abort setup — the project is initialised + // and the pending queue retains any partial state. + process.stderr.write( + `\nInitial indexing hit an error: ${err.message}\n` + + 'Project is initialised; run `knowledge index` later to retry.\n' + ); + } +} + +// cmdIndexBulk is injected by the caller (index.js dispatch) to avoid +// a circular require — esbuild's CJS wrapping breaks `require.main === +// module` on the entry when two modules require each other. +async function cmdSetup(cmdIndexBulk, args, options) { requireTTY(); // Guard: .workflows/ must exist. @@ -355,30 +376,35 @@ async function cmdSetup(args, options) { } const rl = createPrompter(); + let sysResult; try { process.stdout.write('\nKnowledge base setup\n'); process.stdout.write('====================\n'); - const sysResult = await runSystemConfigStep(rl); + sysResult = await runSystemConfigStep(rl); await runProjectInitStep(rl); - - process.stdout.write('\nSetup complete.\n'); - - if (!sysResult.provider) { - process.stdout.write( - '\nStub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. ' + - 'Semantic search is disabled until you configure a provider.\n' - ); - } else if (sysResult.previouslyStub) { - process.stdout.write( - '\nUpgraded from stub mode to a configured provider. ' + - 'Run `knowledge rebuild` to re-index existing artifacts with embeddings.\n' - ); - } } finally { + // Close readline before indexing — indexing is non-interactive and + // a lingering readline blocks process exit. Safe to call twice. rl.close(); } + + await runInitialIndexStep(cmdIndexBulk, options); + + process.stdout.write('\nSetup complete.\n'); + + if (!sysResult.provider) { + process.stdout.write( + '\nStub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. ' + + 'Semantic search is disabled until you configure a provider.\n' + ); + } else if (sysResult.previouslyStub) { + process.stdout.write( + '\nUpgraded from stub mode to a configured provider. ' + + 'The existing store was indexed in keyword-only mode — run `knowledge rebuild` to re-index with embeddings for full hybrid search.\n' + ); + } } module.exports = { @@ -395,6 +421,7 @@ module.exports = { validateApiKey, runSystemConfigStep, runProjectInitStep, + runInitialIndexStep, KEYWORD_ONLY_DIMENSIONS, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_DIMENSIONS, diff --git a/tests/scripts/test-knowledge-cli.sh b/tests/scripts/test-knowledge-cli.sh index 258e20f39..4f176a7b2 100644 --- a/tests/scripts/test-knowledge-cli.sh +++ b/tests/scripts/test-knowledge-cli.sh @@ -167,6 +167,12 @@ for cmd in index query check; do assert_eq "$cmd does not say unknown command" "false" "$(echo "$output" | grep -q 'Unknown command' && echo true || echo false)" done +# --- Test 4b: setup dispatches (not an unknown command) --- +echo "Test 4b: setup routes to the wizard handler" +output=$(echo '' | node "$BUNDLE" setup 2>&1 || true) +assert_eq "setup does not say unknown command" "false" "$(echo "$output" | grep -q 'Unknown command' && echo true || echo false)" +assert_eq "setup does not say not yet implemented" "false" "$(echo "$output" | grep -q 'not yet implemented' && echo true || echo false)" + # ============================================================================ # INDEX COMMAND TESTS # ============================================================================ From f8d26e2d57090be2e240c0cef83a2a6ed79b79aa Mon Sep 17 00:00:00 2001 From: Lee Overy Date: Sun, 19 Apr 2026 19:15:41 +0100 Subject: [PATCH 3/5] =?UTF-8?q?refactor(knowledge):=20hybrid=20credential?= =?UTF-8?q?=20storage=20=E2=80=94=20env=20var=20or=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the credentials-at-rest half of a hybrid auth model: a separate ~/.config/workflows/credentials.json at mode 0600, keyed by provider ({ "credentials": { "openai": { "api_key": "sk-..." } } }), resolved only when the provider-specific env var (OPENAI_API_KEY for openai) is not set. Env var wins — matches the AWS SDK pattern. config.js gains loadCredentials, writeCredentials, resolveApiKey, and a PROVIDER_ENV_VARS map. loadConfig stops reading api_key_env from config files and instead delegates to resolveApiKey. Design doc's Configuration Hierarchy section is rewritten: two config files (non-secret) plus one credentials file (secret, 0600), explicit precedence, rationale for the split. The wizard still writes the old api_key_env field into config.json — that field is now inert and gets cleaned up in the next commit. Co-Authored-By: Claude Opus 4.7 (1M context) --- knowledge-base/design.md | 45 ++-- src/knowledge/config.js | 163 ++++++++++++- tests/scripts/test-knowledge-config.cjs | 292 ++++++++++++++++++++++-- 3 files changed, 459 insertions(+), 41 deletions(-) diff --git a/knowledge-base/design.md b/knowledge-base/design.md index 3686ed05e..a4fc770ee 100644 --- a/knowledge-base/design.md +++ b/knowledge-base/design.md @@ -257,34 +257,47 @@ Adding a new provider is just implementing the `KnowledgeProvider` interface — ### Configuration Hierarchy -Two-level config: system defaults shared across projects, with per-project overrides. +Three files, two concerns. Config is non-secret and layered (system → project). Credentials are secret and live in a separate file with restricted permissions. A provider-specific env var overrides the stored credential so power users and CI can run without a file write. -**System-level** (`~/.config/workflows/config.json`): +**System config** (`~/.config/workflows/config.json`) — non-secret settings shared across projects: ```json { "knowledge": { "provider": "openai", "model": "text-embedding-3-small", "dimensions": 1536, - "api_key_env": "OPENAI_API_KEY" + "similarity_threshold": 0.8, + "decay_months": 6 } } ``` -**Project-level** (`.workflows/.knowledge/config.json`): +**Project config** (`.workflows/.knowledge/config.json`) — per-project overrides. Typical content is `{ "knowledge": {} }` (inherits everything): ```json { "knowledge": { - "provider": "openai", "model": "text-embedding-3-large", "dimensions": 3072 } } ``` -**Resolution**: Project config inherits from system config and overrides what it specifies. API keys are always referenced by env var name (`api_key_env`), never stored directly — keeps secrets out of config files. The user sets the env var in their shell profile. +**Credentials** (`~/.config/workflows/credentials.json`, mode `0600`, user-private) — API keys, keyed by provider so multiple providers coexist: +```json +{ + "credentials": { + "openai": { "api_key": "sk-..." } + } +} +``` + +**Resolution**: +- Config: project merges onto system merges onto built-in defaults. Shallow merge. +- API key (per provider): `process.env[PROVIDER_ENV_VAR]` first (e.g. `OPENAI_API_KEY`). If unset or empty, read `credentials..api_key` from `credentials.json`. If neither, the store runs in keyword-only mode. + +**Why the split**: config files get committed to dotfiles repos, synced, and `cat`'d during support; keeping them free of secrets makes that safe by default. The credentials file is explicitly separate and written at `0600` so the pattern is clear to the reader and the file is harder to leak by accident. Env-override exists because CI, containers, and per-shell workflows don't want a file write and shouldn't have to go through the wizard. -**Typical usage**: System config holds the API key reference and default provider. Most projects inherit everything. A project that needs a different model or provider overrides just that field. +**Typical usage**: `knowledge setup` writes both files on first run — config in plaintext, credentials at `0600`. Most projects inherit everything and don't need a project-level `config.json` override at all. To rotate the key, edit `credentials.json` or re-run `knowledge setup`. To remove the stored key, delete the file or the `openai` entry. **Complete config schema** (all valid fields): ```json @@ -293,13 +306,12 @@ Two-level config: system defaults shared across projects, with per-project overr "provider": "openai", "model": "text-embedding-3-small", "dimensions": 1536, - "api_key_env": "OPENAI_API_KEY", "similarity_threshold": 0.8, "decay_months": 6 } } ``` -System config typically has all fields. Project config only overrides what differs (e.g., just `decay_months`). +System config typically has all fields. Project config only overrides what differs (e.g., just `decay_months`). The `api_key_env` field from earlier drafts is retired — credentials resolution is hardcoded to `PROVIDER_ENV_VARS[provider]` plus the credentials file. ### Knowledge Base is Required Infrastructure @@ -309,10 +321,11 @@ The knowledge base is **required** — skills cannot proceed without it. But it 1. **Entry-point skills check** — Step 0 runs `knowledge check` (lightweight, just checks if the store exists). If not initialised, a reference file displays a clear message explaining the knowledge base, why it's needed, and the exact command to run. Hard stop — same conventions as any terminal condition. 2. **User runs `knowledge setup`** outside Claude — interactive wizard that handles everything: - - System config (`~/.config/workflows/config.json`): provider, model, API key env var, validation + - System config (`~/.config/workflows/config.json`): provider, model, dimensions, similarity threshold, decay + - Credentials (`~/.config/workflows/credentials.json`, `0600`): API key, unless the env var is already set - Project init (`.workflows/.knowledge/`): directory, config, empty store - Initial indexing of all existing completed artifacts - - Stub mode (keyword-only) if user skips the API key step + - Stub mode (keyword-only) if user skips the provider step 3. **User re-runs their workflow** — check passes, skill proceeds normally. `knowledge setup` is the single entry point for all first-time setup. Interactive throughout — Claude cannot run it. Handles both system-level and project-level initialisation in one flow. If system config already exists, skips to project init. If everything exists, no-op. @@ -625,12 +638,14 @@ knowledge status # full health report **`knowledge setup`** - **Interactive wizard** — handles all first-time setup in one flow: - 1. System config (`~/.config/workflows/config.json`): provider, model, API key env var, test embed call to validate - 2. Project init (`.workflows/.knowledge/`): directory, config, empty store - 3. Initial indexing of all existing completed artifacts via `knowledge index` (no args) + 1. System config (`~/.config/workflows/config.json`): provider, model, dimensions, similarity threshold, decay + 2. Credentials (`~/.config/workflows/credentials.json`, `0600`): API key, stored only if the provider-specific env var is not already set (env wins) + 3. Test embed call to validate the key + 4. Project init (`.workflows/.knowledge/`): directory, config, empty store + 5. Initial indexing of all existing completed artifacts via `knowledge index` (no args) - Skips steps that are already done (system config exists → skip to project init; project exists → skip to indexing) - **Human-only** — interactive prompts throughout. Claude cannot run it -- Stub mode available if user skips the API key step +- Stub mode available if user skips the provider step **No migration.** Entry-point skills check `knowledge check` in Step 0. If not initialised, a reference file displays a message and instructs the user to run `knowledge setup`. Hard stop. diff --git a/src/knowledge/config.js b/src/knowledge/config.js index deff26229..41670462e 100644 --- a/src/knowledge/config.js +++ b/src/knowledge/config.js @@ -25,6 +25,12 @@ const DEFAULTS = { // Known providers that have implementations in this codebase. const AVAILABLE_PROVIDERS = ['stub', 'openai']; +// Hardcoded env var per provider. The env var wins over credentials.json — +// power users and CI can override the stored key without editing files. +const PROVIDER_ENV_VARS = { + openai: 'OPENAI_API_KEY', +}; + /** * Resolve the system config path. * @returns {string} @@ -42,6 +48,14 @@ function projectConfigPath(cwd) { return path.join(cwd || process.cwd(), '.workflows', '.knowledge', 'config.json'); } +/** + * Resolve the credentials file path. Sits alongside system config. + * @returns {string} + */ +function credentialsPath() { + return path.join(os.homedir(), '.config', 'workflows', 'credentials.json'); +} + /** * Read a single config file and return the unwrapped `knowledge` object. * Returns null if the file does not exist. @@ -83,10 +97,140 @@ function readConfigFile(filePath) { return parsed.knowledge; } +/** + * Read the credentials file and return the unwrapped `credentials` object. + * Returns null if the file does not exist. Throws on invalid JSON or a + * missing `credentials` wrapper so the caller can surface the error + * rather than silently ignoring a broken file. + * + * @param {string} filePath + * @returns {object|null} + */ +function loadCredentials(filePath) { + if (!fs.existsSync(filePath)) return null; + + let raw; + try { + raw = fs.readFileSync(filePath, 'utf8'); + } catch (e) { + throw new Error(`Failed to read credentials file at ${filePath}: ${e.message}`); + } + + let parsed; + try { + parsed = JSON.parse(raw); + } catch (e) { + throw new Error(`Invalid JSON in credentials file at ${filePath}: ${e.message}`); + } + + if (parsed == null || typeof parsed !== 'object' || !parsed.credentials || + typeof parsed.credentials !== 'object' || Array.isArray(parsed.credentials)) { + throw new Error( + `Credentials file at ${filePath} is missing the required top-level "credentials" object. ` + + 'Expected format: { "credentials": { "": { "api_key": "..." } } }' + ); + } + + return parsed.credentials; +} + +/** + * Atomically write the credentials file with mode 0600 (user-private). + * Merges with existing credentials so writing openai does not clobber + * other providers. Use null apiKey to delete a provider's entry. + * + * @param {string} filePath + * @param {string} provider e.g. 'openai' + * @param {string|null} apiKey null removes the entry + */ +function writeCredentials(filePath, provider, apiKey) { + if (!filePath) throw new Error('writeCredentials: filePath is required'); + if (!provider || typeof provider !== 'string') { + throw new Error('writeCredentials: provider name is required'); + } + + let existing = {}; + if (fs.existsSync(filePath)) { + try { + existing = loadCredentials(filePath) || {}; + } catch (_) { + // Corrupt file — overwrite with a fresh structure rather than + // propagating the read error, since the caller is committing to a + // write. + existing = {}; + } + } + + const credentials = Object.assign({}, existing); + if (apiKey === null || apiKey === undefined) { + delete credentials[provider]; + } else { + credentials[provider] = Object.assign({}, credentials[provider] || {}, { api_key: apiKey }); + } + + const payload = { credentials }; + + const dir = path.dirname(filePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + const tmp = filePath + '.tmp'; + // Open with mode 0600 so the file is user-private from the first byte + // written — close/rename sequence keeps that mode. + const fd = fs.openSync(tmp, 'w', 0o600); + try { + fs.writeSync(fd, JSON.stringify(payload, null, 2) + '\n'); + } finally { + fs.closeSync(fd); + } + fs.chmodSync(tmp, 0o600); + fs.renameSync(tmp, filePath); + // Rename preserves permissions, but chmod again defensively on the + // final path for systems where rename semantics differ. + try { fs.chmodSync(filePath, 0o600); } catch (_) { /* best effort */ } +} + +/** + * Resolve the API key for a provider. Env var takes precedence over the + * credentials file. Returns null if neither source provides a non-empty + * value. + * + * @param {string} provider + * @param {{ credentialsPath?: string }} [opts] + * @returns {string|null} + */ +function resolveApiKey(provider, opts) { + if (!provider) return null; + + const envVar = PROVIDER_ENV_VARS[provider]; + if (envVar) { + const envVal = process.env[envVar]; + if (envVal && envVal.trim() !== '') return envVal; + } + + const credPath = (opts && opts.credentialsPath) || credentialsPath(); + let creds; + try { + creds = loadCredentials(credPath); + } catch (_) { + // Bad credentials file — treat as missing for resolution. A future + // `knowledge doctor` command could surface the error to the user. + return null; + } + + if (creds && creds[provider] && typeof creds[provider].api_key === 'string') { + const k = creds[provider].api_key.trim(); + if (k !== '') return k; + } + + return null; +} + /** * Load and merge config from system and project levels. * - * @param {{ systemPath?: string, projectPath?: string }} [paths] + * @param {{ systemPath?: string, projectPath?: string, credentialsPath?: string }} [paths] * Override default paths (for testing). * @returns {object} Merged config with defaults applied. */ @@ -111,13 +255,11 @@ function loadConfig(paths) { } } - // Resolve API key from environment. - if (merged.api_key_env) { - const envVal = process.env[merged.api_key_env]; - merged._api_key = envVal && envVal.trim() !== '' ? envVal : null; - } else { - merged._api_key = null; - } + // Resolve API key via env-then-credentials-file precedence. + merged._api_key = resolveApiKey( + merged.provider, + { credentialsPath: paths && paths.credentialsPath } + ); return merged; } @@ -204,10 +346,15 @@ function writeConfigFile(filePath, payload) { module.exports = { DEFAULTS, AVAILABLE_PROVIDERS, + PROVIDER_ENV_VARS, systemConfigPath, projectConfigPath, + credentialsPath, readConfigFile, loadConfig, + loadCredentials, + writeCredentials, + resolveApiKey, resolveProvider, writeConfigFile, }; diff --git a/tests/scripts/test-knowledge-config.cjs b/tests/scripts/test-knowledge-config.cjs index 9a7734bc6..560deb7c0 100644 --- a/tests/scripts/test-knowledge-config.cjs +++ b/tests/scripts/test-knowledge-config.cjs @@ -6,7 +6,17 @@ const fs = require('fs'); const path = require('path'); const os = require('os'); -const { loadConfig, readConfigFile, resolveProvider, writeConfigFile, DEFAULTS } = require('../../src/knowledge/config'); +const { + loadConfig, + readConfigFile, + resolveProvider, + writeConfigFile, + loadCredentials, + writeCredentials, + resolveApiKey, + DEFAULTS, + PROVIDER_ENV_VARS, +} = require('../../src/knowledge/config'); const { StubProvider } = require('../../src/knowledge/embeddings'); const { buildSystemConfigOpenAI, @@ -122,56 +132,109 @@ describe('loadConfig', () => { assert.strictEqual(cfg.decay_months, 6); // system falls through }); - it('resolves api_key_env from environment', () => { + it('resolves api key from OPENAI_API_KEY when provider is openai', () => { const sysPath = path.join(tmpDir, 'sys.json'); - writeJSON(sysPath, { knowledge: { api_key_env: 'TEST_KB_KEY' } }); - const oldVal = process.env.TEST_KB_KEY; - process.env.TEST_KB_KEY = 'sk-test-123'; + writeJSON(sysPath, { knowledge: { provider: 'openai' } }); + const oldVal = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = 'sk-test-123'; try { const cfg = loadConfig({ systemPath: sysPath, projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: path.join(tmpDir, 'credentials.json'), }); assert.strictEqual(cfg._api_key, 'sk-test-123'); } finally { - if (oldVal === undefined) delete process.env.TEST_KB_KEY; - else process.env.TEST_KB_KEY = oldVal; + if (oldVal === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = oldVal; } }); - it('returns null api key when env var is not set', () => { + it('returns null api key when env var is not set and no credentials file', () => { const sysPath = path.join(tmpDir, 'sys.json'); - writeJSON(sysPath, { knowledge: { api_key_env: 'TEST_KB_MISSING_VAR' } }); - const oldVal = process.env.TEST_KB_MISSING_VAR; - delete process.env.TEST_KB_MISSING_VAR; + writeJSON(sysPath, { knowledge: { provider: 'openai' } }); + const oldVal = process.env.OPENAI_API_KEY; + delete process.env.OPENAI_API_KEY; try { const cfg = loadConfig({ systemPath: sysPath, projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: path.join(tmpDir, 'credentials.json'), }); assert.strictEqual(cfg._api_key, null); } finally { - if (oldVal !== undefined) process.env.TEST_KB_MISSING_VAR = oldVal; + if (oldVal !== undefined) process.env.OPENAI_API_KEY = oldVal; } }); - it('returns null api key when env var is empty string', () => { + it('returns null api key when env var is empty string and no credentials file', () => { const sysPath = path.join(tmpDir, 'sys.json'); - writeJSON(sysPath, { knowledge: { api_key_env: 'TEST_KB_EMPTY' } }); - const oldVal = process.env.TEST_KB_EMPTY; - process.env.TEST_KB_EMPTY = ''; + writeJSON(sysPath, { knowledge: { provider: 'openai' } }); + const oldVal = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = ''; try { const cfg = loadConfig({ systemPath: sysPath, projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: path.join(tmpDir, 'credentials.json'), }); assert.strictEqual(cfg._api_key, null); } finally { - if (oldVal === undefined) delete process.env.TEST_KB_EMPTY; - else process.env.TEST_KB_EMPTY = oldVal; + if (oldVal === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('falls back to credentials file when env var is not set', () => { + const sysPath = path.join(tmpDir, 'sys.json'); + const credPath = path.join(tmpDir, 'credentials.json'); + writeJSON(sysPath, { knowledge: { provider: 'openai' } }); + writeJSON(credPath, { credentials: { openai: { api_key: 'sk-from-file' } } }); + const oldVal = process.env.OPENAI_API_KEY; + delete process.env.OPENAI_API_KEY; + try { + const cfg = loadConfig({ + systemPath: sysPath, + projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: credPath, + }); + assert.strictEqual(cfg._api_key, 'sk-from-file'); + } finally { + if (oldVal !== undefined) process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('env var wins over credentials file when both are set', () => { + const sysPath = path.join(tmpDir, 'sys.json'); + const credPath = path.join(tmpDir, 'credentials.json'); + writeJSON(sysPath, { knowledge: { provider: 'openai' } }); + writeJSON(credPath, { credentials: { openai: { api_key: 'sk-from-file' } } }); + const oldVal = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = 'sk-from-env'; + try { + const cfg = loadConfig({ + systemPath: sysPath, + projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: credPath, + }); + assert.strictEqual(cfg._api_key, 'sk-from-env'); + } finally { + if (oldVal === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = oldVal; } }); + it('returns null api key when provider is not configured', () => { + const sysPath = path.join(tmpDir, 'sys.json'); + writeJSON(sysPath, { knowledge: {} }); + const cfg = loadConfig({ + systemPath: sysPath, + projectPath: path.join(tmpDir, 'proj.json'), + credentialsPath: path.join(tmpDir, 'credentials.json'), + }); + assert.strictEqual(cfg._api_key, null); + }); + it('ignores unknown fields without error (forward compatibility)', () => { const sysPath = path.join(tmpDir, 'sys.json'); writeJSON(sysPath, { knowledge: { provider: 'stub', future_field: 'whatever' } }); @@ -239,6 +302,199 @@ describe('resolveProvider', () => { }); }); +// --------------------------------------------------------------------------- +// loadCredentials +// --------------------------------------------------------------------------- + +describe('loadCredentials', () => { + beforeEach(setup); + afterEach(teardown); + + it('returns null when the file does not exist', () => { + const result = loadCredentials(path.join(tmpDir, 'missing.json')); + assert.strictEqual(result, null); + }); + + it('reads a credentials file and returns the unwrapped credentials object', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeJSON(filePath, { credentials: { openai: { api_key: 'sk-123' } } }); + const result = loadCredentials(filePath); + assert.deepStrictEqual(result, { openai: { api_key: 'sk-123' } }); + }); + + it('throws for invalid JSON', () => { + const filePath = path.join(tmpDir, 'bad.json'); + fs.writeFileSync(filePath, '{not json', 'utf8'); + assert.throws(() => loadCredentials(filePath), /Invalid JSON/); + }); + + it('throws when credentials key is missing', () => { + const filePath = path.join(tmpDir, 'nowrap.json'); + writeJSON(filePath, { openai: { api_key: 'sk-x' } }); + assert.throws(() => loadCredentials(filePath), /missing the required top-level "credentials" object/); + }); + + it('throws when credentials key is not an object', () => { + const filePath = path.join(tmpDir, 'arr.json'); + writeJSON(filePath, { credentials: [] }); + assert.throws(() => loadCredentials(filePath), /missing the required top-level "credentials" object/); + }); +}); + +// --------------------------------------------------------------------------- +// writeCredentials +// --------------------------------------------------------------------------- + +describe('writeCredentials', () => { + beforeEach(setup); + afterEach(teardown); + + it('writes a credentials file with the expected shape', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-123'); + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + assert.deepStrictEqual(parsed, { credentials: { openai: { api_key: 'sk-123' } } }); + }); + + it('writes the file with mode 0600 (user-private)', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-123'); + const stat = fs.statSync(filePath); + // Extract the permission bits from the mode — drop higher bits. + const mode = stat.mode & 0o777; + assert.strictEqual(mode, 0o600); + }); + + it('creates parent directories when they do not exist', () => { + const filePath = path.join(tmpDir, 'nested', 'a', 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-1'); + assert.ok(fs.existsSync(filePath)); + }); + + it('merges with existing credentials (no clobber)', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-openai'); + writeCredentials(filePath, 'anthropic', 'sk-anthropic'); + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + assert.strictEqual(parsed.credentials.openai.api_key, 'sk-openai'); + assert.strictEqual(parsed.credentials.anthropic.api_key, 'sk-anthropic'); + }); + + it('removes a provider entry when apiKey is null', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-openai'); + writeCredentials(filePath, 'anthropic', 'sk-anthropic'); + writeCredentials(filePath, 'openai', null); + const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + assert.strictEqual(parsed.credentials.openai, undefined); + assert.strictEqual(parsed.credentials.anthropic.api_key, 'sk-anthropic'); + }); + + it('uses atomic write (no .tmp left behind on success)', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + writeCredentials(filePath, 'openai', 'sk-1'); + assert.ok(!fs.existsSync(filePath + '.tmp')); + }); + + it('rejects a missing provider name', () => { + const filePath = path.join(tmpDir, 'credentials.json'); + assert.throws(() => writeCredentials(filePath, '', 'sk-1'), /provider name is required/); + assert.throws(() => writeCredentials(filePath, null, 'sk-1'), /provider name is required/); + }); +}); + +// --------------------------------------------------------------------------- +// resolveApiKey — precedence (env wins) and fallback behaviour +// --------------------------------------------------------------------------- + +describe('resolveApiKey', () => { + beforeEach(setup); + afterEach(teardown); + + it('returns the env var value when set', () => { + const oldVal = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = 'sk-env'; + try { + const credPath = path.join(tmpDir, 'credentials.json'); + const k = resolveApiKey('openai', { credentialsPath: credPath }); + assert.strictEqual(k, 'sk-env'); + } finally { + if (oldVal === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('falls back to credentials file when env var is not set', () => { + const oldVal = process.env.OPENAI_API_KEY; + delete process.env.OPENAI_API_KEY; + const credPath = path.join(tmpDir, 'credentials.json'); + writeJSON(credPath, { credentials: { openai: { api_key: 'sk-file' } } }); + try { + const k = resolveApiKey('openai', { credentialsPath: credPath }); + assert.strictEqual(k, 'sk-file'); + } finally { + if (oldVal !== undefined) process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('returns null when neither source provides a key', () => { + const oldVal = process.env.OPENAI_API_KEY; + delete process.env.OPENAI_API_KEY; + try { + const credPath = path.join(tmpDir, 'credentials.json'); + const k = resolveApiKey('openai', { credentialsPath: credPath }); + assert.strictEqual(k, null); + } finally { + if (oldVal !== undefined) process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('returns null for providers with no registered env var', () => { + const k = resolveApiKey('unknown-provider', { + credentialsPath: path.join(tmpDir, 'credentials.json'), + }); + assert.strictEqual(k, null); + }); + + it('returns null when provider is missing/empty', () => { + assert.strictEqual(resolveApiKey(null), null); + assert.strictEqual(resolveApiKey(''), null); + }); + + it('treats a whitespace-only env var as unset and falls back to file', () => { + const oldVal = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = ' '; + const credPath = path.join(tmpDir, 'credentials.json'); + writeJSON(credPath, { credentials: { openai: { api_key: 'sk-file' } } }); + try { + const k = resolveApiKey('openai', { credentialsPath: credPath }); + assert.strictEqual(k, 'sk-file'); + } finally { + if (oldVal === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = oldVal; + } + }); + + it('returns null when credentials file is corrupt (swallowed, not thrown)', () => { + const oldVal = process.env.OPENAI_API_KEY; + delete process.env.OPENAI_API_KEY; + const credPath = path.join(tmpDir, 'credentials.json'); + fs.writeFileSync(credPath, '{not json', 'utf8'); + try { + const k = resolveApiKey('openai', { credentialsPath: credPath }); + assert.strictEqual(k, null); + } finally { + if (oldVal !== undefined) process.env.OPENAI_API_KEY = oldVal; + } + }); +}); + +describe('PROVIDER_ENV_VARS', () => { + it('maps openai to OPENAI_API_KEY', () => { + assert.strictEqual(PROVIDER_ENV_VARS.openai, 'OPENAI_API_KEY'); + }); +}); + // --------------------------------------------------------------------------- // writeConfigFile // --------------------------------------------------------------------------- From 9ef31bb21b2c387093cf187530d42bf1c6777dcf Mon Sep 17 00:00:00 2001 From: Lee Overy Date: Sun, 19 Apr 2026 19:46:39 +0100 Subject: [PATCH 4/5] feat(knowledge): wizard stores API key in credentials.json MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrites the openai branch of the setup wizard to match the hybrid credential model introduced in the previous commit. Flow becomes: 1. Prompt for model and dimensions. 2. Write the non-secret system config to disk (can be kept even if the key step aborts or the user Ctrl-Cs mid-key-entry). 3. Resolve the API key via the same precedence loadConfig uses: a. $OPENAI_API_KEY if set — validate inline, nothing written. b. Existing credentials.json — validate; if broken, offer to replace with an inline prompt. c. No key anywhere — show the explainer (portal link, dedicated- key recommendation, where it's stored, env-override escape hatch), prompt inline, validate, write to credentials.json. Secret input is read through a new askSecret helper: stdin goes into raw mode during the key prompt, each character is echoed as a '*' so the key never touches terminal scrollback. Ctrl-C aborts cleanly, Ctrl-D submits, backspace edits. Validation failures route through describeValidationError, which maps common OpenAI responses (401, 403, 429, 5xx, network errors) to a short cause line plus a practical next-step hint — no raw "Provider/model changed" errors bubble up to the user. The api_key_env field is gone from buildSystemConfigOpenAI and from every wizard prompt. Config.js already ignored it on read. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../workflow-knowledge/scripts/knowledge.cjs | 192 +++++++----- src/knowledge/setup.js | 282 ++++++++++++++++-- tests/scripts/test-knowledge-config.cjs | 38 ++- 3 files changed, 398 insertions(+), 114 deletions(-) diff --git a/skills/workflow-knowledge/scripts/knowledge.cjs b/skills/workflow-knowledge/scripts/knowledge.cjs index 6bc97f601..3820f6b31 100644 --- a/skills/workflow-knowledge/scripts/knowledge.cjs +++ b/skills/workflow-knowledge/scripts/knowledge.cjs @@ -1,44 +1,48 @@ -"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=b(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.SUPPORTED_LANGUAGES=V.SPLITTERS=V.STEMMERS=void 0;V.getLocale=oc;V.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};V.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};V.SUPPORTED_LANGUAGES=Object.keys(V.STEMMERS);function oc(t){return t!==void 0&&V.SUPPORTED_LANGUAGES.includes(t)?V.STEMMERS[t]:void 0}});var L=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=lc;O.sprintf=dc;O.formatBytes=fc;O.isInsideWebWorker=zr;O.isInsideNode=Vr;O.getNanosecondTimeViaPerformance=fn;O.formatNanoseconds=hc;O.getNanosecondsTime=pc;O.uniqueId=gc;O.getOwnProperty=yc;O.getTokenFrequency=mc;O.insertSortedValue=wc;O.sortTokenScorePredicate=Wr;O.intersect=_c;O.getDocumentProperties=Kr;O.getNested=Sc;O.flattenObject=Hr;O.convertDistanceToMeters=Ic;O.removeVectorsFromHits=xc;O.isPromise=Ec;O.isAsyncFunction=Gr;O.setIntersection=Ac;O.setUnion=Tc;O.setDifference=Dc;O.sleep=Mc;var cc=j(),uc=Date.now().toString().slice(5),ac=0,Fr=1024,Cr=BigInt(1e3),Br=BigInt(1e6),qr=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function lc(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[l,d]=s.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(a=a.toFixed(d)),typeof l=="number"&&l>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function fc(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log(Fr));return`${parseFloat((t/Math.pow(Fr,s)).toFixed(n))} ${r[s]}`}function zr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Vr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function fn(){return BigInt(Math.floor(performance.now()*1e6))}function hc(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Wr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function _c(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Kr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function Ec(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Gr(t){return Array.isArray(t)?t.some(e=>Gr(e)):t?.constructor?.name==="AsyncFunction"}var $r="intersection"in new Set;function Ac(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if($r)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var j=b(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.createError=Uc;var Oc=lt(),Pc=L(),kc=Oc.SUPPORTED_LANGUAGES.join(` - - `),Nc={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. +"use strict";var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lt=b(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.SUPPORTED_LANGUAGES=K.SPLITTERS=K.STEMMERS=void 0;K.getLocale=hc;K.STEMMERS={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};K.SPLITTERS={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim,czech:/[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim};K.SUPPORTED_LANGUAGES=Object.keys(K.STEMMERS);function hc(t){return t!==void 0&&K.SUPPORTED_LANGUAGES.includes(t)?K.STEMMERS[t]:void 0}});var R=b(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.MAX_ARGUMENT_FOR_STACK=O.isServer=void 0;O.safeArrayPush=mc;O.sprintf=wc;O.formatBytes=_c;O.isInsideWebWorker=Kr;O.isInsideNode=Hr;O.getNanosecondTimeViaPerformance=gn;O.formatNanoseconds=Sc;O.getNanosecondsTime=bc;O.uniqueId=Ic;O.getOwnProperty=xc;O.getTokenFrequency=Ec;O.insertSortedValue=Ac;O.sortTokenScorePredicate=Gr;O.intersect=vc;O.getDocumentProperties=Yr;O.getNested=Tc;O.flattenObject=Jr;O.convertDistanceToMeters=Mc;O.removeVectorsFromHits=Oc;O.isPromise=Pc;O.isAsyncFunction=Xr;O.setIntersection=kc;O.setUnion=Uc;O.setDifference=Rc;O.sleep=Lc;var pc=j(),gc=Date.now().toString().slice(5),yc=0,$r=1024,qr=BigInt(1e3),zr=BigInt(1e6),Vr=BigInt(1e9);O.isServer=typeof window>"u";O.MAX_ARGUMENT_FOR_STACK=65535;function mc(t,e){if(e.length\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g,function(...n){let r=n[n.length-1],{width:s,type:i,position:o}=r,c=o?e[Number.parseInt(o)-1]:e.shift(),u=s===""?0:Number.parseInt(s);switch(i){case"d":return c.toString().padStart(u,"0");case"f":{let a=c,[l,d]=s.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(a=a.toFixed(d)),typeof l=="number"&&l>=0?a.toString().padStart(u,"0"):a.toString()}case"s":return u<0?c.toString().padEnd(-u," "):c.toString().padStart(u," ");default:return c}})}function _c(t,e=2){if(t===0)return"0 Bytes";let n=e<0?0:e,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(t)/Math.log($r));return`${parseFloat((t/Math.pow($r,s)).toFixed(n))} ${r[s]}`}function Kr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Hr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function gn(){return BigInt(Math.floor(performance.now()*1e6))}function Sc(t){return typeof t=="number"&&(t=BigInt(t)),t>>1,n(e,t[i])<0?s=i:r=i+1;return t.splice(r,0,e),t}function Gr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function vc(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Yr(t,e){let n={},r=e.length;for(let s=0;s({...n,document:{...n.document,...e.reduce((r,s)=>{let i=s.split("."),o=i.pop(),c=r;for(let u of i)c[u]=c[u]??{},c=c[u];return c[o]=null,r},n.document)}}))}function Pc(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Xr(t){return Array.isArray(t)?t.some(e=>Xr(e)):t?.constructor?.name==="AsyncFunction"}var Wr="intersection"in new Set;function kc(...t){if(t.length===0)return new Set;if(t.length===1)return t[0];if(t.length===2){let r=t[0],s=t[1];if(Wr)return r.intersection(s);let i=new Set,o=r.size0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))}else{if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););}}});var j=b(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.createError=$c;var jc=lt(),Cc=R(),Fc=jc.SUPPORTED_LANGUAGES.join(` + - `),Bc={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported. Supported languages are: - - ${kc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. + - ${Fc}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance. Please install it before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy `,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration. Please provide a chat model before proceeding with creating an answer session. Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy -`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function Uc(t,...e){let n=new Error((0,Pc.sprintf)(Nc[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var Be=b(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.getDocumentProperties=void 0;W.formatElapsedTime=Rc;W.getDocumentIndexId=jc;W.validateSchema=Jr;W.isGeoPointType=Bc;W.isVectorType=Xr;W.isArrayType=Zr;W.getInnerType=Qr;W.getVectorSize=es;var dt=j(),Yr=L(),Lc=L();Object.defineProperty(W,"getDocumentProperties",{enumerable:!0,get:function(){return Lc.getDocumentProperties}});function Rc(t){return{raw:Number(t),formatted:(0,Yr.formatNanoseconds)(t)}}function jc(t){if(t.id){if(typeof t.id!="string")throw(0,dt.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,Yr.uniqueId)()}function Jr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.createInternalDocumentIDStore=qc;be.save=ts;be.load=ns;be.getInternalDocumentId=rs;be.getDocumentIdFromInternalId=$c;function qc(){return{idToInternalId:new Map,internalIdToId:[],save:ts,load:ns}}function ts(t){return{internalIdToId:t.internalIdToId}}function ns(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?rs(t,e.toString()):e}function $c(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.create=ss;K.get=is;K.getMultiple=os;K.getAll=cs;K.store=us;K.remove=as;K.count=ls;K.load=ds;K.save=fs;K.createDocumentsStore=zc;var pn=$();function ss(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function is(t,e){let n=(0,pn.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function os(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function ls(t){return t.count}function ds(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function fs(t){return{docs:t.docs,count:t.count}}function zc(){return{create:ss,get:is,getMultiple:os,getAll:cs,store:us,remove:as,count:ls,load:ds,save:fs}}});var hs=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.AVAILABLE_PLUGIN_HOOKS=void 0;qe.getAllPluginsByHook=Wc;var Vc=j();qe.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function Wc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.SINGLE_OR_ARRAY_COMPONENTS=z.FUNCTION_COMPONENTS=z.OBJECT_COMPONENTS=void 0;z.runSingleHook=Kc;z.runMultipleHook=Hc;z.runAfterSearch=Gc;z.runBeforeSearch=Yc;z.runAfterCreate=Jc;var $e=L();z.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];z.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];z.SINGLE_OR_ARRAY_COMPONENTS=[];function Kc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Hc(t,e,n){if(t.some($e.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function Gc(t,e,n,r,s){if(t.some($e.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function Yc(t,e,n,r){if(t.some($e.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function Jc(t,e){if(t.some($e.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var ps=b(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.AVLTree=Me.AVLNode=void 0;var ue=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Me.AVLNode=ue;var yn=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ue(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ue.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ue(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ue(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:l,node:d}=i[a];if(d.updateHeight(),u){let f=this.rebalanceNode(d);l?l.l===d?l.l=f:l.r===d&&(l.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Me.AVLTree=yn});var gs=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FlatTree=void 0;var mn=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ft.FlatTree=mn});var wn=b(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.boundedLevenshtein=Xc;ze.syncBoundedLevenshtein=Zc;ze.levenshtein=Qc;function ys(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function Xc(t,e,n){let r=ys(t,e,n);return{distance:r,isBounded:r>=0}}function Zc(t,e,n){let r=ys(t,e,n);return{distance:r,isBounded:r>=0}}function Qc(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var ws=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.RadixTree=Oe.RadixNode=void 0;var ms=wn(),_n=L(),Ve=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,_n.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,ms.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,_n.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let l of u)a.includes(l)||a.push(l)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:d,d:f}=c;if(d&&((0,ms.syncBoundedLevenshtein)(e,d,s).isBounded&&(i[d]=[]),(0,_n.getOwnProperty)(i,d)!==void 0&&f.size>0)){let p=new Set(i[d]);for(let g of f)p.add(g);i[d]=Array.from(p)}}if(u>=e.length)continue;let l=e[u];if(c.c.has(l)){let d=c.c.get(l);o.push({node:d,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[d,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),d!==l&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};Oe.RadixNode=Ve;var Sn=class t extends Ve{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,Ve.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};Oe.RadixTree=Sn});var _s=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.BKDTree=void 0;var eu=2,tu=6371e3,ht=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},bn=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ht(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%eu===0)if(e.lon0;){let{node:a,depth:l}=c.pop();if(a==null)continue;let d=o(e,a.point);(r?d<=n:d>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:l+1}),a.right!=null&&c.push({node:a.right,depth:l+1})}return s&&u.sort((a,l)=>{let d=o(e,a.point),f=o(e,l.point);return s.toLowerCase()==="asc"?d-f:f-d}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let l=t.isPointInPolygon(e,u.point);(l&&n||!l&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,l)=>{let d=u(c,a.point),f=u(c,l.point);return r.toLowerCase()==="asc"?d-f:f-d})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ht.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(d-a)*(i-l)/(f-l)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return tu*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,l=Math.atan((1-s)*Math.tan(c)),d=Math.atan((1-s)*Math.tan(u)),f=Math.sin(l),p=Math.cos(l),g=Math.sin(d),y=Math.cos(d),h=a,m,w=1e3,S,_,I,v,D,A;do{let De=Math.sin(h),Ce=Math.cos(h);if(S=Math.sqrt(y*De*(y*De)+(p*g-f*y*Ce)*(p*g-f*y*Ce)),S===0)return 0;_=f*g+p*y*Ce,I=Math.atan2(S,_),v=p*y*De/S,D=1-v*v,A=_-2*f*g/D,isNaN(A)&&(A=0);let dn=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-dn)*s*v*(I+dn*S*(A+dn*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),Te=1+k/16384*(4096+k*(-768+k*(320-175*k))),J=k/1024*(256+k*(-128+k*(74-47*k))),ln=J*S*(A+J/4*(_*(-1+2*A*A)-J/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*Te*(I-ln)}};pt.BKDTree=bn});var Ss=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.BoolNode=void 0;var In=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};gt.BoolNode=In});var bs=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.prioritizeTokenScores=ru;yt.BM25=su;var nu=j();function ru(t,e,n=0,r){if(e===0)throw(0,nu.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let l=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];d=0}let f=l.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.VectorIndex=ae.DEFAULT_SIMILARITY=void 0;ae.getMagnitude=En;ae.findSimilarVectors=Is;ae.DEFAULT_SIMILARITY=.8;var xn=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=En(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),Is(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};ae.VectorIndex=xn;function En(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var mt=b(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.insertDocumentScoreParameters=Ps;R.insertTokenScoreParameters=ks;R.removeDocumentScoreParameters=Ns;R.removeTokenScoreParameters=Us;R.create=Tn;R.insert=Ls;R.insertVector=Rs;R.remove=js;R.calculateResultScores=Dn;R.search=Fs;R.searchByWhereClause=We;R.getSearchableProperties=Cs;R.getSearchablePropertiesWithTypes=Bs;R.load=qs;R.save=$s;R.createIndex=cu;R.searchByGeoWhereClause=au;var Pe=j(),vs=ps(),Ts=gs(),Ds=ws(),Ke=_s(),Ms=Ss(),te=L(),iu=bs(),Ie=Be(),vn=$(),Os=An();function Ps(t,e,n,r,s){let i=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function ks(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function Ns(t,e,n,r){let s=(0,vn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function Us(t,e,n){t.tokenOccurrences[e][n]--}function Tn(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){Tn(t,e,o,r,c);continue}if((0,Ie.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new Os.VectorIndex((0,Ie.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new Ms.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new vs.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new Ds.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new Ts.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new Ke.BKDTree,isArray:u};break;default:throw(0,Pe.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function ou(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:l}=e.indexes[n];switch(a){case"Bool":{l[u?"true":"false"].add(r);break}case"AVL":{let d=c?.avlRebalanceThreshold??1;l.insert(u,r,d);break}case"Radix":{let d=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,d,o);for(let f of d)t.insertTokenScoreParameters(e,n,r,d,f),l.insert(f,r);break}case"Flat":{l.insert(u,r);break}case"BKD":{l.insert(u,[r]);break}}}}function Ls(t,e,n,r,s,i,o,c,u,a,l){if((0,Ie.isVectorType)(o))return Rs(e,n,i,r,s);let d=ou(t,e,n,s,c,u,a,l);if(!(0,Ie.isArrayType)(o))return d(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let ln=J.length;for(let at=0;at[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(d===1)return m;if(d===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(v=>v===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([v])=>v===I)),_=Math.ceil(S.length*d);return[...w,...S.slice(0,_)]}return m}function We(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>We(t,e,u,r));return(0,te.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>We(t,e,u,r)).reduce((u,a)=>(0,te.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let l=1;l<=u.internalIdToId.length;l++)c.add(l);let a=We(t,e,o,r);return(0,te.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,Pe.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:l}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,te.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,te.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=Es(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=Es(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=lu(i[o],y)}}continue}let d=Object.keys(c);if(d.length>1)throw(0,Pe.createError)("INVALID_FILTER_OPERATION",d.length);if(a==="Flat"){let f=new Set(l?u.filterArr(c):u.filter(c));i[o]=(0,te.setUnion)(i[o],f);continue}if(a==="AVL"){let f=d[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,Pe.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,te.setUnion)(i[o],g)}}return(0,te.setIntersection)(...Object.values(i))}function Cs(t){return t.searchableProperties}function Bs(t){return t.searchablePropertiesWithTypes}function qs(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,l={},d={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":l[f]={type:"Radix",node:Ds.RadixTree.fromJSON(p),isArray:y};break;case"Flat":l[f]={type:"Flat",node:Ts.FlatTree.fromJSON(p),isArray:y};break;case"AVL":l[f]={type:"AVL",node:vs.AVLTree.fromJSON(p),isArray:y};break;case"BKD":l[f]={type:"BKD",node:Ke.BKDTree.fromJSON(p),isArray:y};break;case"Bool":l[f]={type:"Bool",node:Ms.BoolNode.fromJSON(p),isArray:y};break;default:l[f]=n[f]}}for(let f of Object.keys(r))d[f]={type:"Vector",isArray:!1,node:Os.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:l,vectorIndexes:d,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function $s(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let d of Object.keys(n))a[d]=n[d].node.toJSON();let l={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:g}=e[d];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?l[d]={type:f,node:p.toJSON(),isArray:g}:(l[d]=e[d],l[d].node=l[d].node.toJSON())}return{indexes:l,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function cu(){return{create:Tn,insert:Ls,remove:js,insertDocumentScoreParameters:Ps,insertTokenScoreParameters:ks,removeDocumentScoreParameters:Ns,removeTokenScoreParameters:Us,calculateResultScores:Dn,search:Fs,searchByWhereClause:We,getSearchableProperties:Cs,getSearchablePropertiesWithTypes:Bs,load:qs,save:$s}}function Es(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function uu(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function au(t,e){let n=t,r=uu(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:l="m",inside:d=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,te.convertDistanceToMeters)(u,l);return c=o.searchByRadius(p,g,d,"asc",f),As(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:l=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",l);let d=Ke.BKDTree.calculatePolygonCentroid(u);return As(c,d,l)}return null}function lu(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.load=Ws;He.save=Ks;He.createSorter=Au;var Mn=j(),du=Be(),wt=$(),fu=L(),hu=lt();function zs(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=zs(t,e,c,r,u);(0,fu.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,du.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,Mn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function pu(t,e,n,r){return r?.enabled!==!1?zs(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function gu(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&On(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function Vs(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)_u(t,n);t.isSorted=!0}function yu(t,e,n){return e[1].localeCompare(n[1],(0,hu.getLocale)(t))}function mu(t,e){return t[1]-e[1]}function wu(t,e){return e[1]?-1:1}function _u(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=yu.bind(null,t.language);break;case"number":r=mu.bind(null);break;case"boolean":r=wu.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function bu(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function Iu(t,e,n){if(!t.enabled)throw(0,Mn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,Mn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return On(t,r),Vs(t),e.sort((o,c)=>{let u=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),l=typeof u<"u",d=typeof a<"u";return!l&&!d?0:l?d?s?a-u:u-a:-1:1}),e}function xu(t){return t.enabled?t.sortableProperties:[]}function Eu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Ws(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,l])=>[+a,l])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Ks(t){if(!t.enabled)return{enabled:!1};Su(t),Vs(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function Au(){return{create:pu,insert:gu,remove:bu,save:Ks,load:Ws,sortBy:Iu,getSortableProperties:xu,getSortablePropertiesWithTypes:Eu}}});var Gs=b(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.replaceDiacritics=Mu;var Hs=192,vu=383,Tu=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Du(t){return tvu?t:Tu[t-Hs]||t}function Mu(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.stemmer=Uu;var Ou={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Pu={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},ku="[^aeiou]",St="[aeiouy]",X=ku+"[^aeiouy]*",Ge=St+"[aeiou]*",Nn="^("+X+")?"+Ge+X,Nu="^("+X+")?"+Ge+X+"("+Ge+")?$",_t="^("+X+")?"+Ge+X+Ge+X,Ys="^("+X+")?"+St;function Uu(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(Nn),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(Ys),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+X+St+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Ys),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Nn),e&&r.test(e)&&(t=e+Ou[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Nn),e&&r.test(e)&&(t=e+Pu[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(_t),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(_t),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(_t),s=new RegExp(Nu),i=new RegExp("^"+X+St+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(_t),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var It=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.normalizeToken=Ln;bt.createTokenizer=Fu;var xe=j(),Lu=Gs(),Zs=lt(),Ru=Js();function Ln(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,Lu.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function ju(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function Xs(t,e,n,r=!0){if(e&&e!==this.language)throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=Zs.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=ju(i);return this.allowDuplicates?o:Array.from(new Set(o))}function Fu(t={}){if(!t.language)t.language="english";else if(!Zs.SUPPORTED_LANGUAGES.includes(t.language))throw(0,xe.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,xe.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=Ru.stemmer;else throw(0,xe.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,xe.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:Xs,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Ln,normalizationCache:new Map};return r.tokenize=Xs.bind(r),r.normalizeToken=Ln,r}});var Rn=b(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.getMatchingRules=Qs;ke.load=ei;ke.save=ti;ke.createPinning=Hu;function Cu(t){return{sharedInternalDocumentStore:t,rules:new Map}}function Bu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function qu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function $u(t,e){return t.rules.delete(e)}function zu(t,e){return t.rules.get(e)}function Vu(t){return Array.from(t.rules.values())}function Wu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Ku(t,e){return t?e.conditions.every(n=>Wu(t,n)):!1}function Qs(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Ku(e,r)&&n.push(r);return n}function ei(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function ti(t){return{rules:Array.from(t.rules.entries())}}function Hu(){return{create:Cu,addRule:Bu,updateRule:qu,removeRule:$u,getRule:zu,getAllRules:Vu,getMatchingRules:Qs,load:ei,save:ti}}});var si=b(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.create=ta;var xt=Be(),Gu=gn(),ni=hs(),Et=ee(),Yu=mt(),Ju=$(),Xu=Pn(),ri=It(),Zu=Rn(),At=j(),Qu=L();function ea(t){let e={formatElapsedTime:xt.formatElapsedTime,getDocumentIndexId:xt.getDocumentIndexId,getDocumentProperties:xt.getDocumentProperties,validateSchema:xt.validateSchema};for(let n of Et.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,At.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Et.OBJECT_COMPONENTS.includes(n)&&!Et.FUNCTION_COMPONENTS.includes(n))throw(0,At.createError)("UNSUPPORTED_COMPONENT",n)}function ta({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,At.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,Qu.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,l=r.pinning;if(o?o.tokenize?o=o:o=(0,ri.createTokenizer)(o):o=(0,ri.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,At.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let d=(0,Ju.createInternalDocumentIDStore)();c||=(0,Yu.createIndex)(),a||=(0,Xu.createSorter)(),u||=(0,Gu.createDocumentsStore)(),l||=(0,Zu.createPinning)(),ea(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:l,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:na()};h.data={index:h.index.create(h,d,t),docs:h.documentsStore.create(h,d),sorting:h.sorter.create(h,d,t,e),pinning:h.pinning.create(d)};for(let w of ni.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,ni.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,Et.runAfterCreate)(m,h),h}function na(){return"{{VERSION}}"}});var Fn=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getByID=ra;vt.count=sa;function ra(t,e){return t.documentsStore.get(t.data.docs,e)}function sa(t){return t.documentsStore.count(t.data.docs)}});var Cn=b(U=>{"use strict";var ii=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ia=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),oa=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ii(e,t,n)},Ye=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.insert=$n;Je.insertMultiple=ha;Je.innerInsertMultiple=pa;var Bn=Cn(),C=L(),Ne=ee(),Ue=j(),qn=$();function $n(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Ue.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?aa(t,e,n,r,s):la(t,e,n,r,s)}var ca=new Set(["enum","enum[]"]),ua=new Set(["string","number"]);async function aa(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];oi(y,h,p,g)}return await da(t,c,l,f,a,n,e,s),r||await(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function la(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Ue.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Ne.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Ue.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];oi(y,h,p,g)}return fa(t,c,l,f,a,n,e,s),r||(0,Ne.runSingleHook)(t.afterInsert,t,c,e),c}function oi(t,e,n,r){if(!((0,Bn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,Bn.isVectorType)(e)&&Array.isArray(r))&&!((0,Bn.isArrayType)(e)&&Array.isArray(r))&&!(ca.has(e)&&ua.has(t))&&t!==e)throw(0,Ue.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function da(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l];await t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function fa(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l],p=(0,qn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function ha(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.afterInsertMultiple)||(0,C.isAsyncFunction)(t.beforeInsertMultiple)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ci(t,e,n,r,s,i):ui(t,e,n,r,s,i)}async function ci(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let l=Math.min(a+n,e.length),d=e.slice(a,l);for(let f of d){let p={avlRebalanceThreshold:d.length},g=await $n(t,f,r,s,p);o.push(g)}return l};return await(async()=>{let a=0;for(;a0){let d=Date.now()-l,f=i-d;f>0&&(0,C.sleep)(f)}}})(),s||await(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ui(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let l=e.slice(c*n,(c+1)*n);if(l.length===0)return!1;for(let d of l){let f={avlRebalanceThreshold:l.length},p=$n(t,d,r,s,f);o.push(p)}return c++,!0}function a(){let l=Date.now();for(;u();)if(i>0){let f=Date.now()-l;if(f>=i){let p=i-f%i;p>0&&(0,C.sleep)(p)}}}return a(),s||(0,Ne.runMultipleHook)(t.afterInsertMultiple,t,e),o}function pa(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.index.beforeInsert)||(0,C.isAsyncFunction)(t.index.insert)||(0,C.isAsyncFunction)(t.index.afterInsert)?ci(t,e,n,r,s,i):ui(t,e,n,r,s,i)}});var ai=b(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.insertPin=ga;Ee.updatePin=ya;Ee.deletePin=ma;Ee.getPin=wa;Ee.getAllPins=_a;function ga(t,e){t.pinning.addRule(t.data.pinning,e)}function ya(t,e){t.pinning.updateRule(t.data.pinning,e)}function ma(t,e){return t.pinning.removeRule(t.data.pinning,e)}function wa(t,e){return t.pinning.getRule(t.data.pinning,e)}function _a(t){return t.pinning.getAllRules(t.data.pinning)}});var Vn=b(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.remove=zn;Dt.removeMultiple=Ia;var de=ee(),fe=$(),le=L();function zn(t,e,n,r){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)?Sa(t,e,n,r):ba(t,e,n,r)}async function Sa(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||await(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function ba(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||(0,de.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,de.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Ia(t,e,n,r,s){return(0,le.isAsyncFunction)(t.index.beforeRemove)||(0,le.isAsyncFunction)(t.index.remove)||(0,le.isAsyncFunction)(t.index.afterRemove)||(0,le.isAsyncFunction)(t.beforeRemoveMultiple)||(0,le.isAsyncFunction)(t.afterRemoveMultiple)?xa(t,e,n,r,s):Ea(t,e,n,r,s)}async function xa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function l(){let d=e.slice(a*n,++a*n);if(!d.length)return c();for(let f of d)try{await zn(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(l,0)}setTimeout(l,0)}),s||await(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function Ea(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,fe.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,fe.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,de.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let l of a)zn(t,l,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,de.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Wn=b(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.MODE_VECTOR_SEARCH=he.MODE_HYBRID_SEARCH=he.MODE_FULLTEXT_SEARCH=void 0;he.MODE_FULLTEXT_SEARCH="fulltext";he.MODE_HYBRID_SEARCH="hybrid";he.MODE_VECTOR_SEARCH="vector"});var Mt=b(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.getFacets=Oa;var Aa=j(),va=L();function Ta(t,e){return t[1]-e[1]}function Da(t,e){return e[1]-t[1]}function Ma(t="desc"){return t.toLowerCase()==="asc"?Ta:Da}function Oa(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let l;if(c[a]==="number"){let{ranges:d}=n[a],f=d.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function di(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Ot=b(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.getGroups=Na;var fi=j(),Hn=L(),Pa=$(),ka={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},hi=["string","number","boolean"];function Na(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,fi.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!hi.includes(i[w]))throw(0,fi.createError)("INVALID_GROUP_BY_PROPERTY",w,hi.join(", "),i[w])}let o=e.map(([m])=>(0,Pa.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,l=[],d={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}l.push(Array.from(_)),d[w]=S}let f=pi(l),p=f.length,g=[];for(let m=0;mv-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),v=S.getInitialValue(w.indexes.length),D=_.reduce(I,v);h[m]={values:w.values,result:D}}return h}function pi(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=pi(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Hn.safeArrayPush)(c,o),s.push(c)}return s}});var Pt=b(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.applyPinningRules=Ra;var Ua=$(),La=Rn();function Ra(t,e,n,r){let s=(0,La.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,Ua.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),l=1e6,d=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?d.push([h,l-m]):t.documentsStore.get(t.data.docs,h)&&d.push([h,0]);d.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of d){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var Jn=b(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.defaultBM25Params=void 0;ne.innerFullTextSearch=mi;ne.fullTextSearch=Ka;var ja=Mt(),Fa=Ot(),gi=ee(),Ca=$(),Ba=mt(),qa=Pt(),$a=j(),kt=L(),za=Fn(),yi=Xe();function mi(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let d=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>d[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let d of s)if(!o.includes(d))throw(0,$a.createError)("UNKNOWN_INDEX",d,o.join(", "));o=o.filter(d=>s.includes(d))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,l=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let d=(0,za.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},Ha(e.relevance),d,u,l),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=Wa(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${Va(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let d=(0,Ba.searchByGeoWhereClause)(i,e.where);d?a=d:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function Va(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wa(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Ka(t,e,n){let r=(0,kt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:l=0,distinctOn:d,includeVectors:f=!1}=e,p=e.preflight===!0,g=mi(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,Ca.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(kt.sortTokenScorePredicate);g=(0,qa.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=d?(0,yi.fetchDocumentsWithDistinct)(t,g,l,a,d):(0,yi.fetchDocuments)(t,g,l,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,kt.removeVectorsFromHits)(h,c)),u){let m=(0,ja.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,Fa.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,kt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,gi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,gi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}ne.defaultBM25Params={k:1.2,b:.75,d:.5};function Ha(t){let e=t??{};return e.k=e.k??ne.defaultBM25Params.k,e.b=e.b??ne.defaultBM25Params.b,e.d=e.d??ne.defaultBM25Params.d,e}});var Rt=b(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.innerVectorSearch=_i;Lt.searchVector=Qa;var Nt=L(),Ga=Mt(),Ut=j(),Ya=Ot(),Ja=$(),wi=ee(),Xa=An(),Za=Pt();function _i(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Ut.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Ut.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Ut.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Ut.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??Xa.DEFAULT_SIMILARITY,c)}function Qa(t,e,n="english"){let r=(0,Nt.getNanosecondsTime)();function s(){let c=_i(t,e,n).sort(Nt.sortTokenScorePredicate);c=(0,Za.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,Ga.getFacets)(t,c,e.facets));let l=e.vector.property,d=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.innerHybridSearch=Ii;Ft.hybridSearch=ol;var jt=L(),el=Mt(),tl=Ot(),nl=Xe(),rl=Jn(),sl=Rt(),Si=ee(),il=Pt();function Ii(t,e,n){let r=cl((0,rl.innerFullTextSearch)(t,e,n)),s=(0,sl.innerVectorSearch)(t,e,n),i=e.hybridWeights;return al(r,s,e.term??"",i)}function ol(t,e,n){let r=(0,jt.getNanosecondsTime)();function s(){let c=Ii(t,e,n);c=(0,il.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,el.getFacets)(t,c,e.facets));let l;e.groupBy&&(l=(0,tl.getGroups)(t,c,e.groupBy));let d=e.offset??0,f=e.limit??10,p=(0,nl.fetchDocuments)(t,c,d,f).filter(Boolean),g=(0,jt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,jt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...l?{groups:l}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,jt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,Si.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,Si.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function Xn(t){return t[1]}function cl(t){let e=Math.max.apply(Math,t.map(Xn));return t.map(([n,r])=>[n,r/e])}function bi(t,e){return t/e}function ul(t,e){return(n,r)=>n*t+r*e}function al(t,e,n,r){let s=Math.max.apply(Math,t.map(Xn)),i=Math.max.apply(Math,e.map(Xn)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:ll(n),a=new Map,l=t.length,d=ul(c,u);for(let p=0;pg[1]-p[1])}function ll(t){return{text:.5,vector:.5}}});var Xe=b(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.search=yl;Ze.fetchDocumentsWithDistinct=ml;Ze.fetchDocuments=wl;var Ei=$(),dl=j(),fl=L(),Ct=Wn(),hl=Jn(),pl=Rt(),gl=xi();function yl(t,e,n){let r=e.mode??Ct.MODE_FULLTEXT_SEARCH;if(r===Ct.MODE_FULLTEXT_SEARCH)return(0,hl.fullTextSearch)(t,e,n);if(r===Ct.MODE_VECTOR_SEARCH)return(0,pl.searchVector)(t,e);if(r===Ct.MODE_HYBRID_SEARCH)return(0,gl.hybridSearch)(t,e);throw(0,dl.createError)("INVALID_SEARCH_MODE",r)}function ml(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,l=0;for(let d=0;d"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,fl.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),l++,!(l<=n)&&(c.push({id:(0,Ei.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),l>=n+r)))break}return c}function wl(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,l]=u;if(!o.has(a)){let d=t.documentsStore.get(s,a);i[c]={id:(0,Ei.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:l,document:d},o.add(a)}}return i}});var Ai=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.load=_l;Bt.save=Sl;function _l(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function Sl(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var Zn=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.update=bl;zt.updateMultiple=El;var pe=ee(),vi=j(),qt=Tt(),$t=Vn(),F=L();function bl(t,e,n,r,s){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)?Il(t,e,n,r,s):xl(t,e,n,r,s)}async function Il(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,pe.runSingleHook)(t.beforeUpdate,t,e),await(0,$t.remove)(t,e,r,s);let i=await(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function xl(t,e,n,r,s){!s&&t.beforeUpdate&&(0,pe.runSingleHook)(t.beforeUpdate,t,e),(0,$t.remove)(t,e,r,s);let i=(0,qt.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,pe.runSingleHook)(t.afterUpdate,t,i),i}function El(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterRemove)||(0,F.isAsyncFunction)(t.beforeRemove)||(0,F.isAsyncFunction)(t.beforeUpdate)||(0,F.isAsyncFunction)(t.afterUpdate)||(0,F.isAsyncFunction)(t.beforeUpdateMultiple)||(0,F.isAsyncFunction)(t.afterUpdateMultiple)||(0,F.isAsyncFunction)(t.beforeRemoveMultiple)||(0,F.isAsyncFunction)(t.afterRemoveMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.afterInsertMultiple)?Al(t,e,n,r,s,i):vl(t,e,n,r,s,i)}async function Al(t,e,n,r,s,i){i||await(0,pe.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.upsert=Tl;Kt.upsertMultiple=Ol;var ge=ee(),Le=j(),Vt=Tt(),Wt=Zn(),P=L();function Tl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Dl(t,e,n,r,s):Ml(t,e,n,r,s)}async function Dl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Wt.update)(t,i,e,n,r):c=await(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ml(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,ge.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Wt.update)(t,i,e,n,r):c=(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,ge.runSingleHook)(t.afterUpsert,t,c,e),c}function Ol(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Pl(t,e,n,r,s):kl(t,e,n,r,s)}async function Pl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=await(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=await(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&await(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function kl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,ge.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&(0,ge.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var Di=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AnswerSession=void 0;var Ht=j(),Nl=Xe(),Ul="orama-secure-proxy",Qn=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,Ht.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,Nl.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===Ul)}let r=await n();if(!r)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};Gt.AnswerSession=Qn});var Mi=b(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.kRemovals=H.kInsertions=H.MODE_VECTOR_SEARCH=H.MODE_HYBRID_SEARCH=H.MODE_FULLTEXT_SEARCH=void 0;var er=Wn();Object.defineProperty(H,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return er.MODE_FULLTEXT_SEARCH}});Object.defineProperty(H,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return er.MODE_HYBRID_SEARCH}});Object.defineProperty(H,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return er.MODE_VECTOR_SEARCH}});H.kInsertions=Symbol("orama.insertions");H.kRemovals=Symbol("orama.removals")});var Oi=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var Ll=wn();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return Ll.boundedLevenshtein}});var re=L();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return re.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return re.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return re.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return re.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return re.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return re.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return re.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return re.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return re.setDifference}});var Rl=It();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return Rl.normalizeToken}})});var Ci=b(x=>{"use strict";var Pi=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Fl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Pi(e,t,n)},ki=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.utf8Count=zl;se.utf8EncodeJs=Bi;se.utf8EncodeTE=qi;se.utf8Encode=Kl;se.utf8DecodeJs=$i;se.utf8DecodeTD=zi;se.utf8Decode=Jl;function zl(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var Vl=new TextEncoder,Wl=50;function qi(t,e,n){Vl.encodeInto(t,e.subarray(n))}function Kl(t,e,n){t.length>Wl?qi(t,e,n):Bi(t,e,n)}var Hl=4096;function $i(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(c);i.length>=Hl&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var Gl=new TextDecoder,Yl=200;function zi(t,e,n){let r=t.subarray(e,e+n);return Gl.decode(r)}function Jl(t,e,n){return n>Yl?zi(t,e,n):$i(t,e,n)}});var nr=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.ExtData=void 0;var tr=class{type;data;constructor(e,n){this.type=e,this.data=n}};Jt.ExtData=tr});var Zt=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DecodeError=void 0;var rr=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Xt.DecodeError=rr});var Qt=b(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.UINT32_MAX=void 0;ye.setUint64=Xl;ye.setInt64=Zl;ye.getInt64=Ql;ye.getUint64=ed;ye.UINT32_MAX=4294967295;function Xl(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zl(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Ql(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function ed(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var sr=b(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.timestampExtension=G.EXT_TIMESTAMP=void 0;G.encodeTimeSpecToTimestamp=Wi;G.encodeDateToTimeSpec=Ki;G.encodeTimestampExtension=Hi;G.decodeTimestampToTimeSpec=Gi;G.decodeTimestampExtension=Yi;var td=Zt(),Vi=Qt();G.EXT_TIMESTAMP=-1;var nd=4294967296-1,rd=17179869184-1;function Wi({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=rd)if(e===0&&t<=nd){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,Vi.setInt64)(r,4,t),n}}function Ki(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Hi(t){if(t instanceof Date){let e=Ki(t);return Wi(e)}else return null}function Gi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,Vi.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new td.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Yi(t){let e=Gi(t);return new Date(e.sec*1e3+e.nsec/1e6)}G.timestampExtension={type:G.EXT_TIMESTAMP,encode:Hi,decode:Yi}});var nn=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ExtensionCodec=void 0;var en=nr(),sd=sr(),ir=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(sd.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.ensureUint8Array=od;function id(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function od(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):id(t)?new Uint8Array(t):Uint8Array.from(t)}});var ar=b(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.Encoder=Z.DEFAULT_INITIAL_BUFFER_SIZE=Z.DEFAULT_MAX_DEPTH=void 0;var Ji=Yt(),cd=nn(),Xi=Qt(),ud=cr();Z.DEFAULT_MAX_DEPTH=100;Z.DEFAULT_INITIAL_BUFFER_SIZE=2048;var ur=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??cd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Z.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??Z.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Ji.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Ji.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,ud.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Xi.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Xi.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};Z.Encoder=ur});var Zi=b(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.encode=ld;var ad=ar();function ld(t,e){return new ad.Encoder(e).encodeSharedRef(t)}});var Qi=b(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.prettyByte=dd;function dd(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var eo=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CachedKeyDecoder=void 0;var fd=Yt(),hd=16,pd=16,fr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=hd,n=pd){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,fd.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};rn.CachedKeyDecoder=fr});var on=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.Decoder=void 0;var hr=Qi(),gd=nn(),Ae=Qt(),yd=Yt(),to=cr(),md=eo(),ie=Zt(),pr="array",tt="map_key",ro="map_value",wd=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ie.DecodeError("The type of key must be string or number but "+typeof t)},gr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=pr,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=tt,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===pr){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===tt||e.type===ro){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},et=-1,mr=new DataView(new ArrayBuffer(0)),_d=new Uint8Array(mr.buffer);try{mr.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var no=new RangeError("Insufficient data"),Sd=new md.CachedKeyDecoder,yr=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=mr;bytes=_d;headByte=et;stack=new gr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??gd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Ae.UINT32_MAX,this.maxBinLength=e?.maxBinLength??Ae.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??Ae.UINT32_MAX,this.maxMapLength=e?.maxMapLength??Ae.UINT32_MAX,this.maxExtLength=e?.maxExtLength??Ae.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Sd,this.mapKeyConverter=e?.mapKeyConverter??wd}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=et,this.stack.reset()}setBuffer(e){let n=(0,to.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===et&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,to.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,hr.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new ie.DecodeError(`Unrecognized type byte: ${(0,hr.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===pr)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===tt){if(n==="__proto__")throw new ie.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=ro;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=tt;continue e}}return n}}readHeadByte(){return this.headByte===et&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=et}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ie.DecodeError(`Unrecognized array type byte: ${(0,hr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ie.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ie.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new ie.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===tt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new ie.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw no;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new ie.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,Ae.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,Ae.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};sn.Decoder=yr});var io=b(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.decode=bd;cn.decodeMulti=Id;var so=on();function bd(t,e){return new so.Decoder(e).decode(t)}function Id(t,e){return new so.Decoder(e).decodeMulti(t)}});var uo=b(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.isAsyncIterable=oo;nt.asyncIterableFromStream=co;nt.ensureAsyncIterable=xd;function oo(t){return t[Symbol.asyncIterator]!=null}async function*co(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function xd(t){return oo(t)?t:co(t)}});var ao=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.decodeAsync=Ed;rt.decodeArrayStream=Ad;rt.decodeMultiStream=vd;var wr=on(),_r=uo();async function Ed(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeAsync(n)}function Ad(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeArrayStream(n)}function vd(t,e){let n=(0,_r.ensureAsyncIterable)(t);return new wr.Decoder(e).decodeStream(n)}});var fo=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var Td=Zi();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return Td.encode}});var lo=io();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return lo.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return lo.decodeMulti}});var Sr=ao();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return Sr.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return Sr.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return Sr.decodeMultiStream}});var Dd=on();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return Dd.Decoder}});var Md=Zt();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return Md.DecodeError}});var Od=ar();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return Od.Encoder}});var Pd=nn();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return Pd.ExtensionCodec}});var kd=nr();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return kd.ExtData}});var Re=sr();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return Re.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return Re.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return Re.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return Re.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return Re.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return Re.decodeTimestampExtension}})});var xr=b((zh,mo)=>{"use strict";var q=require("fs"),Q=Ci(),{encode:Nd,decode:Ud}=fo(),br=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function ho(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function Ld(t){let e=ho(t);return Q.create({schema:e})}function Rd(t){for(let e of br)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function jd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");Rd(e);let n={};for(let r of br)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return Q.insert(t,n)}async function Fd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return po(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function po(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await Q.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await Q.removeMultiple(t,r)}function Ir(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function Cd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await Q.search(t,s)).hits.map(Ir)}async function Bd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await Q.search(t,i)).hits.map(Ir)}async function qd(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await Q.search(t,u)).hits.map(Ir)}async function $d(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=Q.save(t),r={v:1,schema:t.schema,raw:n},s=Nd(r),i=e+".tmp";q.writeFileSync(i,s),q.renameSync(i,e)}async function zd(t){if(!t)throw new Error("loadStore: storePath is required");if(!q.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=q.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=Ud(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await Q.create({schema:n.schema});return Q.load(r,n.raw),r}var Vd=3e4,Wd=50,Kd=1e4;function Hd(t){try{let e=q.openSync(t,"wx");return q.writeSync(e,String(process.pid)),q.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function Gd(t){return new Promise(e=>setTimeout(e,t))}async function go(t){let e=Date.now()+Kd;for(;;){if(Hd(t))return;try{let n=q.statSync(t);if(Date.now()-n.mtimeMs>Vd){try{q.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await Gd(Wd)}}function yo(t){try{q.unlinkSync(t)}catch{}}async function Yd(t,e){await go(t);try{return await e()}finally{yo(t)}}var Jd=["provider","model","dimensions","last_indexed","pending"];function Xd(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";q.writeFileSync(r,JSON.stringify(n,null,2)+` -`,"utf8"),q.renameSync(r,t)}function Zd(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!q.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=q.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}mo.exports={SCHEMA_FIELDS:br,METADATA_FIELDS:Jd,buildSchema:ho,createStore:Ld,insertDocument:jd,removeByIdentity:Fd,removeByFilter:po,searchFulltext:Cd,searchVector:Bd,searchHybrid:qd,saveStore:$d,loadStore:zd,acquireLock:go,releaseLock:yo,withLock:Yd,writeMetadata:Xd,readMetadata:Zd}});var Io=b((Vh,bo)=>{"use strict";var Qd=/^\s*(```+|~~~+)/,wo=/^---\s*$/;function ef(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` +`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function $c(t,...e){let n=new Error((0,Cc.sprintf)(Bc[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}});var $e=b(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.getDocumentProperties=void 0;H.formatElapsedTime=zc;H.getDocumentIndexId=Vc;H.validateSchema=Qr;H.isGeoPointType=Hc;H.isVectorType=es;H.isArrayType=ts;H.getInnerType=ns;H.getVectorSize=rs;var dt=j(),Zr=R(),qc=R();Object.defineProperty(H,"getDocumentProperties",{enumerable:!0,get:function(){return qc.getDocumentProperties}});function zc(t){return{raw:Number(t),formatted:(0,Zr.formatNanoseconds)(t)}}function Vc(t){if(t.id){if(typeof t.id!="string")throw(0,dt.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return(0,Zr.uniqueId)()}function Qr(t,e){for(let[n,r]of Object.entries(e)){let s=t[n];if(!(typeof s>"u")&&!(r==="geopoint"&&typeof s=="object"&&typeof s.lon=="number"&&typeof s.lat=="number")&&!(r==="enum"&&(typeof s=="string"||typeof s=="number"))){if(r==="enum[]"&&Array.isArray(s)){let i=s.length;for(let o=0;o{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.createInternalDocumentIDStore=Gc;Ie.save=ss;Ie.load=is;Ie.getInternalDocumentId=os;Ie.getDocumentIdFromInternalId=Yc;function Gc(){return{idToInternalId:new Map,internalIdToId:[],save:ss,load:is}}function ss(t){return{internalIdToId:t.internalIdToId}}function is(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let s=0;st.internalIdToId.length?os(t,e.toString()):e}function Yc(t,e){if(t.internalIdToId.length{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.create=cs;G.get=us;G.getMultiple=as;G.getAll=ls;G.store=ds;G.remove=fs;G.count=hs;G.load=ps;G.save=gs;G.createDocumentsStore=Jc;var mn=V();function cs(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function us(t,e){let n=(0,mn.getInternalDocumentId)(t.sharedInternalDocumentStore,e);return t.docs[n]}function as(t,e){let n=e.length,r=Array.from({length:n});for(let s=0;s"u"?!1:(delete t.docs[n],t.count--,!0)}function hs(t){return t.count}function ps(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function gs(t){return{docs:t.docs,count:t.count}}function Jc(){return{create:cs,get:us,getMultiple:as,getAll:ls,store:ds,remove:fs,count:hs,load:ps,save:gs}}});var ys=b(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.AVAILABLE_PLUGIN_HOOKS=void 0;qe.getAllPluginsByHook=Zc;var Xc=j();qe.AVAILABLE_PLUGIN_HOOKS=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeUpsert","afterUpsert","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeUpsertMultiple","afterUpsertMultiple","beforeLoad","afterLoad","afterCreate"];function Zc(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let s=0;s{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.SINGLE_OR_ARRAY_COMPONENTS=W.FUNCTION_COMPONENTS=W.OBJECT_COMPONENTS=void 0;W.runSingleHook=Qc;W.runMultipleHook=eu;W.runAfterSearch=tu;W.runBeforeSearch=nu;W.runAfterCreate=ru;var ze=R();W.OBJECT_COMPONENTS=["tokenizer","index","documentsStore","sorter","pinning"];W.FUNCTION_COMPONENTS=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"];W.SINGLE_OR_ARRAY_COMPONENTS=[];function Qc(t,e,n,r){if(t.some(ze.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function eu(t,e,n){if(t.some(ze.isAsyncFunction))return(async()=>{for(let s of t)await s(e,n)})();for(let s of t)s(e,n)}function tu(t,e,n,r,s){if(t.some(ze.isAsyncFunction))return(async()=>{for(let o of t)await o(e,n,r,s)})();for(let o of t)o(e,n,r,s)}function nu(t,e,n,r){if(t.some(ze.isAsyncFunction))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function ru(t,e){if(t.some(ze.isAsyncFunction))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}});var ms=b(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.AVLTree=Oe.AVLNode=void 0;var ae=class t{k;v;l=null;r=null;h=1;constructor(e,n){this.k=e,this.v=new Set(n)}updateHeight(){this.h=Math.max(t.getHeight(this.l),t.getHeight(this.r))+1}static getHeight(e){return e?e.h:0}getBalanceFactor(){return t.getHeight(this.l)-t.getHeight(this.r)}rotateLeft(){let e=this.r;return this.r=e.l,e.l=this,this.updateHeight(),e.updateHeight(),e}rotateRight(){let e=this.l;return this.l=e.r,e.r=this,this.updateHeight(),e.updateHeight(),e}toJSON(){return{k:this.k,v:Array.from(this.v),l:this.l?this.l.toJSON():null,r:this.r?this.r.toJSON():null,h:this.h}}static fromJSON(e){let n=new t(e.k,e.v);return n.l=e.l?t.fromJSON(e.l):null,n.r=e.r?t.fromJSON(e.r):null,n.h=e.h,n}};Oe.AVLNode=ae;var _n=class t{root=null;insertCount=0;constructor(e,n){e!==void 0&&n!==void 0&&(this.root=new ae(e,n))}insert(e,n,r=1e3){this.root=this.insertNode(this.root,e,n,r)}insertMultiple(e,n,r=1e3){for(let s of n)this.insert(e,s,r)}rebalance(){this.root&&(this.root=this.rebalanceNode(this.root))}toJSON(){return{root:this.root?this.root.toJSON():null,insertCount:this.insertCount}}static fromJSON(e){let n=new t;return n.root=e.root?ae.fromJSON(e.root):null,n.insertCount=e.insertCount||0,n}insertNode(e,n,r,s){if(e===null)return new ae(n,[r]);let i=[],o=e,c=null;for(;o!==null;)if(i.push({parent:c,node:o}),no.k)if(o.r===null){o.r=new ae(n,[r]),i.push({parent:o,node:o.r});break}else c=o,o=o.r;else return o.v.add(r),e;let u=!1;this.insertCount++%s===0&&(u=!0);for(let a=i.length-1;a>=0;a--){let{parent:l,node:d}=i[a];if(d.updateHeight(),u){let f=this.rebalanceNode(d);l?l.l===d?l.l=f:l.r===d&&(l.r=f):e=f}}return e}rebalanceNode(e){let n=e.getBalanceFactor();if(n>1){if(e.l&&e.l.getBalanceFactor()>=0)return e.rotateRight();if(e.l)return e.l=e.l.rotateLeft(),e.rotateRight()}if(n<-1){if(e.r&&e.r.getBalanceFactor()<=0)return e.rotateLeft();if(e.r)return e.r=e.r.rotateRight(),e.rotateLeft()}return e}find(e){let n=this.findNodeByKey(e);return n?n.v:null}contains(e){return this.find(e)!==null}getSize(){let e=0,n=[],r=this.root;for(;r||n.length>0;){for(;r;)n.push(r),r=r.l;r=n.pop(),e++,r=r.r}return e}isBalanced(){if(!this.root)return!0;let e=[this.root];for(;e.length>0;){let n=e.pop(),r=n.getBalanceFactor();if(Math.abs(r)>1)return!1;n.l&&e.push(n.l),n.r&&e.push(n.r)}return!0}remove(e){this.root=this.removeNode(this.root,e)}removeDocument(e,n){let r=this.findNodeByKey(e);r&&(r.v.size===1?this.root=this.removeNode(this.root,e):r.v=new Set([...r.v.values()].filter(s=>s!==n)))}findNodeByKey(e){let n=this.root;for(;n;)if(en.k)n=n.r;else return n;return null}removeNode(e,n){if(e===null)return null;let r=[],s=e;for(;s!==null&&s.k!==n;)r.push(s),n=0;i--){let o=r[i];o.updateHeight();let c=this.rebalanceNode(o);if(i>0){let u=r[i-1];u.l===o?u.l=c:u.r===o&&(u.r=c)}else e=c}return e}rangeSearch(e,n){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),i.k>=e&&i.k<=n)for(let o of i.v)r.add(o);if(i.k>n)break;i=i.r}return r}greaterThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.r;if(i=s.pop(),n&&i.k>=e||!n&&i.k>e)for(let o of i.v)r.add(o);else if(i.k<=e)break;i=i.l}return r}lessThan(e,n=!1){let r=new Set,s=[],i=this.root;for(;i||s.length>0;){for(;i;)s.push(i),i=i.l;if(i=s.pop(),n&&i.k<=e||!n&&i.ke)break;i=i.r}return r}};Oe.AVLTree=_n});var ws=b(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.FlatTree=void 0;var Sn=class t{numberToDocumentId;constructor(){this.numberToDocumentId=new Map}insert(e,n){this.numberToDocumentId.has(e)?this.numberToDocumentId.get(e).add(n):this.numberToDocumentId.set(e,new Set([n]))}find(e){let n=this.numberToDocumentId.get(e);return n?Array.from(n):null}remove(e){this.numberToDocumentId.delete(e)}removeDocument(e,n){let r=this.numberToDocumentId.get(n);r&&(r.delete(e),r.size===0&&this.numberToDocumentId.delete(n))}contains(e){return this.numberToDocumentId.has(e)}getSize(){let e=0;for(let n of this.numberToDocumentId.values())e+=n.size;return e}filter(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let s=e[r],i=this.numberToDocumentId.get(s);return i?Array.from(i):[]}case"in":{let s=e[r],i=new Set;for(let o of s){let c=this.numberToDocumentId.get(o);if(c)for(let u of c)i.add(u)}return Array.from(i)}case"nin":{let s=new Set(e[r]),i=new Set;for(let[o,c]of this.numberToDocumentId.entries())if(!s.has(o))for(let u of c)i.add(u);return Array.from(i)}default:throw new Error("Invalid operation")}}filterArr(e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c].filter(a=>u.has(a))));return Array.from(o)}case"containsAny":{let i=e[r].map(c=>this.numberToDocumentId.get(c)??new Set);if(i.length===0)return[];let o=i.reduce((c,u)=>new Set([...c,...u]));return Array.from(o)}default:throw new Error("Invalid operation")}}static fromJSON(e){if(!e.numberToDocumentId)throw new Error("Invalid Flat Tree JSON");let n=new t;for(let[r,s]of e.numberToDocumentId)n.numberToDocumentId.set(r,new Set(s));return n}toJSON(){return{numberToDocumentId:Array.from(this.numberToDocumentId.entries()).map(([e,n])=>[e,Array.from(n)])}}};ft.FlatTree=Sn});var bn=b(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.boundedLevenshtein=su;Ve.syncBoundedLevenshtein=iu;Ve.levenshtein=ou;function _s(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,s=e.length;if(r===0)return s<=n?s:-1;if(s===0)return r<=n?r:-1;let i=Math.abs(r-s);if(t.startsWith(e))return i<=n?i:-1;if(e.startsWith(t))return 0;if(i>n)return-1;let o=[];for(let c=0;c<=r;c++){o[c]=[c];for(let u=1;u<=s;u++)o[c][u]=c===0?u:0}for(let c=1;c<=r;c++){let u=1/0;for(let a=1;a<=s;a++)t[c-1]===e[a-1]?o[c][a]=o[c-1][a-1]:o[c][a]=Math.min(o[c-1][a]+1,o[c][a-1]+1,o[c-1][a-1]+1),u=Math.min(u,o[c][a]);if(u>n)return-1}return o[r][s]<=n?o[r][s]:-1}function su(t,e,n){let r=_s(t,e,n);return{distance:r,isBounded:r>=0}}function iu(t,e,n){let r=_s(t,e,n);return{distance:r,isBounded:r>=0}}function ou(t,e){if(!t.length)return e.length;if(!e.length)return t.length;let n=t;t.length>e.length&&(t=e,e=n);let r=Array.from({length:t.length+1},(i,o)=>o),s=0;for(let i=1;i<=e.length;i++){let o=i;for(let c=1;c<=t.length;c++)e[i-1]===t[c-1]?s=r[c-1]:s=Math.min(r[c-1]+1,Math.min(o+1,r[c]+1)),r[c-1]=o,o=s;r[t.length]=o}return r[t.length]}});var bs=b(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.RadixTree=Pe.RadixNode=void 0;var Ss=bn(),In=R(),We=class t{k;s;c=new Map;d=new Set;e;w="";constructor(e,n,r){this.k=e,this.s=n,this.e=r}updateParent(e){this.w=e.w+this.s}addDocument(e){this.d.add(e)}removeDocument(e){return this.d.delete(e)}findAllWords(e,n,r,s){let i=[this];for(;i.length>0;){let o=i.pop();if(o.e){let{w:c,d:u}=o;if(r&&c!==n)continue;if((0,In.getOwnProperty)(e,c)!==null)if(s)if(Math.abs(n.length-c.length)<=s&&(0,Ss.syncBoundedLevenshtein)(n,c,s).isBounded)e[c]=[];else continue;else e[c]=[];if((0,In.getOwnProperty)(e,c)!=null&&u.size>0){let a=e[c];for(let l of u)a.includes(l)||a.push(l)}}o.c.size>0&&i.push(...o.c.values())}return e}insert(e,n){let r=this,s=0,i=e.length;for(;s0;){let{node:c,index:u,tolerance:a}=o.pop();if(c.w.startsWith(e)){c.findAllWords(i,e,!1,0);continue}if(a<0)continue;if(c.e){let{w:d,d:f}=c;if(d&&((0,Ss.syncBoundedLevenshtein)(e,d,s).isBounded&&(i[d]=[]),(0,In.getOwnProperty)(i,d)!==void 0&&f.size>0)){let p=new Set(i[d]);for(let g of f)p.add(g);i[d]=Array.from(p)}}if(u>=e.length)continue;let l=e[u];if(c.c.has(l)){let d=c.c.get(l);o.push({node:d,index:u+1,tolerance:a})}o.push({node:c,index:u+1,tolerance:a-1});for(let[d,f]of c.c)o.push({node:f,index:u,tolerance:a-1}),d!==l&&o.push({node:f,index:u+1,tolerance:a-1})}}find(e){let{term:n,exact:r,tolerance:s}=e;if(s&&!r){let i={};return this._findLevenshtein(n,0,s,s,i),i}else{let i=this,o=0,c=n.length;for(;o0&&n.c.size===0&&!n.e&&n.d.size===0;){let{parent:i,character:o}=s.pop();i.c.delete(o),n=i}return!0}removeDocumentByWord(e,n,r=!0){if(!e)return!0;let s=this,i=e.length;for(let o=0;o[e,n.toJSON()])}}static fromJSON(e){let n=new t(e.k,e.s,e.e);return n.w=e.w,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,t.fromJSON(s)])||[]),n}};Pe.RadixNode=We;var xn=class t extends We{constructor(){super("","",!1)}static fromJSON(e){let n=new t;return n.w=e.w,n.s=e.s,n.e=e.e,n.k=e.k,n.d=new Set(e.d),n.c=new Map(e?.c?.map(([r,s])=>[r,We.fromJSON(s)])||[]),n}toJSON(){return super.toJSON()}};Pe.RadixTree=xn});var Is=b(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.BKDTree=void 0;var cu=2,uu=6371e3,ht=class t{point;docIDs;left;right;parent;constructor(e,n){this.point=e,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(e,n=null){let r=new t(e.point,e.docIDs);return r.parent=n,e.left&&(r.left=t.fromJSON(e.left,r)),e.right&&(r.right=t.fromJSON(e.right,r)),r}},En=class t{root;nodeMap;constructor(){this.root=null,this.nodeMap=new Map}getPointKey(e){return`${e.lon},${e.lat}`}insert(e,n){let r=this.getPointKey(e),s=this.nodeMap.get(r);if(s){n.forEach(u=>s.docIDs.add(u));return}let i=new ht(e,n);if(this.nodeMap.set(r,i),this.root==null){this.root=i;return}let o=this.root,c=0;for(;;){if(c%cu===0)if(e.lon0;){let{node:a,depth:l}=c.pop();if(a==null)continue;let d=o(e,a.point);(r?d<=n:d>n)&&u.push({point:a.point,docIDs:Array.from(a.docIDs)}),a.left!=null&&c.push({node:a.left,depth:l+1}),a.right!=null&&c.push({node:a.right,depth:l+1})}return s&&u.sort((a,l)=>{let d=o(e,a.point),f=o(e,l.point);return s.toLowerCase()==="asc"?d-f:f-d}),u}searchByPolygon(e,n=!0,r=null,s=!1){let i=[{node:this.root,depth:0}],o=[];for(;i.length>0;){let{node:u,depth:a}=i.pop();if(u==null)continue;u.left!=null&&i.push({node:u.left,depth:a+1}),u.right!=null&&i.push({node:u.right,depth:a+1});let l=t.isPointInPolygon(e,u.point);(l&&n||!l&&!n)&&o.push({point:u.point,docIDs:Array.from(u.docIDs)})}let c=t.calculatePolygonCentroid(e);if(r){let u=s?t.vincentyDistance:t.haversineDistance;o.sort((a,l)=>{let d=u(c,a.point),f=u(c,l.point);return r.toLowerCase()==="asc"?d-f:f-d})}return o}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(e){let n=new t;return e.root&&(n.root=ht.fromJSON(e.root),n.buildNodeMap(n.root)),n}buildNodeMap(e){if(e==null)return;let n=this.getPointKey(e.point);this.nodeMap.set(n,e),e.left&&this.buildNodeMap(e.left),e.right&&this.buildNodeMap(e.right)}static calculatePolygonCentroid(e){let n=0,r=0,s=0,i=e.length;for(let c=0,u=i-1;ci!=f>i&&s<(d-a)*(i-l)/(f-l)+a&&(r=!r)}return r}static haversineDistance(e,n){let r=Math.PI/180,s=e.lat*r,i=n.lat*r,o=(n.lat-e.lat)*r,c=(n.lon-e.lon)*r,u=Math.sin(o/2)*Math.sin(o/2)+Math.cos(s)*Math.cos(i)*Math.sin(c/2)*Math.sin(c/2),a=2*Math.atan2(Math.sqrt(u),Math.sqrt(1-u));return uu*a}static vincentyDistance(e,n){let s=.0033528106647474805,i=(1-s)*6378137,o=Math.PI/180,c=e.lat*o,u=n.lat*o,a=(n.lon-e.lon)*o,l=Math.atan((1-s)*Math.tan(c)),d=Math.atan((1-s)*Math.tan(u)),f=Math.sin(l),p=Math.cos(l),g=Math.sin(d),y=Math.cos(d),h=a,m,w=1e3,S,_,I,v,D,A;do{let Me=Math.sin(h),Be=Math.cos(h);if(S=Math.sqrt(y*Me*(y*Me)+(p*g-f*y*Be)*(p*g-f*y*Be)),S===0)return 0;_=f*g+p*y*Be,I=Math.atan2(S,_),v=p*y*Me/S,D=1-v*v,A=_-2*f*g/D,isNaN(A)&&(A=0);let pn=s/16*D*(4+s*(4-3*D));m=h,h=a+(1-pn)*s*v*(I+pn*S*(A+pn*_*(-1+2*A*A)))}while(Math.abs(h-m)>1e-12&&--w>0);if(w===0)return NaN;let k=D*(6378137*6378137-i*i)/(i*i),De=1+k/16384*(4096+k*(-768+k*(320-175*k))),X=k/1024*(256+k*(-128+k*(74-47*k))),hn=X*S*(A+X/4*(_*(-1+2*A*A)-X/6*A*(-3+4*S*S)*(-3+4*A*A)));return i*De*(I-hn)}};pt.BKDTree=En});var xs=b(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.BoolNode=void 0;var An=class t{true;false;constructor(){this.true=new Set,this.false=new Set}insert(e,n){n?this.true.add(e):this.false.add(e)}delete(e,n){n?this.true.delete(e):this.false.delete(e)}getSize(){return this.true.size+this.false.size}toJSON(){return{true:Array.from(this.true),false:Array.from(this.false)}}static fromJSON(e){let n=new t;return n.true=new Set(e.true),n.false=new Set(e.false),n}};gt.BoolNode=An});var Es=b(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.prioritizeTokenScores=lu;yt.BM25=du;var au=j();function lu(t,e,n=0,r){if(e===0)throw(0,au.createError)("INVALID_BOOST_VALUE");let s=new Map,i=t.length;for(let y=0;yh[1]-y[1]);if(n===1||n===0&&r===1)return c;let u=c.length,a=[];for(let y of s.entries())a.push([y[0],y[1][0],y[1][1]]);let l=a.sort((y,h)=>y[2]>h[2]?-1:y[2]h[1]?-1:y[1]"u"){if(n===0)return[];d=0}let f=l.length,p=new Array(f);for(let y=0;y{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.VectorIndex=le.DEFAULT_SIMILARITY=void 0;le.getMagnitude=Tn;le.findSimilarVectors=As;le.DEFAULT_SIMILARITY=.8;var vn=class t{size;vectors=new Map;constructor(e){this.size=e}add(e,n){n instanceof Float32Array||(n=new Float32Array(n));let r=Tn(n,this.size);this.vectors.set(e,[r,n])}remove(e){this.vectors.delete(e)}find(e,n,r){return e instanceof Float32Array||(e=new Float32Array(e)),As(e,r,this.vectors,this.size,n)}toJSON(){let e=[];for(let[n,[r,s]]of this.vectors)e.push([n,[r,Array.from(s)]]);return{size:this.size,vectors:e}}static fromJSON(e){let n=e,r=new t(n.size);for(let[s,[i,o]]of n.vectors)r.vectors.set(s,[i,new Float32Array(o)]);return r}};le.VectorIndex=vn;function Tn(t,e){let n=0;for(let r=0;r=s&&o.push([u,p])}return o}});var mt=b(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.insertDocumentScoreParameters=Us;L.insertTokenScoreParameters=Rs;L.removeDocumentScoreParameters=Ls;L.removeTokenScoreParameters=js;L.create=On;L.insert=Cs;L.insertVector=Fs;L.remove=Bs;L.calculateResultScores=Pn;L.search=$s;L.searchByWhereClause=Ke;L.getSearchableProperties=qs;L.getSearchablePropertiesWithTypes=zs;L.load=Vs;L.save=Ws;L.createIndex=pu;L.searchByGeoWhereClause=yu;var ke=j(),Ms=ms(),Os=ws(),Ps=bs(),He=Is(),ks=xs(),ne=R(),fu=Es(),xe=$e(),Mn=V(),Ns=Dn();function Us(t,e,n,r,s){let i=(0,Mn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(s-1)+r.length)/s,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function Rs(t,e,n,r,s){let i=0;for(let u of r)u===s&&i++;let o=(0,Mn.getInternalDocumentId)(t.sharedInternalDocumentStore,n),c=i/r.length;t.frequencies[e][o][s]=c,s in t.tokenOccurrences[e]||(t.tokenOccurrences[e][s]=0),t.tokenOccurrences[e][s]=(t.tokenOccurrences[e][s]??0)+1}function Ls(t,e,n,r){let s=(0,Mn.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][s])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][s]=void 0,t.frequencies[e][s]=void 0}function js(t,e,n){t.tokenOccurrences[e][n]--}function On(t,e,n,r,s=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,o]of Object.entries(n)){let c=`${s}${s?".":""}${i}`;if(typeof o=="object"&&!Array.isArray(o)){On(t,e,o,r,c);continue}if((0,xe.isVectorType)(o))r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o,r.vectorIndexes[c]={type:"Vector",node:new Ns.VectorIndex((0,xe.getVectorSize)(o)),isArray:!1};else{let u=/\[/.test(o);switch(o){case"boolean":case"boolean[]":r.indexes[c]={type:"Bool",node:new ks.BoolNode,isArray:u};break;case"number":case"number[]":r.indexes[c]={type:"AVL",node:new Ms.AVLTree(0,[]),isArray:u};break;case"string":case"string[]":r.indexes[c]={type:"Radix",node:new Ps.RadixTree,isArray:u},r.avgFieldLength[c]=0,r.frequencies[c]={},r.tokenOccurrences[c]={},r.fieldLengths[c]={};break;case"enum":case"enum[]":r.indexes[c]={type:"Flat",node:new Os.FlatTree,isArray:u};break;case"geopoint":r.indexes[c]={type:"BKD",node:new He.BKDTree,isArray:u};break;default:throw(0,ke.createError)("INVALID_SCHEMA_TYPE",Array.isArray(o)?"array":o,c)}r.searchableProperties.push(c),r.searchablePropertiesWithTypes[c]=o}}return r}function hu(t,e,n,r,s,i,o,c){return u=>{let{type:a,node:l}=e.indexes[n];switch(a){case"Bool":{l[u?"true":"false"].add(r);break}case"AVL":{let d=c?.avlRebalanceThreshold??1;l.insert(u,r,d);break}case"Radix":{let d=i.tokenize(u,s,n,!1);t.insertDocumentScoreParameters(e,n,r,d,o);for(let f of d)t.insertTokenScoreParameters(e,n,r,d,f),l.insert(f,r);break}case"Flat":{l.insert(u,r);break}case"BKD":{l.insert(u,[r]);break}}}}function Cs(t,e,n,r,s,i,o,c,u,a,l){if((0,xe.isVectorType)(o))return Fs(e,n,i,r,s);let d=hu(t,e,n,s,c,u,a,l);if(!(0,xe.isArrayType)(o))return d(i);let f=i,p=f.length;for(let g=0;g0&&y.set(k,!0);let hn=X.length;for(let at=0;at[S,_]).sort((S,_)=>_[1]-S[1]);if(m.length===0)return[];if(d===1)return m;if(d===0){if(p===1)return m;for(let _ of f)if(!y.get(_))return[];return m.filter(([_])=>{let I=g.get(_);return I?Array.from(I.values()).some(v=>v===p):!1})}let w=m.filter(([S])=>{let _=g.get(S);return _?Array.from(_.values()).some(I=>I===p):!1});if(w.length>0){let S=m.filter(([I])=>!w.some(([v])=>v===I)),_=Math.ceil(S.length*d);return[...w,...S.slice(0,_)]}return m}function Ke(t,e,n,r){if("and"in n&&n.and&&Array.isArray(n.and)){let o=n.and;if(o.length===0)return new Set;let c=o.map(u=>Ke(t,e,u,r));return(0,ne.setIntersection)(...c)}if("or"in n&&n.or&&Array.isArray(n.or)){let o=n.or;return o.length===0?new Set:o.map(u=>Ke(t,e,u,r)).reduce((u,a)=>(0,ne.setUnion)(u,a),new Set)}if("not"in n&&n.not){let o=n.not,c=new Set,u=t.sharedInternalDocumentStore;for(let l=1;l<=u.internalIdToId.length;l++)c.add(l);let a=Ke(t,e,o,r);return(0,ne.setDifference)(c,a)}let s=Object.keys(n),i=s.reduce((o,c)=>({[c]:new Set,...o}),{});for(let o of s){let c=n[o];if(typeof t.indexes[o]>"u")throw(0,ke.createError)("UNKNOWN_FILTER_PROPERTY",o);let{node:u,type:a,isArray:l}=t.indexes[o];if(a==="Bool"){let f=u,p=c?f.true:f.false;i[o]=(0,ne.setUnion)(i[o],p);continue}if(a==="BKD"){let f;if("radius"in c)f="radius";else if("polygon"in c)f="polygon";else throw new Error(`Invalid operation ${c}`);if(f==="radius"){let{value:p,coordinates:g,unit:y="m",inside:h=!0,highPrecision:m=!1}=c[f],w=(0,ne.convertDistanceToMeters)(p,y),S=u.searchByRadius(g,w,h,void 0,m);i[o]=Ts(i[o],S)}else{let{coordinates:p,inside:g=!0,highPrecision:y=!1}=c[f],h=u.searchByPolygon(p,g,void 0,y);i[o]=Ts(i[o],h)}continue}if(a==="Radix"&&(typeof c=="string"||Array.isArray(c))){for(let f of[c].flat()){let p=e.tokenize(f,r,o);for(let g of p){let y=u.find({term:g,exact:!0});i[o]=mu(i[o],y)}}continue}let d=Object.keys(c);if(d.length>1)throw(0,ke.createError)("INVALID_FILTER_OPERATION",d.length);if(a==="Flat"){let f=new Set(l?u.filterArr(c):u.filter(c));i[o]=(0,ne.setUnion)(i[o],f);continue}if(a==="AVL"){let f=d[0],p=c[f],g;switch(f){case"gt":{g=u.greaterThan(p,!1);break}case"gte":{g=u.greaterThan(p,!0);break}case"lt":{g=u.lessThan(p,!1);break}case"lte":{g=u.lessThan(p,!0);break}case"eq":{g=u.find(p)??new Set;break}case"between":{let[y,h]=p;g=u.rangeSearch(y,h);break}default:throw(0,ke.createError)("INVALID_FILTER_OPERATION",f)}i[o]=(0,ne.setUnion)(i[o],g)}}return(0,ne.setIntersection)(...Object.values(i))}function qs(t){return t.searchableProperties}function zs(t){return t.searchablePropertiesWithTypes}function Vs(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}=e,l={},d={};for(let f of Object.keys(n)){let{node:p,type:g,isArray:y}=n[f];switch(g){case"Radix":l[f]={type:"Radix",node:Ps.RadixTree.fromJSON(p),isArray:y};break;case"Flat":l[f]={type:"Flat",node:Os.FlatTree.fromJSON(p),isArray:y};break;case"AVL":l[f]={type:"AVL",node:Ms.AVLTree.fromJSON(p),isArray:y};break;case"BKD":l[f]={type:"BKD",node:He.BKDTree.fromJSON(p),isArray:y};break;case"Bool":l[f]={type:"Bool",node:ks.BoolNode.fromJSON(p),isArray:y};break;default:l[f]=n[f]}}for(let f of Object.keys(r))d[f]={type:"Vector",isArray:!1,node:Ns.VectorIndex.fromJSON(r[f])};return{sharedInternalDocumentStore:t,indexes:l,vectorIndexes:d,searchableProperties:s,searchablePropertiesWithTypes:i,frequencies:o,tokenOccurrences:c,avgFieldLength:u,fieldLengths:a}}function Ws(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}=t,a={};for(let d of Object.keys(n))a[d]=n[d].node.toJSON();let l={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:g}=e[d];f==="Flat"||f==="Radix"||f==="AVL"||f==="BKD"||f==="Bool"?l[d]={type:f,node:p.toJSON(),isArray:g}:(l[d]=e[d],l[d].node=l[d].node.toJSON())}return{indexes:l,vectorIndexes:a,searchableProperties:r,searchablePropertiesWithTypes:s,frequencies:i,tokenOccurrences:o,avgFieldLength:c,fieldLengths:u}}function pu(){return{create:On,insert:Cs,remove:Bs,insertDocumentScoreParameters:Us,insertTokenScoreParameters:Rs,removeDocumentScoreParameters:Ls,removeTokenScoreParameters:js,calculateResultScores:Pn,search:$s,searchByWhereClause:Ke,getSearchableProperties:qs,getSearchablePropertiesWithTypes:zs,load:Vs,save:Ws}}function Ts(t,e){t||(t=new Set);let n=e.length;for(let r=0;ra[1]-u[1]),s}function gu(t,e){let n=Object.keys(t);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],s=t[r];if(typeof e.indexes[r]>"u")return{isGeoOnly:!1};let{type:i}=e.indexes[r];return i==="BKD"&&s&&("radius"in s||"polygon"in s)?{isGeoOnly:!0,geoProperty:r,geoOperation:s}:{isGeoOnly:!1}}function yu(t,e){let n=t,r=gu(e,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:s}=n.indexes[r.geoProperty],i=r.geoOperation,o=s,c;if("radius"in i){let{value:u,coordinates:a,unit:l="m",inside:d=!0,highPrecision:f=!1}=i.radius,p=a,g=(0,ne.convertDistanceToMeters)(u,l);return c=o.searchByRadius(p,g,d,"asc",f),Ds(c,p,f)}else if("polygon"in i){let{coordinates:u,inside:a=!0,highPrecision:l=!1}=i.polygon;c=o.searchByPolygon(u,a,"asc",l);let d=He.BKDTree.calculatePolygonCentroid(u);return Ds(c,d,l)}return null}function mu(t,e){t||(t=new Set);let n=Object.keys(e),r=n.length;for(let s=0;s{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.load=Gs;Ge.save=Ys;Ge.createSorter=ku;var kn=j(),wu=$e(),wt=V(),_u=R(),Su=lt();function Ks(t,e,n,r,s){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[o,c]of Object.entries(n)){let u=`${s}${s?".":""}${o}`;if(!r.includes(u)){if(typeof c=="object"&&!Array.isArray(c)){let a=Ks(t,e,c,r,u);(0,_u.safeArrayPush)(i.sortableProperties,a.sortableProperties),i.sorts={...i.sorts,...a.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...a.sortablePropertiesWithTypes};continue}if(!(0,wu.isVectorType)(c))switch(c){case"boolean":case"number":case"string":i.sortableProperties.push(u),i.sortablePropertiesWithTypes[u]=c,i.sorts[u]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:c};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw(0,kn.createError)("INVALID_SORT_SCHEMA_TYPE",Array.isArray(c)?"array":c,u)}}}return i}function bu(t,e,n,r){return r?.enabled!==!1?Ks(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function Iu(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(s)&&Nn(t,e),i.docs.set(s,i.orderedDocs.length),i.orderedDocs.push([s,r])}function Hs(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)vu(t,n);t.isSorted=!0}function xu(t,e,n){return e[1].localeCompare(n[1],(0,Su.getLocale)(t))}function Eu(t,e){return t[1]-e[1]}function Au(t,e){return e[1]?-1:1}function vu(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=xu.bind(null,t.language);break;case"number":r=Eu.bind(null);break;case"boolean":r=Au.bind(null);break}n.orderedDocs.sort(r);let s=n.orderedDocs.length;for(let i=0;i!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function Du(t,e,n){if(!t.enabled)return;let r=t.sorts[e],s=(0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,n);r.docs.get(s)&&(r.docs.delete(s),r.orderedDocsToRemove.set(s,!0))}function Mu(t,e,n){if(!t.enabled)throw(0,kn.createError)("SORT_DISABLED");let r=n.property,s=n.order==="DESC",i=t.sorts[r];if(!i)throw(0,kn.createError)("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return Nn(t,r),Hs(t),e.sort((o,c)=>{let u=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,o[0])),a=i.docs.get((0,wt.getInternalDocumentId)(t.sharedInternalDocumentStore,c[0])),l=typeof u<"u",d=typeof a<"u";return!l&&!d?0:l?d?s?a-u:u-a:-1:1}),e}function Ou(t){return t.enabled?t.sortableProperties:[]}function Pu(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function Gs(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((s,i)=>{let{docs:o,orderedDocs:c,type:u}=n.sorts[i];return s[i]={docs:new Map(Object.entries(o).map(([a,l])=>[+a,l])),orderedDocsToRemove:new Map,orderedDocs:c,type:u},s},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function Ys(t){if(!t.enabled)return{enabled:!1};Tu(t),Hs(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:s,orderedDocs:i,type:o}=t.sorts[r];return n[r]={docs:Object.fromEntries(s.entries()),orderedDocs:i,type:o},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function ku(){return{create:bu,insert:Iu,remove:Du,save:Ys,load:Gs,sortBy:Mu,getSortableProperties:Ou,getSortablePropertiesWithTypes:Pu}}});var Xs=b(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.replaceDiacritics=Lu;var Js=192,Nu=383,Uu=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115];function Ru(t){return tNu?t:Uu[t-Js]||t}function Lu(t){let e=[];for(let n=0;n{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.stemmer=$u;var ju={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},Cu={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Fu="[^aeiou]",St="[aeiouy]",Z=Fu+"[^aeiouy]*",Ye=St+"[aeiou]*",Ln="^("+Z+")?"+Ye+Z,Bu="^("+Z+")?"+Ye+Z+"("+Ye+")?$",_t="^("+Z+")?"+Ye+Z+Ye+Z,Zs="^("+Z+")?"+St;function $u(t){let e,n,r,s,i,o;if(t.length<3)return t;let c=t.substring(0,1);if(c=="y"&&(t=c.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,s=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):s.test(t)&&(t=t.replace(s,"$1$2")),r=/^(.+?)eed$/,s=/^(.+?)(ed|ing)$/,r.test(t)){let u=r.exec(t);r=new RegExp(Ln),r.test(u[1])&&(r=/.$/,t=t.replace(r,""))}else s.test(t)&&(e=s.exec(t)[1],s=new RegExp(Zs),s.test(e)&&(t=e,s=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),o=new RegExp("^"+Z+St+"[^aeiouwxy]$"),s.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):o.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Zs),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Ln),e&&r.test(e)&&(t=e+ju[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let u=r.exec(t);e=u?.[1],n=u?.[2],r=new RegExp(Ln),e&&r.test(e)&&(t=e+Cu[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,s=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(_t),e&&r.test(e)&&(t=e);else if(s.test(t)){let u=s.exec(t);e=u?.[1]??""+u?.[2]??"",s=new RegExp(_t),s.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(_t),s=new RegExp(Bu),i=new RegExp("^"+Z+St+"[^aeiouwxy]$"),e&&(r.test(e)||s.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,s=new RegExp(_t),r.test(t)&&s.test(t)&&(r=/.$/,t=t.replace(r,"")),c=="y"&&(t=c.toLowerCase()+t.substring(1)),t}});var It=b(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.normalizeToken=Cn;bt.createTokenizer=Wu;var Ee=j(),qu=Xs(),ti=lt(),zu=Qs();function Cn(t,e,n=!0){let r=`${this.language}:${t}:${e}`;return n&&this.normalizationCache.has(r)?this.normalizationCache.get(r):this.stopWords?.includes(e)?(n&&this.normalizationCache.set(r,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=(0,qu.replaceDiacritics)(e),n&&this.normalizationCache.set(r,e),e)}function Vu(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function ei(t,e,n,r=!0){if(e&&e!==this.language)throw(0,Ee.createError)("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let s=this.normalizeToken.bind(this,n??""),i;if(n&&this.tokenizeSkipProperties.has(n))i=[s(t,r)];else{let c=ti.SPLITTERS[this.language];i=t.toLowerCase().split(c).map(u=>s(u,r)).filter(Boolean)}let o=Vu(i);return this.allowDuplicates?o:Array.from(new Set(o))}function Wu(t={}){if(!t.language)t.language="english";else if(!ti.SUPPORTED_LANGUAGES.includes(t.language))throw(0,Ee.createError)("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw(0,Ee.createError)("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=zu.stemmer;else throw(0,Ee.createError)("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw(0,Ee.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw(0,Ee.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let s of n)if(typeof s!="string")throw(0,Ee.createError)("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:ei,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Cn,normalizationCache:new Map};return r.tokenize=ei.bind(r),r.normalizeToken=Cn,r}});var Fn=b(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.getMatchingRules=ni;Ne.load=ri;Ne.save=si;Ne.createPinning=ea;function Ku(t){return{sharedInternalDocumentStore:t,rules:new Map}}function Hu(t,e){if(t.rules.has(e.id))throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${e.id}" already exists. Use updateRule to modify it.`);t.rules.set(e.id,e)}function Gu(t,e){if(!t.rules.has(e.id))throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${e.id}" because it does not exist. Use addRule to create it.`);t.rules.set(e.id,e)}function Yu(t,e){return t.rules.delete(e)}function Ju(t,e){return t.rules.get(e)}function Xu(t){return Array.from(t.rules.values())}function Zu(t,e){let n=t.toLowerCase().trim(),r=e.pattern.toLowerCase().trim();switch(e.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function Qu(t,e){return t?e.conditions.every(n=>Zu(t,n)):!1}function ni(t,e){if(!e)return[];let n=[];for(let r of t.rules.values())Qu(e,r)&&n.push(r);return n}function ri(t,e){let n=e;return{sharedInternalDocumentStore:t,rules:new Map(n?.rules??[])}}function si(t){return{rules:Array.from(t.rules.entries())}}function ea(){return{create:Ku,addRule:Hu,updateRule:Gu,removeRule:Yu,getRule:Ju,getAllRules:Xu,getMatchingRules:ni,load:ri,save:si}}});var ci=b(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.create=ua;var xt=$e(),ta=wn(),ii=ys(),Et=te(),na=mt(),ra=V(),sa=Un(),oi=It(),ia=Fn(),At=j(),oa=R();function ca(t){let e={formatElapsedTime:xt.formatElapsedTime,getDocumentIndexId:xt.getDocumentIndexId,getDocumentProperties:xt.getDocumentProperties,validateSchema:xt.validateSchema};for(let n of Et.FUNCTION_COMPONENTS){let r=n;if(t[r]){if(typeof t[r]!="function")throw(0,At.createError)("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!Et.OBJECT_COMPONENTS.includes(n)&&!Et.FUNCTION_COMPONENTS.includes(n))throw(0,At.createError)("UNSUPPORTED_COMPONENT",n)}function ua({schema:t,sort:e,language:n,components:r,id:s,plugins:i}){r||(r={});for(let w of i??[]){if(!("getComponents"in w)||typeof w.getComponents!="function")continue;let S=w.getComponents(t),_=Object.keys(S);for(let I of _)if(r[I])throw(0,At.createError)("PLUGIN_COMPONENT_CONFLICT",I,w.name);r={...r,...S}}s||(s=(0,oa.uniqueId)());let o=r.tokenizer,c=r.index,u=r.documentsStore,a=r.sorter,l=r.pinning;if(o?o.tokenize?o=o:o=(0,oi.createTokenizer)(o):o=(0,oi.createTokenizer)({language:n??"english"}),r.tokenizer&&n)throw(0,At.createError)("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let d=(0,ra.createInternalDocumentIDStore)();c||=(0,na.createIndex)(),a||=(0,sa.createSorter)(),u||=(0,ta.createDocumentsStore)(),l||=(0,ia.createPinning)(),ca(r);let{getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,formatElapsedTime:y}=r,h={data:{},caches:{},schema:t,tokenizer:o,index:c,sorter:a,documentsStore:u,pinning:l,internalDocumentIDStore:d,getDocumentProperties:f,getDocumentIndexId:p,validateSchema:g,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeUpsert:[],afterUpsert:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],beforeUpdateMultiple:[],afterUpdateMultiple:[],beforeUpsertMultiple:[],afterUpsertMultiple:[],afterCreate:[],formatElapsedTime:y,id:s,plugins:i,version:aa()};h.data={index:h.index.create(h,d,t),docs:h.documentsStore.create(h,d),sorting:h.sorter.create(h,d,t,e),pinning:h.pinning.create(d)};for(let w of ii.AVAILABLE_PLUGIN_HOOKS)h[w]=(h[w]??[]).concat((0,ii.getAllPluginsByHook)(h,w));let m=h.afterCreate;return m&&(0,Et.runAfterCreate)(m,h),h}function aa(){return"{{VERSION}}"}});var $n=b(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.getByID=la;vt.count=da;function la(t,e){return t.documentsStore.get(t.data.docs,e)}function da(t){return t.documentsStore.count(t.data.docs)}});var qn=b(U=>{"use strict";var ui=U&&U.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),fa=U&&U.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),ha=U&&U.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ui(e,t,n)},Je=U&&U.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.insert=Wn;Xe.insertMultiple=Sa;Xe.innerInsertMultiple=ba;var zn=qn(),F=R(),Ue=te(),Re=j(),Vn=V();function Wn(t,e,n,r,s){let i=t.validateSchema(e,t.schema);if(i)throw(0,Re.createError)("SCHEMA_VALIDATION_FAILURE",i);return(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?ya(t,e,n,r,s):ma(t,e,n,r,s)}var pa=new Set(["enum","enum[]"]),ga=new Set(["string","number"]);async function ya(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Re.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Vn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||await(0,Ue.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Re.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ai(y,h,p,g)}return await wa(t,c,l,f,a,n,e,s),r||await(0,Ue.runSingleHook)(t.afterInsert,t,c,e),c}function ma(t,e,n,r,s){let{index:i,docs:o}=t.data,c=t.getDocumentIndexId(e);if(typeof c!="string")throw(0,Re.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof c);let u=(0,Vn.getInternalDocumentId)(t.internalDocumentIDStore,c);if(r||(0,Ue.runSingleHook)(t.beforeInsert,t,c,e),!t.documentsStore.store(o,c,u,e))throw(0,Re.createError)("DOCUMENT_ALREADY_EXISTS",c);let a=t.documentsStore.count(o),l=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(e,l);for(let[p,g]of Object.entries(f)){if(typeof g>"u")continue;let y=typeof g,h=d[p];ai(y,h,p,g)}return _a(t,c,l,f,a,n,e,s),r||(0,Ue.runSingleHook)(t.afterInsert,t,c,e),c}function ai(t,e,n,r){if(!((0,zn.isGeoPointType)(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!((0,zn.isVectorType)(e)&&Array.isArray(r))&&!((0,zn.isArrayType)(e)&&Array.isArray(r))&&!(pa.has(e)&&ga.has(t))&&t!==e)throw(0,Re.createError)("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function wa(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l];await t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s);let p=t.internalDocumentIDStore.idToInternalId.get(e);await t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),await t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function _a(t,e,n,r,s,i,o,c){for(let l of n){let d=r[l];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[l],p=(0,Vn.getInternalDocumentId)(t.internalDocumentIDStore,e);t.index.beforeInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s),t.index.insert(t.index,t.data.index,l,e,p,d,f,i,t.tokenizer,s,c),t.index.afterInsert?.(t.data.index,l,e,d,f,i,t.tokenizer,s)}let u=t.sorter.getSortableProperties(t.data.sorting),a=t.getDocumentProperties(o,u);for(let l of u){let d=a[l];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[l];t.sorter.insert(t.data.sorting,l,e,d,f,i)}}function Sa(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.afterInsertMultiple)||(0,F.isAsyncFunction)(t.beforeInsertMultiple)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?li(t,e,n,r,s,i):di(t,e,n,r,s,i)}async function li(t,e,n=1e3,r,s,i=0){let o=[],c=async a=>{let l=Math.min(a+n,e.length),d=e.slice(a,l);for(let f of d){let p={avlRebalanceThreshold:d.length},g=await Wn(t,f,r,s,p);o.push(g)}return l};return await(async()=>{let a=0;for(;a0){let d=Date.now()-l,f=i-d;f>0&&(0,F.sleep)(f)}}})(),s||await(0,Ue.runMultipleHook)(t.afterInsertMultiple,t,e),o}function di(t,e,n=1e3,r,s,i=0){let o=[],c=0;function u(){let l=e.slice(c*n,(c+1)*n);if(l.length===0)return!1;for(let d of l){let f={avlRebalanceThreshold:l.length},p=Wn(t,d,r,s,f);o.push(p)}return c++,!0}function a(){let l=Date.now();for(;u();)if(i>0){let f=Date.now()-l;if(f>=i){let p=i-f%i;p>0&&(0,F.sleep)(p)}}}return a(),s||(0,Ue.runMultipleHook)(t.afterInsertMultiple,t,e),o}function ba(t,e,n,r,s,i){return(0,F.isAsyncFunction)(t.beforeInsert)||(0,F.isAsyncFunction)(t.afterInsert)||(0,F.isAsyncFunction)(t.index.beforeInsert)||(0,F.isAsyncFunction)(t.index.insert)||(0,F.isAsyncFunction)(t.index.afterInsert)?li(t,e,n,r,s,i):di(t,e,n,r,s,i)}});var fi=b(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.insertPin=Ia;Ae.updatePin=xa;Ae.deletePin=Ea;Ae.getPin=Aa;Ae.getAllPins=va;function Ia(t,e){t.pinning.addRule(t.data.pinning,e)}function xa(t,e){t.pinning.updateRule(t.data.pinning,e)}function Ea(t,e){return t.pinning.removeRule(t.data.pinning,e)}function Aa(t,e){return t.pinning.getRule(t.data.pinning,e)}function va(t){return t.pinning.getAllRules(t.data.pinning)}});var Hn=b(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.remove=Kn;Dt.removeMultiple=Ma;var fe=te(),he=V(),de=R();function Kn(t,e,n,r){return(0,de.isAsyncFunction)(t.index.beforeRemove)||(0,de.isAsyncFunction)(t.index.remove)||(0,de.isAsyncFunction)(t.index.afterRemove)?Ta(t,e,n,r):Da(t,e,n,r)}async function Ta(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,he.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,he.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||await(0,fe.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];await t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),await t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),await t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=await t.sorter.getSortableProperties(t.data.sorting),y=await t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await(0,fe.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Da(t,e,n,r){let s=!0,{index:i,docs:o}=t.data,c=t.documentsStore.get(o,e);if(!c)return!1;let u=(0,he.getInternalDocumentId)(t.internalDocumentIDStore,e),a=(0,he.getDocumentIdFromInternalId)(t.internalDocumentIDStore,u),l=t.documentsStore.count(o);r||(0,fe.runSingleHook)(t.beforeRemove,t,a);let d=t.index.getSearchableProperties(i),f=t.index.getSearchablePropertiesWithTypes(i),p=t.getDocumentProperties(c,d);for(let h of d){let m=p[h];if(typeof m>"u")continue;let w=f[h];t.index.beforeRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l),t.index.remove(t.index,t.data.index,h,e,u,m,w,n,t.tokenizer,l)||(s=!1),t.index.afterRemove?.(t.data.index,h,a,m,w,n,t.tokenizer,l)}let g=t.sorter.getSortableProperties(t.data.sorting),y=t.getDocumentProperties(c,g);for(let h of g)typeof y[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||(0,fe.runSingleHook)(t.afterRemove,t,a),t.documentsStore.remove(t.data.docs,e,u),s}function Ma(t,e,n,r,s){return(0,de.isAsyncFunction)(t.index.beforeRemove)||(0,de.isAsyncFunction)(t.index.remove)||(0,de.isAsyncFunction)(t.index.afterRemove)||(0,de.isAsyncFunction)(t.beforeRemoveMultiple)||(0,de.isAsyncFunction)(t.afterRemoveMultiple)?Oa(t,e,n,r,s):Pa(t,e,n,r,s)}async function Oa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(c=>(0,he.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,he.getInternalDocumentId)(t.internalDocumentIDStore,c)));return s||await(0,fe.runMultipleHook)(t.beforeRemoveMultiple,t,o),await new Promise((c,u)=>{let a=0;async function l(){let d=e.slice(a*n,++a*n);if(!d.length)return c();for(let f of d)try{await Kn(t,f,r,s)&&i++}catch(p){u(p)}setTimeout(l,0)}setTimeout(l,0)}),s||await(0,fe.runMultipleHook)(t.afterRemoveMultiple,t,o),i}function Pa(t,e,n,r,s){let i=0;n||(n=1e3);let o=s?[]:e.map(a=>(0,he.getDocumentIdFromInternalId)(t.internalDocumentIDStore,(0,he.getInternalDocumentId)(t.internalDocumentIDStore,a)));s||(0,fe.runMultipleHook)(t.beforeRemoveMultiple,t,o);let c=0;function u(){let a=e.slice(c*n,++c*n);if(a.length){for(let l of a)Kn(t,l,r,s)&&i++;setTimeout(u,0)}}return u(),s||(0,fe.runMultipleHook)(t.afterRemoveMultiple,t,o),i}});var Gn=b(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.MODE_VECTOR_SEARCH=pe.MODE_HYBRID_SEARCH=pe.MODE_FULLTEXT_SEARCH=void 0;pe.MODE_FULLTEXT_SEARCH="fulltext";pe.MODE_HYBRID_SEARCH="hybrid";pe.MODE_VECTOR_SEARCH="vector"});var Mt=b(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.getFacets=ja;var ka=j(),Na=R();function Ua(t,e){return t[1]-e[1]}function Ra(t,e){return e[1]-t[1]}function La(t="desc"){return t.toLowerCase()==="asc"?Ua:Ra}function ja(t,e,n){let r={},s=e.map(([a])=>a),i=t.documentsStore.getMultiple(t.data.docs,s),o=Object.keys(n),c=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let a of o){let l;if(c[a]==="number"){let{ranges:d}=n[a],f=d.length,p=Array.from({length:f});for(let g=0;g{for(let s of t){let i=`${s.from}-${s.to}`;n?.has(i)||r>=s.from&&r<=s.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function pi(t,e,n){let r=e==="boolean"?"false":"";return s=>{let i=s?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}});var Ot=b(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.getGroups=Ba;var gi=j(),Jn=R(),Ca=V(),Fa={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},yi=["string","number","boolean"];function Ba(t,e,n){let r=n.properties,s=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let m=0;m"u")throw(0,gi.createError)("UNKNOWN_GROUP_BY_PROPERTY",w);if(!yi.includes(i[w]))throw(0,gi.createError)("INVALID_GROUP_BY_PROPERTY",w,yi.join(", "),i[w])}let o=e.map(([m])=>(0,Ca.getDocumentIdFromInternalId)(t.internalDocumentIDStore,m)),c=t.documentsStore.getMultiple(t.data.docs,o),u=c.length,a=n.maxResult||Number.MAX_SAFE_INTEGER,l=[],d={};for(let m=0;m"u")continue;let A=typeof D!="boolean"?D:""+D,k=S.perValue[A]??{indexes:[],count:0};k.count>=a||(k.indexes.push(I),k.count++,S.perValue[A]=k,_.add(D))}l.push(Array.from(_)),d[w]=S}let f=mi(l),p=f.length,g=[];for(let m=0;mv-D),_.indexes.length!==0&&g.push(_)}let y=g.length,h=Array.from({length:y});for(let m=0;m({id:o[A],score:e[A][1],document:c[A]})),I=S.reducer.bind(null,w.values),v=S.getInitialValue(w.indexes.length),D=_.reduce(I,v);h[m]={values:w.values,result:D}}return h}function mi(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=mi(t,e+1),s=[];for(let i of n)for(let o of r){let c=[i];(0,Jn.safeArrayPush)(c,o),s.push(c)}return s}});var Pt=b(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.applyPinningRules=za;var $a=V(),qa=Fn();function za(t,e,n,r){let s=(0,qa.getMatchingRules)(e,r);if(s.length===0)return n;let i=s.flatMap(h=>h.consequence.promote);i.sort((h,m)=>h.position-m.position);let o=new Set,c=new Map,u=new Set;for(let h of i){let m=(0,$a.getInternalDocumentId)(t.internalDocumentIDStore,h.doc_id);if(m!==void 0){if(c.has(m)){let w=c.get(m);h.position!o.has(h)),l=1e6,d=[];for(let[h,m]of c.entries())n.find(([S])=>S===h)?d.push([h,l-m]):t.documentsStore.get(t.data.docs,h)&&d.push([h,0]);d.sort((h,m)=>{let w=c.get(h[0])??1/0,S=c.get(m[0])??1/0;return w-S});let f=[],p=new Map;for(let h of d){let m=c.get(h[0]);p.set(m,h)}let g=0,y=0;for(;y=f.length&&f.push(m);return f}});var Qn=b(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.defaultBM25Params=void 0;re.innerFullTextSearch=Si;re.fullTextSearch=Qa;var Va=Mt(),Wa=Ot(),wi=te(),Ka=V(),Ha=mt(),Ga=Pt(),Ya=j(),kt=R(),Ja=$n(),_i=Ze();function Si(t,e,n){let{term:r,properties:s}=e,i=t.data.index,o=t.caches.propertiesToSearch;if(!o){let d=t.index.getSearchablePropertiesWithTypes(i);o=t.index.getSearchableProperties(i),o=o.filter(f=>d[f].startsWith("string")),t.caches.propertiesToSearch=o}if(s&&s!=="*"){for(let d of s)if(!o.includes(d))throw(0,Ya.createError)("UNKNOWN_INDEX",d,o.join(", "));o=o.filter(d=>s.includes(d))}let c=Object.keys(e.where??{}).length>0,u;c&&(u=t.index.searchByWhereClause(i,t.tokenizer,e.where,n));let a,l=e.threshold!==void 0&&e.threshold!==null?e.threshold:1;if(r||s){let d=(0,Ja.count)(t);if(a=t.index.search(i,r||"",t.tokenizer,n,o,e.exact||!1,e.tolerance||0,e.boost||{},el(e.relevance),d,u,l),e.exact&&r){let f=r.trim().split(/\s+/);a=a.filter(([p])=>{let g=t.documentsStore.get(t.data.docs,p);if(!g)return!1;for(let y of o){let h=Za(g,y);if(typeof h=="string"&&f.every(w=>new RegExp(`\\b${Xa(w)}\\b`).test(h)))return!0}return!1})}}else if(c){let d=(0,Ha.searchByGeoWhereClause)(i,e.where);d?a=d:a=(u?Array.from(u):[]).map(p=>[+p,0])}else a=Object.keys(t.documentsStore.getAll(t.data.docs)).map(f=>[+f,0]);return a}function Xa(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Za(t,e){let n=e.split("."),r=t;for(let s of n)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Qa(t,e,n){let r=(0,kt.getNanosecondsTime)();function s(){let c=Object.keys(t.data.index.vectorIndexes),u=e.facets&&Object.keys(e.facets).length>0,{limit:a=10,offset:l=0,distinctOn:d,includeVectors:f=!1}=e,p=e.preflight===!0,g=Si(t,e,n);if(e.sortBy)if(typeof e.sortBy=="function"){let m=g.map(([_])=>_),S=t.documentsStore.getMultiple(t.data.docs,m).map((_,I)=>[g[I][0],g[I][1],_]);S.sort(e.sortBy),g=S.map(([_,I])=>[_,I])}else g=t.sorter.sortBy(t.data.sorting,g,e.sortBy).map(([m,w])=>[(0,Ka.getInternalDocumentId)(t.internalDocumentIDStore,m),w]);else g=g.sort(kt.sortTokenScorePredicate);g=(0,Ga.applyPinningRules)(t,t.data.pinning,g,e.term);let y;p||(y=d?(0,_i.fetchDocumentsWithDistinct)(t,g,l,a,d):(0,_i.fetchDocuments)(t,g,l,a));let h={elapsed:{formatted:"",raw:0},hits:[],count:g.length};if(typeof y<"u"&&(h.hits=y.filter(Boolean),f||(0,kt.removeVectorsFromHits)(h,c)),u){let m=(0,Va.getFacets)(t,g,e.facets);h.facets=m}return e.groupBy&&(h.groups=(0,Wa.getGroups)(t,g,e.groupBy)),h.elapsed=t.formatElapsedTime((0,kt.getNanosecondsTime)()-r),h}async function i(){t.beforeSearch&&await(0,wi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,wi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}re.defaultBM25Params={k:1.2,b:.75,d:.5};function el(t){let e=t??{};return e.k=e.k??re.defaultBM25Params.k,e.b=e.b??re.defaultBM25Params.b,e.d=e.d??re.defaultBM25Params.d,e}});var Lt=b(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.innerVectorSearch=Ii;Rt.searchVector=ol;var Nt=R(),tl=Mt(),Ut=j(),nl=Ot(),rl=V(),bi=te(),sl=Dn(),il=Pt();function Ii(t,e,n){let r=e.vector;if(r&&(!("value"in r)||!("property"in r)))throw(0,Ut.createError)("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let s=t.data.index.vectorIndexes[r.property];if(!s)throw(0,Ut.createError)("UNKNOWN_VECTOR_PROPERTY",r.property);let i=s.node.size;if(r?.value.length!==i)throw r?.property===void 0||r?.value.length===void 0?(0,Ut.createError)("INVALID_INPUT_VECTOR","undefined",i,"undefined"):(0,Ut.createError)("INVALID_INPUT_VECTOR",r.property,i,r.value.length);let o=t.data.index,c;return Object.keys(e.where??{}).length>0&&(c=t.index.searchByWhereClause(o,t.tokenizer,e.where,n)),s.node.find(r.value,e.similarity??sl.DEFAULT_SIMILARITY,c)}function ol(t,e,n="english"){let r=(0,Nt.getNanosecondsTime)();function s(){let c=Ii(t,e,n).sort(Nt.sortTokenScorePredicate);c=(0,il.applyPinningRules)(t,t.data.pinning,c,void 0);let u=[];e.facets&&Object.keys(e.facets).length>0&&(u=(0,tl.getFacets)(t,c,e.facets));let l=e.vector.property,d=e.includeVectors??!1,f=e.limit??10,p=e.offset??0,g=Array.from({length:f});for(let w=0;w{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.innerHybridSearch=Ai;Ct.hybridSearch=hl;var jt=R(),cl=Mt(),ul=Ot(),al=Ze(),ll=Qn(),dl=Lt(),xi=te(),fl=Pt();function Ai(t,e,n){let r=pl((0,ll.innerFullTextSearch)(t,e,n)),s=(0,dl.innerVectorSearch)(t,e,n),i=e.hybridWeights;return yl(r,s,e.term??"",i)}function hl(t,e,n){let r=(0,jt.getNanosecondsTime)();function s(){let c=Ai(t,e,n);c=(0,fl.applyPinningRules)(t,t.data.pinning,c,e.term);let u;e.facets&&Object.keys(e.facets).length>0&&(u=(0,cl.getFacets)(t,c,e.facets));let l;e.groupBy&&(l=(0,ul.getGroups)(t,c,e.groupBy));let d=e.offset??0,f=e.limit??10,p=(0,al.fetchDocuments)(t,c,d,f).filter(Boolean),g=(0,jt.getNanosecondsTime)(),y={count:c.length,elapsed:{raw:Number(g-r),formatted:(0,jt.formatNanoseconds)(g-r)},hits:p,...u?{facets:u}:{},...l?{groups:l}:{}};if(!(e.includeVectors??!1)){let m=Object.keys(t.data.index.vectorIndexes);(0,jt.removeVectorsFromHits)(y,m)}return y}async function i(){t.beforeSearch&&await(0,xi.runBeforeSearch)(t.beforeSearch,t,e,n);let c=s();return t.afterSearch&&await(0,xi.runAfterSearch)(t.afterSearch,t,e,n,c),c}return t.beforeSearch?.length||t.afterSearch?.length?i():s()}function er(t){return t[1]}function pl(t){let e=Math.max.apply(Math,t.map(er));return t.map(([n,r])=>[n,r/e])}function Ei(t,e){return t/e}function gl(t,e){return(n,r)=>n*t+r*e}function yl(t,e,n,r){let s=Math.max.apply(Math,t.map(er)),i=Math.max.apply(Math,e.map(er)),o=r&&r.text&&r.vector,{text:c,vector:u}=o?r:ml(n),a=new Map,l=t.length,d=gl(c,u);for(let p=0;pg[1]-p[1])}function ml(t){return{text:.5,vector:.5}}});var Ze=b(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.search=xl;Qe.fetchDocumentsWithDistinct=El;Qe.fetchDocuments=Al;var Ti=V(),wl=j(),_l=R(),Ft=Gn(),Sl=Qn(),bl=Lt(),Il=vi();function xl(t,e,n){let r=e.mode??Ft.MODE_FULLTEXT_SEARCH;if(r===Ft.MODE_FULLTEXT_SEARCH)return(0,Sl.fullTextSearch)(t,e,n);if(r===Ft.MODE_VECTOR_SEARCH)return(0,bl.searchVector)(t,e);if(r===Ft.MODE_HYBRID_SEARCH)return(0,Il.hybridSearch)(t,e);throw(0,wl.createError)("INVALID_SEARCH_MODE",r)}function El(t,e,n,r,s){let i=t.data.docs,o=new Map,c=[],u=new Set,a=e.length,l=0;for(let d=0;d"u")continue;let[p,g]=f;if(u.has(p))continue;let y=t.documentsStore.get(i,p),h=(0,_l.getNested)(y,s);if(!(typeof h>"u"||o.has(h))&&(o.set(h,!0),l++,!(l<=n)&&(c.push({id:(0,Ti.getDocumentIdFromInternalId)(t.internalDocumentIDStore,p),score:g,document:y}),u.add(p),l>=n+r)))break}return c}function Al(t,e,n,r){let s=t.data.docs,i=Array.from({length:r}),o=new Set;for(let c=n;c"u")break;let[a,l]=u;if(!o.has(a)){let d=t.documentsStore.get(s,a);i[c]={id:(0,Ti.getDocumentIdFromInternalId)(t.internalDocumentIDStore,a),score:l,document:d},o.add(a)}}return i}});var Di=b(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.load=vl;Bt.save=Tl;function vl(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.data.pinning=t.pinning.load(t.internalDocumentIDStore,e.pinning),t.tokenizer.language=e.language}function Tl(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),pinning:t.pinning.save(t.data.pinning),language:t.tokenizer.language}}});var tr=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.update=Dl;zt.updateMultiple=Pl;var ge=te(),Mi=j(),$t=Tt(),qt=Hn(),C=R();function Dl(t,e,n,r,s){return(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterRemove)||(0,C.isAsyncFunction)(t.beforeRemove)||(0,C.isAsyncFunction)(t.beforeUpdate)||(0,C.isAsyncFunction)(t.afterUpdate)?Ml(t,e,n,r,s):Ol(t,e,n,r,s)}async function Ml(t,e,n,r,s){!s&&t.beforeUpdate&&await(0,ge.runSingleHook)(t.beforeUpdate,t,e),await(0,qt.remove)(t,e,r,s);let i=await(0,$t.insert)(t,n,r,s);return!s&&t.afterUpdate&&await(0,ge.runSingleHook)(t.afterUpdate,t,i),i}function Ol(t,e,n,r,s){!s&&t.beforeUpdate&&(0,ge.runSingleHook)(t.beforeUpdate,t,e),(0,qt.remove)(t,e,r,s);let i=(0,$t.insert)(t,n,r,s);return!s&&t.afterUpdate&&(0,ge.runSingleHook)(t.afterUpdate,t,i),i}function Pl(t,e,n,r,s,i){return(0,C.isAsyncFunction)(t.afterInsert)||(0,C.isAsyncFunction)(t.beforeInsert)||(0,C.isAsyncFunction)(t.afterRemove)||(0,C.isAsyncFunction)(t.beforeRemove)||(0,C.isAsyncFunction)(t.beforeUpdate)||(0,C.isAsyncFunction)(t.afterUpdate)||(0,C.isAsyncFunction)(t.beforeUpdateMultiple)||(0,C.isAsyncFunction)(t.afterUpdateMultiple)||(0,C.isAsyncFunction)(t.beforeRemoveMultiple)||(0,C.isAsyncFunction)(t.afterRemoveMultiple)||(0,C.isAsyncFunction)(t.beforeInsertMultiple)||(0,C.isAsyncFunction)(t.afterInsertMultiple)?kl(t,e,n,r,s,i):Nl(t,e,n,r,s,i)}async function kl(t,e,n,r,s,i){i||await(0,ge.runMultipleHook)(t.beforeUpdateMultiple,t,e);let o=n.length;for(let u=0;u{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.upsert=Ul;Kt.upsertMultiple=jl;var ye=te(),Le=j(),Vt=Tt(),Wt=tr(),P=R();function Ul(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Rl(t,e,n,r,s):Ll(t,e,n,r,s)}async function Rl(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&await(0,ye.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=await(0,Wt.update)(t,i,e,n,r):c=await(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&await(0,ye.runSingleHook)(t.afterUpsert,t,c,e),c}function Ll(t,e,n,r,s){let i=t.getDocumentIndexId(e);if(typeof i!="string")throw(0,Le.createError)("DOCUMENT_ID_MUST_BE_STRING",typeof i);!r&&t.beforeUpsert&&(0,ye.runSingleHook)(t.beforeUpsert,t,i,e);let o=t.documentsStore.get(t.data.docs,i),c;return o?c=(0,Wt.update)(t,i,e,n,r):c=(0,Vt.insert)(t,e,n,r,s),!r&&t.afterUpsert&&(0,ye.runSingleHook)(t.afterUpsert,t,c,e),c}function jl(t,e,n,r,s){return(0,P.isAsyncFunction)(t.afterInsert)||(0,P.isAsyncFunction)(t.beforeInsert)||(0,P.isAsyncFunction)(t.afterRemove)||(0,P.isAsyncFunction)(t.beforeRemove)||(0,P.isAsyncFunction)(t.beforeUpdate)||(0,P.isAsyncFunction)(t.afterUpdate)||(0,P.isAsyncFunction)(t.beforeUpsert)||(0,P.isAsyncFunction)(t.afterUpsert)||(0,P.isAsyncFunction)(t.beforeUpsertMultiple)||(0,P.isAsyncFunction)(t.afterUpsertMultiple)||(0,P.isAsyncFunction)(t.beforeInsertMultiple)||(0,P.isAsyncFunction)(t.afterInsertMultiple)||(0,P.isAsyncFunction)(t.beforeUpdateMultiple)||(0,P.isAsyncFunction)(t.afterUpdateMultiple)||(0,P.isAsyncFunction)(t.beforeRemoveMultiple)||(0,P.isAsyncFunction)(t.afterRemoveMultiple)||(0,P.isAsyncFunction)(t.index.beforeInsert)||(0,P.isAsyncFunction)(t.index.insert)||(0,P.isAsyncFunction)(t.index.afterInsert)?Cl(t,e,n,r,s):Fl(t,e,n,r,s)}async function Cl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&await(0,ye.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=await(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=await(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&await(0,ye.runMultipleHook)(t.afterUpsertMultiple,t,a),a}function Fl(t,e,n,r,s){!s&&t.beforeUpsertMultiple&&(0,ye.runMultipleHook)(t.beforeUpsertMultiple,t,e);let i=e.length;for(let l=0;l0){let l=(0,Wt.updateMultiple)(t,u,c,n,r,s);a.push(...l)}if(o.length>0){let l=(0,Vt.innerInsertMultiple)(t,o,n,r,s);a.push(...l)}return!s&&t.afterUpsertMultiple&&(0,ye.runMultipleHook)(t.afterUpsertMultiple,t,a),a}});var Pi=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.AnswerSession=void 0;var Ht=j(),Bl=Ze(),$l="orama-secure-proxy",nr=class{db;proxy=null;config;abortController=null;lastInteractionParams=null;chatModel=null;conversationID;messages=[];events;initPromise;state=[];constructor(e,n){this.db=e,this.config=n,this.init(),this.messages=n.initialMessages||[],this.events=n.events||{},this.conversationID=n.conversationID||this.generateRandomID()}async ask(e){await this.initPromise;let n="";for await(let r of await this.askStream(e))n+=r;return n}async askStream(e){return await this.initPromise,this.fetchAnswer(e)}abortAnswer(){this.abortController?.abort(),this.state[this.state.length-1].aborted=!0,this.triggerStateChange()}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[]}regenerateLast({stream:e=!0}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw(0,Ht.createError)("ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}async*fetchAnswer(e){if(!this.chatModel)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL");this.abortController=new AbortController,this.lastInteractionParams=e;let n=this.generateRandomID();this.messages.push({role:"user",content:e.term??""}),this.state.push({interactionId:n,aborted:!1,loading:!0,query:e.term??"",response:"",sources:null,translatedQuery:null,error:!1,errorMessage:null});let r=this.state.length-1;this.addEmptyAssistantMessage(),this.triggerStateChange();try{let s=await(0,Bl.search)(this.db,e);this.state[r].sources=s,this.triggerStateChange();for await(let i of this.proxy.chatStream({model:this.chatModel,messages:this.messages}))yield i,this.state[r].response+=i,this.messages.findLast(o=>o.role==="assistant").content+=i,this.triggerStateChange()}catch(s){s.name==="AbortError"?this.state[r].aborted=!0:(this.state[r].error=!0,this.state[r].errorMessage=s.toString()),this.triggerStateChange()}return this.state[r].loading=!1,this.triggerStateChange(),this.state[r].response}generateRandomID(e=24){return Array.from({length:e},()=>Math.floor(Math.random()*36).toString(36)).join("")}triggerStateChange(){this.events.onStateChange&&this.events.onStateChange(this.state)}async init(){let e=this;async function n(){return await e.db.plugins.find(i=>i.name===$l)}let r=await n();if(!r)throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_NOT_FOUND");let s=r.extra;if(this.proxy=s.proxy,this.config.systemPrompt&&this.messages.push({role:"system",content:this.config.systemPrompt}),s?.pluginParams?.chat?.model)this.chatModel=s.pluginParams.chat.model;else throw(0,Ht.createError)("PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL")}addEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}};Gt.AnswerSession=nr});var ki=b(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.kRemovals=Y.kInsertions=Y.MODE_VECTOR_SEARCH=Y.MODE_HYBRID_SEARCH=Y.MODE_FULLTEXT_SEARCH=void 0;var rr=Gn();Object.defineProperty(Y,"MODE_FULLTEXT_SEARCH",{enumerable:!0,get:function(){return rr.MODE_FULLTEXT_SEARCH}});Object.defineProperty(Y,"MODE_HYBRID_SEARCH",{enumerable:!0,get:function(){return rr.MODE_HYBRID_SEARCH}});Object.defineProperty(Y,"MODE_VECTOR_SEARCH",{enumerable:!0,get:function(){return rr.MODE_VECTOR_SEARCH}});Y.kInsertions=Symbol("orama.insertions");Y.kRemovals=Symbol("orama.removals")});var Ni=b(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.normalizeToken=N.setDifference=N.setUnion=N.setIntersection=N.safeArrayPush=N.convertDistanceToMeters=N.uniqueId=N.getNanosecondsTime=N.formatNanoseconds=N.formatBytes=N.boundedLevenshtein=void 0;var ql=bn();Object.defineProperty(N,"boundedLevenshtein",{enumerable:!0,get:function(){return ql.boundedLevenshtein}});var se=R();Object.defineProperty(N,"formatBytes",{enumerable:!0,get:function(){return se.formatBytes}});Object.defineProperty(N,"formatNanoseconds",{enumerable:!0,get:function(){return se.formatNanoseconds}});Object.defineProperty(N,"getNanosecondsTime",{enumerable:!0,get:function(){return se.getNanosecondsTime}});Object.defineProperty(N,"uniqueId",{enumerable:!0,get:function(){return se.uniqueId}});Object.defineProperty(N,"convertDistanceToMeters",{enumerable:!0,get:function(){return se.convertDistanceToMeters}});Object.defineProperty(N,"safeArrayPush",{enumerable:!0,get:function(){return se.safeArrayPush}});Object.defineProperty(N,"setIntersection",{enumerable:!0,get:function(){return se.setIntersection}});Object.defineProperty(N,"setUnion",{enumerable:!0,get:function(){return se.setUnion}});Object.defineProperty(N,"setDifference",{enumerable:!0,get:function(){return se.setDifference}});var zl=It();Object.defineProperty(N,"normalizeToken",{enumerable:!0,get:function(){return zl.normalizeToken}})});var qi=b(x=>{"use strict";var Ui=x&&x.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Vl=x&&x.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wl=x&&x.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ui(e,t,n)},Ri=x&&x.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.utf8Count=Jl;ie.utf8EncodeJs=zi;ie.utf8EncodeTE=Vi;ie.utf8Encode=Ql;ie.utf8DecodeJs=Wi;ie.utf8DecodeTD=Ki;ie.utf8Decode=rd;function Jl(t){let e=t.length,n=0,r=0;for(;r=55296&&s<=56319&&r>6&31|192;else{if(o>=55296&&o<=56319&&i>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}var Xl=new TextEncoder,Zl=50;function Vi(t,e,n){Xl.encodeInto(t,e.subarray(n))}function Ql(t,e,n){t.length>Zl?Vi(t,e,n):zi(t,e,n)}var ed=4096;function Wi(t,e,n){let r=e,s=r+n,i=[],o="";for(;r65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(c);i.length>=ed&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}var td=new TextDecoder,nd=200;function Ki(t,e,n){let r=t.subarray(e,e+n);return td.decode(r)}function rd(t,e,n){return n>nd?Ki(t,e,n):Wi(t,e,n)}});var ir=b(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.ExtData=void 0;var sr=class{type;data;constructor(e,n){this.type=e,this.data=n}};Jt.ExtData=sr});var Zt=b(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DecodeError=void 0;var or=class t extends Error{constructor(e){super(e);let n=Object.create(t.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};Xt.DecodeError=or});var Qt=b(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.UINT32_MAX=void 0;me.setUint64=sd;me.setInt64=id;me.getInt64=od;me.getUint64=cd;me.UINT32_MAX=4294967295;function sd(t,e,n){let r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function id(t,e,n){let r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function od(t,e){let n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function cd(t,e){let n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}});var cr=b(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.timestampExtension=J.EXT_TIMESTAMP=void 0;J.encodeTimeSpecToTimestamp=Gi;J.encodeDateToTimeSpec=Yi;J.encodeTimestampExtension=Ji;J.decodeTimestampToTimeSpec=Xi;J.decodeTimestampExtension=Zi;var ud=Zt(),Hi=Qt();J.EXT_TIMESTAMP=-1;var ad=4294967296-1,ld=17179869184-1;function Gi({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=ld)if(e===0&&t<=ad){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{let n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),(0,Hi.setInt64)(r,4,t),n}}function Yi(t){let e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function Ji(t){if(t instanceof Date){let e=Yi(t);return Gi(e)}else return null}function Xi(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{let n=(0,Hi.getInt64)(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ud.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Zi(t){let e=Xi(t);return new Date(e.sec*1e3+e.nsec/1e6)}J.timestampExtension={type:J.EXT_TIMESTAMP,encode:Ji,decode:Zi}});var nn=b(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.ExtensionCodec=void 0;var en=ir(),dd=cr(),ur=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(dd.timestampExtension)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{let s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.ensureUint8Array=hd;function fd(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function hd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):fd(t)?new Uint8Array(t):Uint8Array.from(t)}});var fr=b(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.Encoder=Q.DEFAULT_INITIAL_BUFFER_SIZE=Q.DEFAULT_MAX_DEPTH=void 0;var Qi=Yt(),pd=nn(),eo=Qt(),gd=lr();Q.DEFAULT_MAX_DEPTH=100;Q.DEFAULT_INITIAL_BUFFER_SIZE=2048;var dr=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Q.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??Q.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Qi.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Qi.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let r=(0,gd.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,n){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(let s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){let r=Object.keys(e);this.sortKeys&&r.sort();let s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(let i of r){let o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,eo.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,eo.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};Q.Encoder=dr});var to=b(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.encode=md;var yd=fr();function md(t,e){return new yd.Encoder(e).encodeSharedRef(t)}});var no=b(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.prettyByte=wd;function wd(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var ro=b(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.CachedKeyDecoder=void 0;var _d=Yt(),Sd=16,bd=16,gr=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=Sd,n=bd){this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r0&&e<=this.maxKeyLength}find(e,n,r){let s=this.caches[r-1];e:for(let i of s){let o=i.bytes;for(let c=0;c=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){let s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;let i=(0,_d.utf8DecodeJs)(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}};rn.CachedKeyDecoder=gr});var on=b(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.Decoder=void 0;var yr=no(),Id=nn(),ve=Qt(),xd=Yt(),so=lr(),Ed=ro(),oe=Zt(),mr="array",nt="map_key",oo="map_value",Ad=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new oe.DecodeError("The type of key must be string or number but "+typeof t)},wr=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=mr,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=nt,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===mr){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===nt||e.type===oo){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},tt=-1,Sr=new DataView(new ArrayBuffer(0)),vd=new Uint8Array(Sr.buffer);try{Sr.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var io=new RangeError("Insufficient data"),Td=new Ed.CachedKeyDecoder,_r=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Sr;bytes=vd;headByte=tt;stack=new wr;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Id.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??ve.UINT32_MAX,this.maxBinLength=e?.maxBinLength??ve.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??ve.UINT32_MAX,this.maxMapLength=e?.maxMapLength??ve.UINT32_MAX,this.maxExtLength=e?.maxExtLength??ve.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Td,this.mapKeyConverter=e?.mapKeyConverter??Ad}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=tt,this.stack.reset()}setBuffer(e){let n=(0,so.ensureUint8Array)(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===tt&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),r=(0,so.ensureUint8Array)(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(let c of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{r=this.doDecodeSync(),n=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${(0,yr.prettyByte)(s)} at ${o} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(let i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){let s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{let s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){let s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){let s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){let s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){let s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){let s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){let s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){let s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){let s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){let s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){let s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){let s=this.lookU32();n=this.decodeExtension(s,4)}else throw new oe.DecodeError(`Unrecognized type byte: ${(0,yr.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let s=r.top();if(s.type===mr)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===nt){if(n==="__proto__")throw new oe.DecodeError("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=oo;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=nt;continue e}}return n}}readHeadByte(){return this.headByte===tt&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=tt}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new oe.DecodeError(`Unrecognized array type byte: ${(0,yr.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new oe.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new oe.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new oe.DecodeError(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength0?this.stack.top().type===nt:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new oe.DecodeError(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw io;let r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new oe.DecodeError(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=(0,ve.getUint64)(this.view,this.pos);return this.pos+=8,e}readI64(){let e=(0,ve.getInt64)(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};sn.Decoder=_r});var uo=b(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.decode=Dd;cn.decodeMulti=Md;var co=on();function Dd(t,e){return new co.Decoder(e).decode(t)}function Md(t,e){return new co.Decoder(e).decodeMulti(t)}});var fo=b(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.isAsyncIterable=ao;rt.asyncIterableFromStream=lo;rt.ensureAsyncIterable=Od;function ao(t){return t[Symbol.asyncIterator]!=null}async function*lo(t){let e=t.getReader();try{for(;;){let{done:n,value:r}=await e.read();if(n)return;yield r}}finally{e.releaseLock()}}function Od(t){return ao(t)?t:lo(t)}});var ho=b(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.decodeAsync=Pd;st.decodeArrayStream=kd;st.decodeMultiStream=Nd;var br=on(),Ir=fo();async function Pd(t,e){let n=(0,Ir.ensureAsyncIterable)(t);return new br.Decoder(e).decodeAsync(n)}function kd(t,e){let n=(0,Ir.ensureAsyncIterable)(t);return new br.Decoder(e).decodeArrayStream(n)}function Nd(t,e){let n=(0,Ir.ensureAsyncIterable)(t);return new br.Decoder(e).decodeStream(n)}});var go=b(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.decodeTimestampExtension=M.encodeTimestampExtension=M.decodeTimestampToTimeSpec=M.encodeTimeSpecToTimestamp=M.encodeDateToTimeSpec=M.EXT_TIMESTAMP=M.ExtData=M.ExtensionCodec=M.Encoder=M.DecodeError=M.Decoder=M.decodeMultiStream=M.decodeArrayStream=M.decodeAsync=M.decodeMulti=M.decode=M.encode=void 0;var Ud=to();Object.defineProperty(M,"encode",{enumerable:!0,get:function(){return Ud.encode}});var po=uo();Object.defineProperty(M,"decode",{enumerable:!0,get:function(){return po.decode}});Object.defineProperty(M,"decodeMulti",{enumerable:!0,get:function(){return po.decodeMulti}});var xr=ho();Object.defineProperty(M,"decodeAsync",{enumerable:!0,get:function(){return xr.decodeAsync}});Object.defineProperty(M,"decodeArrayStream",{enumerable:!0,get:function(){return xr.decodeArrayStream}});Object.defineProperty(M,"decodeMultiStream",{enumerable:!0,get:function(){return xr.decodeMultiStream}});var Rd=on();Object.defineProperty(M,"Decoder",{enumerable:!0,get:function(){return Rd.Decoder}});var Ld=Zt();Object.defineProperty(M,"DecodeError",{enumerable:!0,get:function(){return Ld.DecodeError}});var jd=fr();Object.defineProperty(M,"Encoder",{enumerable:!0,get:function(){return jd.Encoder}});var Cd=nn();Object.defineProperty(M,"ExtensionCodec",{enumerable:!0,get:function(){return Cd.ExtensionCodec}});var Fd=ir();Object.defineProperty(M,"ExtData",{enumerable:!0,get:function(){return Fd.ExtData}});var je=cr();Object.defineProperty(M,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return je.EXT_TIMESTAMP}});Object.defineProperty(M,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return je.encodeDateToTimeSpec}});Object.defineProperty(M,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return je.encodeTimeSpecToTimestamp}});Object.defineProperty(M,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return je.decodeTimestampToTimeSpec}});Object.defineProperty(M,"encodeTimestampExtension",{enumerable:!0,get:function(){return je.encodeTimestampExtension}});Object.defineProperty(M,"decodeTimestampExtension",{enumerable:!0,get:function(){return je.decodeTimestampExtension}})});var vr=b((Xh,So)=>{"use strict";var z=require("fs"),ee=qi(),{encode:Bd,decode:$d}=go(),Er=["id","content","work_unit","work_type","phase","topic","confidence","source_file","timestamp"];function yo(t){if(!Number.isInteger(t)||t<=0)throw new Error(`createStore: dimensions must be a positive integer, got ${t}`);return{id:"string",content:"string",work_unit:"enum",work_type:"enum",phase:"enum",topic:"enum",confidence:"enum",source_file:"string",timestamp:"number",embedding:`vector[${t}]`}}async function qd(t){let e=yo(t);return ee.create({schema:e})}function zd(t){for(let e of Er)if(t[e]===void 0||t[e]===null)throw new Error(`insertDocument: missing required field "${e}"`);if(typeof t.timestamp!="number"||!Number.isFinite(t.timestamp))throw new Error("insertDocument: timestamp must be a finite number (epoch ms)")}async function Vd(t,e){if(e==null||typeof e!="object")throw new Error("insertDocument: doc must be an object");zd(e);let n={};for(let r of Er)n[r]=e[r];if("embedding"in e){if(e.embedding===null)throw new Error("insertDocument: embedding cannot be null (Orama crashes on null vectors). Omit the field for keyword-only mode, or pass a real vector.");if(e.embedding!==void 0){if(!Array.isArray(e.embedding))throw new Error("insertDocument: embedding must be an array of numbers when present");n.embedding=e.embedding}}return ee.insert(t,n)}async function Wd(t,e){if(!e||!e.work_unit||!e.phase||!e.topic)throw new Error("removeByIdentity: work_unit, phase, and topic are all required");return mo(t,{work_unit:{eq:e.work_unit},phase:{eq:e.phase},topic:{eq:e.topic}})}async function mo(t,e){if(!e||Object.keys(e).length===0)throw new Error("removeByFilter: where clause is required");let r=(await ee.search(t,{term:"",where:e,limit:1e5})).hits.map(i=>i.id);return r.length===0?0:await ee.removeMultiple(t,r)}function Ar(t){let e=t.document||{};return{id:e.id,content:e.content,work_unit:e.work_unit,work_type:e.work_type,phase:e.phase,topic:e.topic,confidence:e.confidence,source_file:e.source_file,timestamp:e.timestamp,score:t.score}}async function Kd(t,{term:e="",where:n,limit:r=10}={}){let s={term:e,limit:r};return n&&Object.keys(n).length>0&&(s.where=n),(await ee.search(t,s)).hits.map(Ar)}async function Hd(t,{vector:e,where:n,limit:r=10,similarity:s}={}){if(!Array.isArray(e))throw new Error("searchVector: vector (number[]) is required");let i={mode:"vector",vector:{value:e,property:"embedding"},limit:r};return typeof s=="number"&&(i.similarity=s),n&&Object.keys(n).length>0&&(i.where=n),(await ee.search(t,i)).hits.map(Ar)}async function Gd(t,{term:e,vector:n,where:r,limit:s=10,textWeight:i=.4,vectorWeight:o=.6,similarity:c}={}){if(typeof e!="string")throw new Error("searchHybrid: term (string) is required");if(!Array.isArray(n))throw new Error("searchHybrid: vector (number[]) is required");let u={mode:"hybrid",term:e,vector:{value:n,property:"embedding"},hybridWeights:{text:i,vector:o},limit:s};return typeof c=="number"&&(u.similarity=c),r&&Object.keys(r).length>0&&(u.where=r),(await ee.search(t,u)).hits.map(Ar)}async function Yd(t,e){if(!e)throw new Error("saveStore: storePath is required");let n=ee.save(t),r={v:1,schema:t.schema,raw:n},s=Bd(r),i=e+".tmp";z.writeFileSync(i,s),z.renameSync(i,e)}async function Jd(t){if(!t)throw new Error("loadStore: storePath is required");if(!z.existsSync(t))throw new Error(`loadStore: store file not found at ${t}`);let e;try{e=z.readFileSync(t)}catch(s){throw new Error(`loadStore: failed to read ${t}: ${s.message}`)}if(e.length===0)throw new Error(`loadStore: store file is empty at ${t}`);let n;try{n=$d(e)}catch(s){throw new Error(`loadStore: corrupted store file at ${t}: ${s.message}`)}if(!n||typeof n!="object"||!n.schema||!n.raw)throw new Error(`loadStore: malformed envelope at ${t}`);let r=await ee.create({schema:n.schema});return ee.load(r,n.raw),r}var Xd=3e4,Zd=50,Qd=1e4;function ef(t){try{let e=z.openSync(t,"wx");return z.writeSync(e,String(process.pid)),z.closeSync(e),!0}catch(e){if(e.code!=="EEXIST")throw e;return!1}}function tf(t){return new Promise(e=>setTimeout(e,t))}async function wo(t){let e=Date.now()+Qd;for(;;){if(ef(t))return;try{let n=z.statSync(t);if(Date.now()-n.mtimeMs>Xd){try{z.unlinkSync(t)}catch{}continue}}catch{continue}if(Date.now()>=e)throw new Error(`knowledge store: timed out waiting for lock at ${t}. If no other process is running, delete the file manually.`);await tf(Zd)}}function _o(t){try{z.unlinkSync(t)}catch{}}async function nf(t,e){await wo(t);try{return await e()}finally{_o(t)}}var rf=["provider","model","dimensions","last_indexed","pending"];function sf(t,e){if(!t)throw new Error("writeMetadata: metadataPath is required");if(e==null||typeof e!="object")throw new Error("writeMetadata: data must be an object");let n={provider:e.provider===void 0?null:e.provider,model:e.model===void 0?null:e.model,dimensions:e.dimensions===void 0?null:e.dimensions,last_indexed:e.last_indexed===void 0?null:e.last_indexed,pending:Array.isArray(e.pending)?e.pending:[]},r=t+".tmp";z.writeFileSync(r,JSON.stringify(n,null,2)+` +`,"utf8"),z.renameSync(r,t)}function of(t){if(!t)throw new Error("readMetadata: metadataPath is required");if(!z.existsSync(t))throw new Error(`readMetadata: metadata file not found at ${t}`);let e;try{e=z.readFileSync(t,"utf8")}catch(r){throw new Error(`readMetadata: failed to read ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`readMetadata: invalid JSON at ${t}: ${r.message}`)}return n}So.exports={SCHEMA_FIELDS:Er,METADATA_FIELDS:rf,buildSchema:yo,createStore:qd,insertDocument:Vd,removeByIdentity:Wd,removeByFilter:mo,searchFulltext:Kd,searchVector:Hd,searchHybrid:Gd,saveStore:Yd,loadStore:Jd,acquireLock:wo,releaseLock:_o,withLock:nf,writeMetadata:sf,readMetadata:of}});var Ao=b((Zh,Eo)=>{"use strict";var cf=/^\s*(```+|~~~+)/,bo=/^---\s*$/;function uf(t,e){if(typeof t!="string")throw new TypeError("chunk: markdown must be a string");if(!e||typeof e!="object")throw new TypeError("chunk: config must be an object");let{primary_level:n=2,fallback_level:r=3,max_lines:s=200,keep_whole_below:i=50,special_sections:o={},strip_frontmatter:c=!0,skip_empty_sections:u=!0}=e,a=t.replace(/\r\n/g,` `).replace(/\r/g,` -`),l=c?tf(a):a;if(l.trim()==="")return[];let d=l.split(` -`);if(d.length_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:me(l)}];let h=nf(d,f,y),m=rf(h,d,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=me(d.slice(_.startLine,_.endLine+1).join(` -`)),v={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&_o(v))continue;let D=I.split(` -`);if(_.action==="regular"&&D.length>s){let A=sf(v,r);for(let k of A)u&&_o(k)||S.push({content:k.text})}else S.push({content:I})}return S}function me(t){return t.replace(/\s+$/,"")}function tf(t){let e=t.split(` -`);if(e.length===0||!wo.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let l=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),d=o.startLine,f=!0;for(let p of l)p.startLine>d&&(i.push({action:"regular",startLine:d,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),d=p.endLine+1;d<=o.endLine&&i.push({action:"regular",startLine:d,endLine:o.endLine,heading:"",headingLine:""})}return i}function sf(t,e){let n=t.text.split(` -`),s=So(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=me(c.join(` -`));u.trim()!==""&&i.push({heading:t.heading,headingLine:t.headingLine,text:u})}for(let c=0;c_.level===n),g=f.some(_=>_.level===r),y;if(p)y=n;else if(g)y=r;else return[{content:we(l)}];let h=lf(d,f,y),m=df(h,d,y,o,f),w=[];for(let _ of m)if(_.action!=="skip"){if(_.action==="merge-up"){if(w.length===0)w.push({action:"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine});else{let I=w[w.length-1];I.endLine=_.endLine}continue}w.push({action:_.action||"regular",startLine:_.startLine,endLine:_.endLine,heading:_.heading,headingLine:_.headingLine})}let S=[];for(let _ of w){let I=we(d.slice(_.startLine,_.endLine+1).join(` +`)),v={heading:_.heading,headingLine:_.headingLine,text:I};if(u&&Io(v))continue;let D=I.split(` +`);if(_.action==="regular"&&D.length>s){let A=ff(v,r);for(let k of A)u&&Io(k)||S.push({content:k.text})}else S.push({content:I})}return S}function we(t){return t.replace(/\s+$/,"")}function af(t){let e=t.split(` +`);if(e.length===0||!bo.test(e[0]||""))return t;for(let n=1;no.level===n).map(o=>o.line),s=[],i=r.length>0?r[0]:t.length;if(i>0){let o=t.slice(0,i),c=e.find(a=>a.level===1&&a.line{if(p.line<=o.startLine||p.line>o.endLine||p.level===1||p.level===n)return!1;let g=r[p.text];return g==="own-chunk"||g==="skip"});if(a.length===0){i.push({action:"regular",startLine:o.startLine,endLine:o.endLine,heading:o.heading,headingLine:o.headingLine});continue}let l=a.map(p=>{let g=o.endLine;for(let y of s)if(!(y.line<=p.line)){if(y.line>o.endLine)break;if(y.level<=p.level){g=y.line-1;break}}return{action:r[p.text],startLine:p.line,endLine:g,heading:p.text,headingLine:e[p.line]}}),d=o.startLine,f=!0;for(let p of l)p.startLine>d&&(i.push({action:"regular",startLine:d,endLine:p.startLine-1,heading:f?o.heading:"",headingLine:f?o.headingLine:""}),f=!1),i.push({action:p.action,startLine:p.startLine,endLine:p.endLine,heading:p.heading,headingLine:p.headingLine}),d=p.endLine+1;d<=o.endLine&&i.push({action:"regular",startLine:d,endLine:o.endLine,heading:"",headingLine:""})}return i}function ff(t,e){let n=t.text.split(` +`),s=xo(n).filter(c=>c.level===e).map(c=>c.line);if(s.length===0)return[t];let i=[],o=s[0];if(o>0){let c=n.slice(0,o),u=we(c.join(` +`));u.trim()!==""&&i.push({heading:t.heading,headingLine:t.headingLine,text:u})}for(let c=0;c{"use strict";var xo="stub";function of(t){let e=2166136261;for(let n=0;n>>0}function cf(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var Er=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=of(n)||1,s=cf(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var Ao="text-embedding-3-small",vo="https://api.openai.com/v1/embeddings",vr=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||Ao,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var je=require("fs"),Mr=require("path"),uf=require("os"),{StubProvider:af}=Ar(),{OpenAIProvider:lf}=un(),Do={similarity_threshold:.8,decay_months:6},Tr=["stub","openai"];function Mo(){return Mr.join(uf.homedir(),".config","workflows","config.json")}function Oo(t){return Mr.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Dr(t){if(!je.existsSync(t))return null;let e;try{e=je.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function df(t){let e=t&&t.systemPath||Mo(),n=t&&t.projectPath||Oo(),r=Dr(e),s=Dr(n),i=Object.assign({},Do);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);if(i.api_key_env){let o=process.env[i.api_key_env];i._api_key=o&&o.trim()!==""?o:null}else i._api_key=null;return i}function ff(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new af(n!=null?{dimensions:n}:void 0)}if(!Tr.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${Tr.join(", ")}`);return t._api_key&&e==="openai"?new lf({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}function hf(t,e){if(!t)throw new Error("writeConfigFile: filePath is required");if(e==null||typeof e!="object"||!e.knowledge)throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key');let n=Mr.dirname(t);je.existsSync(n)||je.mkdirSync(n,{recursive:!0});let r=t+".tmp";je.writeFileSync(r,JSON.stringify(e,null,2)+` -`,"utf8"),je.renameSync(r,t)}Po.exports={DEFAULTS:Do,AVAILABLE_PROVIDERS:Tr,systemConfigPath:Mo,projectConfigPath:Oo,readConfigFile:Dr,loadConfig:df,resolveProvider:ff,writeConfigFile:hf}});var Go=b((Gh,Ho)=>{"use strict";var we=require("fs"),_e=require("path"),pf=require("readline"),Y=Or(),Pr=xr(),{OpenAIProvider:gf}=un(),ko="text-embedding-3-small",No=1536,Uo="OPENAI_API_KEY",Lo=1536;function Ro(){process.stdin.isTTY||(process.stderr.write(`knowledge setup requires an interactive terminal. Run it directly, not through Claude or a pipe. -`),process.exit(1))}function jo(){let t=pf.createInterface({input:process.stdin,output:process.stdout});return t.on("SIGINT",()=>{process.stderr.write(` +`).trim()===""}Eo.exports={chunk:uf}});var Dr=b((Qh,To)=>{"use strict";var vo="stub";function hf(t){let e=2166136261;for(let n=0;n>>0}function pf(t){let e=t>>>0;return function(){e=e+1831565813>>>0;let r=e;return r=Math.imul(r^r>>>15,r|1),r^=r+Math.imul(r^r>>>7,r|61),((r^r>>>14)>>>0)/4294967296}}var Tr=class{constructor(e){let n=e&&typeof e.dimensions=="number"?e.dimensions:128;if(!Number.isInteger(n)||n<=0)throw new Error(`StubProvider: dimensions must be a positive integer, got ${n}`);this._dimensions=n}embed(e){let n=typeof e=="string"?e:String(e??""),r=hf(n)||1,s=pf(r),i=new Array(this._dimensions);for(let o=0;o{"use strict";var Do="text-embedding-3-small",Mo="https://api.openai.com/v1/embeddings",Mr=class{constructor(e){if(!e||!e.apiKey)throw new Error("OpenAIProvider: apiKey is required");this._apiKey=e.apiKey,this._model=e.model||Do,this._dimensions=typeof e.dimensions=="number"?e.dimensions:1536}async embed(e){let n=JSON.stringify({model:this._model,input:typeof e=="string"?e:String(e??""),dimensions:this._dimensions});return(await this._fetch(n)).data[0].embedding}async embedBatch(e){if(!Array.isArray(e))throw new Error("OpenAIProvider.embedBatch: texts must be an array");if(e.length===0)return[];if(e.length<=2048){let r=JSON.stringify({model:this._model,input:e,dimensions:this._dimensions});return(await this._fetch(r)).data.sort((o,c)=>o.index-c.index).map(o=>o.embedding)}let n=new Array(e.length);for(let r=0;ru.index-a.index);for(let u=0;u{"use strict";var B=require("fs"),it=require("path"),Po=require("os"),{StubProvider:gf}=Dr(),{OpenAIProvider:yf}=un(),ko={similarity_threshold:.8,decay_months:6},Or=["stub","openai"],No={openai:"OPENAI_API_KEY"};function Uo(){return it.join(Po.homedir(),".config","workflows","config.json")}function Ro(t){return it.join(t||process.cwd(),".workflows",".knowledge","config.json")}function Lo(){return it.join(Po.homedir(),".config","workflows","credentials.json")}function Pr(t){if(!B.existsSync(t))return null;let e;try{e=B.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read config file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in config file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.knowledge)throw new Error(`Config file at ${t} is missing the required top-level "knowledge" key. Expected format: { "knowledge": { ... } }`);if(typeof n.knowledge!="object"||Array.isArray(n.knowledge))throw new Error(`Config file at ${t}: the "knowledge" key must be an object.`);return n.knowledge}function kr(t){if(!B.existsSync(t))return null;let e;try{e=B.readFileSync(t,"utf8")}catch(r){throw new Error(`Failed to read credentials file at ${t}: ${r.message}`)}let n;try{n=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON in credentials file at ${t}: ${r.message}`)}if(n==null||typeof n!="object"||!n.credentials||typeof n.credentials!="object"||Array.isArray(n.credentials))throw new Error(`Credentials file at ${t} is missing the required top-level "credentials" object. Expected format: { "credentials": { "": { "api_key": "..." } } }`);return n.credentials}function mf(t,e,n){if(!t)throw new Error("writeCredentials: filePath is required");if(!e||typeof e!="string")throw new Error("writeCredentials: provider name is required");let r={};if(B.existsSync(t))try{r=kr(t)||{}}catch{r={}}let s=Object.assign({},r);n==null?delete s[e]:s[e]=Object.assign({},s[e]||{},{api_key:n});let i={credentials:s},o=it.dirname(t);B.existsSync(o)||B.mkdirSync(o,{recursive:!0});let c=t+".tmp",u=B.openSync(c,"w",384);try{B.writeSync(u,JSON.stringify(i,null,2)+` +`)}finally{B.closeSync(u)}B.chmodSync(c,384),B.renameSync(c,t);try{B.chmodSync(t,384)}catch{}}function jo(t,e){if(!t)return null;let n=No[t];if(n){let i=process.env[n];if(i&&i.trim()!=="")return i}let r=e&&e.credentialsPath||Lo(),s;try{s=kr(r)}catch{return null}if(s&&s[t]&&typeof s[t].api_key=="string"){let i=s[t].api_key.trim();if(i!=="")return i}return null}function wf(t){let e=t&&t.systemPath||Uo(),n=t&&t.projectPath||Ro(),r=Pr(e),s=Pr(n),i=Object.assign({},ko);if(r)for(let o of Object.keys(r))r[o]!==void 0&&(i[o]=r[o]);if(s)for(let o of Object.keys(s))s[o]!==void 0&&(i[o]=s[o]);return i._api_key=jo(i.provider,{credentialsPath:t&&t.credentialsPath}),i}function _f(t){if(!t||typeof t!="object")throw new Error("resolveProvider: config is required");let e=t.provider;if(!e)return null;if(e==="stub"){let n=t.dimensions||void 0;return new gf(n!=null?{dimensions:n}:void 0)}if(!Or.includes(e))throw new Error(`Provider "${e}" is not available. Available providers: ${Or.join(", ")}`);return t._api_key&&e==="openai"?new yf({apiKey:t._api_key,model:t.model||void 0,dimensions:t.dimensions||void 0}):null}function Sf(t,e){if(!t)throw new Error("writeConfigFile: filePath is required");if(e==null||typeof e!="object"||!e.knowledge)throw new Error('writeConfigFile: payload must be an object with a top-level "knowledge" key');let n=it.dirname(t);B.existsSync(n)||B.mkdirSync(n,{recursive:!0});let r=t+".tmp";B.writeFileSync(r,JSON.stringify(e,null,2)+` +`,"utf8"),B.renameSync(r,t)}Co.exports={DEFAULTS:ko,AVAILABLE_PROVIDERS:Or,PROVIDER_ENV_VARS:No,systemConfigPath:Uo,projectConfigPath:Ro,credentialsPath:Lo,readConfigFile:Pr,loadConfig:wf,loadCredentials:kr,writeCredentials:mf,resolveApiKey:jo,resolveProvider:_f,writeConfigFile:Sf}});var tc=b((np,ec)=>{"use strict";var _e=require("fs"),Se=require("path"),bf=require("readline"),$=Nr(),Ur=vr(),{OpenAIProvider:If}=un(),Fo="text-embedding-3-small",Bo=1536,$o=1536;function qo(){process.stdin.isTTY||(process.stderr.write(`knowledge setup requires an interactive terminal. Run it directly, not through Claude or a pipe. +`),process.exit(1))}function zo(){let t=bf.createInterface({input:process.stdin,output:process.stdout});return t.on("SIGINT",()=>{process.stderr.write(` Setup cancelled. -`),t.close(),process.exit(130)}),t}function st(t,e,n){let r=n!=null&&n!==""?` [${n}]`:"";return new Promise(s=>{t.question(`${e}${r}: `,i=>{let o=(i||"").trim();s(o===""&&n!==void 0&&n!==null?String(n):o)})})}async function it(t,e,n){let r=n?"Y/n":"y/N";return new Promise(s=>{t.question(`${e} (${r}): `,i=>{let o=(i||"").trim().toLowerCase();if(o==="")return s(!!n);s(o==="y"||o==="yes")})})}function Fo({model:t,dimensions:e,apiKeyEnv:n}){return{knowledge:{provider:"openai",model:t,dimensions:e,api_key_env:n,similarity_threshold:Y.DEFAULTS.similarity_threshold,decay_months:Y.DEFAULTS.decay_months}}}function Co(){return{knowledge:{similarity_threshold:Y.DEFAULTS.similarity_threshold,decay_months:Y.DEFAULTS.decay_months}}}function Bo(){return{knowledge:{}}}function qo(t){if(!we.existsSync(t))return{exists:!1,valid:!1,knowledge:null};try{let e=we.readFileSync(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||!n.knowledge||typeof n.knowledge!="object"||Array.isArray(n.knowledge)?{exists:!0,valid:!1,knowledge:null,reason:'missing or invalid "knowledge" key'}:{exists:!0,valid:!0,knowledge:n.knowledge}}catch(e){return{exists:!0,valid:!1,knowledge:null,reason:e.message}}}function $o(t){let e=_e.join(t,"config.json"),n=_e.join(t,"store.msp"),r=_e.join(t,"metadata.json"),s=we.existsSync(t),i=we.existsSync(e),o=we.existsSync(n),c=we.existsSync(r);return{dirExists:s,configExists:i,storeExists:o,metadataExists:c,fullyInitialised:i&&o&&c,partiallyInitialised:s&&!(i&&o&&c)}}async function zo({apiKey:t,model:e,dimensions:n}){let s=await new gf({apiKey:t,model:e,dimensions:n}).embed("knowledge base setup test");if(!Array.isArray(s)||s.length!==n)throw new Error(`Expected a vector of length ${n}, got ${Array.isArray(s)?s.length:typeof s}`);return!0}async function Vo(t){let e=Y.systemConfigPath(),n=qo(e);if(n.exists&&n.valid){process.stdout.write(` +`),t.close(),process.exit(130)}),t}function an(t,e,n){let r=n!=null&&n!==""?` [${n}]`:"";return new Promise(s=>{t.question(`${e}${r}: `,i=>{let o=(i||"").trim();s(o===""&&n!==void 0&&n!==null?String(n):o)})})}async function Ce(t,e,n){let r=n?"Y/n":"y/N";return new Promise(s=>{t.question(`${e} (${r}): `,i=>{let o=(i||"").trim().toLowerCase();if(o==="")return s(!!n);s(o==="y"||o==="yes")})})}function Vo(t,e){return new Promise(n=>{let r=process.stdin,s=process.stdout;if(!r.isTTY||typeof r.setRawMode!="function"){t.question(e,a=>n((a||"").trim()));return}s.write(e),t.pause();let i=r.isRaw===!0;r.setRawMode(!0),r.resume(),r.setEncoding("utf8");let o="",c=()=>{r.removeListener("data",u);try{r.setRawMode(i)}catch{}r.pause(),t.resume()},u=a=>{for(let l of a.toString("utf8")){if(l===` +`||l==="\r")return c(),s.write(` +`),n(o.trim());if(l===""){c(),s.write(` +`),process.exit(130);return}if(l==="")return c(),s.write(` +`),n(o.trim());if(l==="\x7F"||l==="\b"){o.length>0&&(o=o.slice(0,-1),s.write("\b \b"));continue}l<" "||(o+=l,s.write("*"))}};r.on("data",u)})}function Wo({model:t,dimensions:e}){return{knowledge:{provider:"openai",model:t,dimensions:e,similarity_threshold:$.DEFAULTS.similarity_threshold,decay_months:$.DEFAULTS.decay_months}}}function Ko(){return{knowledge:{similarity_threshold:$.DEFAULTS.similarity_threshold,decay_months:$.DEFAULTS.decay_months}}}function Ho(){return{knowledge:{}}}function Go(t){if(!_e.existsSync(t))return{exists:!1,valid:!1,knowledge:null};try{let e=_e.readFileSync(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||!n.knowledge||typeof n.knowledge!="object"||Array.isArray(n.knowledge)?{exists:!0,valid:!1,knowledge:null,reason:'missing or invalid "knowledge" key'}:{exists:!0,valid:!0,knowledge:n.knowledge}}catch(e){return{exists:!0,valid:!1,knowledge:null,reason:e.message}}}function Yo(t){let e=Se.join(t,"config.json"),n=Se.join(t,"store.msp"),r=Se.join(t,"metadata.json"),s=_e.existsSync(t),i=_e.existsSync(e),o=_e.existsSync(n),c=_e.existsSync(r);return{dirExists:s,configExists:i,storeExists:o,metadataExists:c,fullyInitialised:i&&o&&c,partiallyInitialised:s&&!(i&&o&&c)}}async function ln({apiKey:t,model:e,dimensions:n}){let s=await new If({apiKey:t,model:e,dimensions:n}).embed("knowledge base setup test");if(!Array.isArray(s)||s.length!==n)throw new Error(`Expected a vector of length ${n}, got ${Array.isArray(s)?s.length:typeof s}`);return!0}function dn(t){let e=t&&t.message||String(t);return/401/.test(e)||/invalid or expired/i.test(e)?{message:"The API key was rejected (HTTP 401).",hint:"Check that the key is active and not revoked. Free-tier keys also need billing enabled for /v1/embeddings. Create a fresh key at https://platform.openai.com/api-keys and try again."}:/403/.test(e)||/permission/i.test(e)?{message:"The API key does not have permission for embeddings (HTTP 403).",hint:"If this is a restricted key, check its allowed endpoints in the OpenAI dashboard. Create a key with Embeddings access enabled."}:/429/.test(e)||/rate limit/i.test(e)?{message:"Rate limit hit during validation (HTTP 429).",hint:"Your account may be out of quota, or the default rate limit is saturated. Wait a moment and retry, or check billing at https://platform.openai.com/account."}:/network error/i.test(e)||/ENOTFOUND/.test(e)||/ECONN/.test(e)||/ETIMEDOUT/.test(e)?{message:"Could not reach OpenAI (network error).",hint:"Check your internet connection, VPN, or corporate proxy. No key was written \u2014 you can re-run `knowledge setup` once the connection is stable."}:/HTTP 5\d\d/.test(e)?{message:"OpenAI returned a server error during validation.",hint:"Transient on their side. Retry in a minute."}:{message:"API key validation failed.",hint:`Error detail: ${e}`}}async function Jo(t){let e=$.systemConfigPath(),n=Go(e);if(n.exists&&n.valid){process.stdout.write(` System config already exists at ${e} `),process.stdout.write(` Current settings: -`);let l=n.knowledge;if(process.stdout.write(` provider: ${l.provider==null?"(none \u2014 stub mode)":l.provider} -`),l.model&&process.stdout.write(` model: ${l.model} -`),l.dimensions&&process.stdout.write(` dimensions: ${l.dimensions} -`),l.api_key_env&&process.stdout.write(` api_key_env: ${l.api_key_env} +`);let a=n.knowledge;if(process.stdout.write(` provider: ${a.provider==null?"(none \u2014 stub mode)":a.provider} +`),a.model&&process.stdout.write(` model: ${a.model} +`),a.dimensions&&process.stdout.write(` dimensions: ${a.dimensions} `),process.stdout.write(` -`),!await it(t,"Reconfigure system settings?",!1))return process.stdout.write(`Keeping existing system config. -`),{provider:l.provider||null,previouslyStub:!l.provider}}else n.exists&&!n.valid?(process.stdout.write(` +`),!await Ce(t,"Reconfigure system settings?",!1))return process.stdout.write(`Keeping existing system config. +`),{provider:a.provider||null,previouslyStub:!a.provider}}else n.exists&&!n.valid?(process.stdout.write(` System config at ${e} is not valid: ${n.reason} -`),await it(t,"Overwrite it?",!0)||(process.stdout.write(`Aborting setup so you can fix the file manually. +`),await Ce(t,"Overwrite it?",!0)||(process.stdout.write(`Aborting setup so you can fix the file manually. `),process.exit(1))):process.stdout.write(` No system config found at ${e}. Creating a new one. `);let r=n.exists&&n.valid&&!n.knowledge.provider;process.stdout.write(` @@ -46,47 +50,77 @@ Embedding provider: `),process.stdout.write(` openai \u2014 OpenAI embeddings API (requires an API key) `),process.stdout.write(` skip \u2014 Stub mode (keyword-only search, no embeddings) -`);let s;for(;s=(await st(t,"Provider (openai / skip)","openai")).toLowerCase(),!(s==="openai"||s==="skip");)process.stdout.write(`Unknown choice "${s}". Enter "openai" or "skip". -`);if(s==="skip")return Y.writeConfigFile(e,Co()),process.stdout.write(` +`);let s;for(;s=(await an(t,"Provider (openai / skip)","openai")).toLowerCase(),!(s==="openai"||s==="skip");)process.stdout.write(`Unknown choice "${s}". Enter "openai" or "skip". +`);if(s==="skip")return $.writeConfigFile(e,Ko()),process.stdout.write(` Wrote stub-mode system config to ${e} -`),process.stdout.write("Stub mode uses keyword-only (BM25) search. Semantic search is disabled. Run `knowledge setup` again later to configure a provider.\n"),{provider:null,previouslyStub:r};let i=await st(t,"Embedding model",ko),o=await st(t,"Vector dimensions",String(No)),c=parseInt(o,10);(!Number.isInteger(c)||c<=0)&&(process.stderr.write(`Invalid dimensions: "${o}". Must be a positive integer. -`),process.exit(1));let u=await st(t,"API key environment variable",Uo),a=process.env[u];if(a&&a.trim()!==""){process.stdout.write(` -Validating API key via a test embed... -`);try{await zo({apiKey:a.trim(),model:i,dimensions:c}),process.stdout.write(`API key works. -`)}catch(l){process.stdout.write(`API key validation failed: ${l.message} -`),await it(t,"Continue anyway (you can fix the key later)?",!0)||(process.stdout.write(`Aborting setup. -`),process.exit(1))}}else process.stdout.write(` -Environment variable ${u} is not set. Set it in your shell profile (e.g., ~/.zshrc) before using the knowledge base: - export ${u}="sk-..." -Setup will continue \u2014 the key is only needed at query/index time. -`);return Y.writeConfigFile(e,Fo({model:i,dimensions:c,apiKeyEnv:u})),process.stdout.write(` +`),process.stdout.write("Stub mode uses keyword-only (BM25) search. Semantic search is disabled. Run `knowledge setup` again later to configure a provider.\n"),{provider:null,previouslyStub:r};let i=await an(t,"Embedding model",Fo),o=await an(t,"Vector dimensions",String(Bo)),c=parseInt(o,10);(!Number.isInteger(c)||c<=0)&&(process.stderr.write(`Invalid dimensions: "${o}". Must be a positive integer. +`),process.exit(1)),$.writeConfigFile(e,Wo({model:i,dimensions:c})),process.stdout.write(` Wrote system config to ${e} -`),{provider:"openai",previouslyStub:r}}async function Wo(t){let e=_e.resolve(process.cwd(),".workflows",".knowledge"),n=_e.join(e,"config.json"),r=_e.join(e,"store.msp"),s=_e.join(e,"metadata.json"),i=$o(e);if(i.fullyInitialised){if(process.stdout.write(` +`);let u=$.PROVIDER_ENV_VARS.openai;return await Xo(t,{envVar:u,model:i,dimensions:c}),{provider:"openai",previouslyStub:r}}async function Xo(t,{envVar:e,model:n,dimensions:r}){let s=$.credentialsPath(),i=process.env[e];if(i&&i.trim()!==""){process.stdout.write(` +Using API key from $${e} \u2014 validating via a test embed... +`);try{await ln({apiKey:i.trim(),model:n,dimensions:r}),process.stdout.write(`API key works. +`)}catch(c){let{message:u,hint:a}=dn(c);process.stdout.write(`${u} + ${a} +`),process.stdout.write(`The failing key came from $${e}. Fix or unset it in your shell, then re-run \`knowledge setup\`. Setup will continue \u2014 indexing will queue until the key is corrected. +`)}return}let o=$.resolveApiKey("openai",{credentialsPath:s});if(o){process.stdout.write(` +Found an existing API key in ${s} \u2014 validating via a test embed... +`);try{await ln({apiKey:o,model:n,dimensions:r}),process.stdout.write(`API key works. +`);return}catch(c){let{message:u,hint:a}=dn(c);if(process.stdout.write(`${u} + ${a} +`),!await Ce(t,"Enter a new key to replace it?",!0)){process.stdout.write(`Keeping the existing stored key. Indexing will fail until it is rotated. +Edit ${s} or re-run \`knowledge setup\` when you have a new key. +`);return}}}await xf(t,{envVar:e,model:n,dimensions:r,credPath:s})}async function xf(t,{envVar:e,model:n,dimensions:r,credPath:s}){for(process.stdout.write(` +OpenAI API Key +-------------- +Semantic search in the knowledge base relies on OpenAI embeddings. +We recommend creating a dedicated key for this tool so you can rotate +or revoke it independently from other integrations. + + 1. Create a key: https://platform.openai.com/api-keys + (Suggested name: "agentic-workflows") + 2. Paste the full key (starting with "sk-") at the prompt below. + +Your key will be stored at: + ${s} (mode 0600, user-private) +Setting $${e} in your shell takes precedence and overrides the +stored key, so you can swap it without editing the file. + +`);;){let i=await Vo(t,"API key (input hidden): ");if(i===""){process.stdout.write(`Empty input \u2014 enter the key, or Ctrl-C to abort setup. + +`);continue}process.stdout.write(` +Validating via a test embed... +`);try{await ln({apiKey:i,model:n,dimensions:r})}catch(o){let{message:c,hint:u}=dn(o);if(process.stdout.write(`${c} + ${u} + +`),!await Ce(t,"Try a different key?",!0)){process.stdout.write(`No key stored. Setup continues but indexing will skip until a key is provided. +Set $${e} in your shell or re-run \`knowledge setup\`. +`);return}continue}$.writeCredentials(s,"openai",i),process.stdout.write(`API key works. Stored at ${s} (mode 0600). +`);return}}async function Zo(t){let e=Se.resolve(process.cwd(),".workflows",".knowledge"),n=Se.join(e,"config.json"),r=Se.join(e,"store.msp"),s=Se.join(e,"metadata.json"),i=Yo(e);if(i.fullyInitialised){if(process.stdout.write(` Project knowledge base already initialised at ${e} -`),!await it(t,"Reinitialise (destroys existing store)?",!1))return process.stdout.write(`Keeping existing project files. +`),!await Ce(t,"Reinitialise (destroys existing store)?",!1))return process.stdout.write(`Keeping existing project files. `),{created:!1}}else i.partiallyInitialised?(process.stdout.write(` Project knowledge base partially initialised at ${e} `),process.stdout.write(` Missing files will be created. `)):process.stdout.write(` Initialising project knowledge base at ${e} -`);we.mkdirSync(e,{recursive:!0}),(!i.configExists||i.fullyInitialised)&&(Y.writeConfigFile(n,Bo()),process.stdout.write(` config.json written -`));let o=Y.loadConfig(),c=o.provider||null,u=Number.isInteger(o.dimensions)&&o.dimensions>0?o.dimensions:Lo;if(!i.storeExists||i.fullyInitialised){let a=await Pr.createStore(u);await Pr.saveStore(a,r),process.stdout.write(` store.msp written (${u} dimensions) -`)}return(!i.metadataExists||i.fullyInitialised)&&(Pr.writeMetadata(s,{provider:c||null,model:c&&o.model?o.model:null,dimensions:c?u:null,last_indexed:null,pending:[]}),process.stdout.write(` metadata.json written -`)),{created:!0,provider:c,dimensions:u}}async function Ko(t,e){let n=Y.loadConfig(),r=Y.resolveProvider(n);process.stdout.write(` +`);_e.mkdirSync(e,{recursive:!0}),(!i.configExists||i.fullyInitialised)&&($.writeConfigFile(n,Ho()),process.stdout.write(` config.json written +`));let o=$.loadConfig(),c=o.provider||null,u=Number.isInteger(o.dimensions)&&o.dimensions>0?o.dimensions:$o;if(!i.storeExists||i.fullyInitialised){let a=await Ur.createStore(u);await Ur.saveStore(a,r),process.stdout.write(` store.msp written (${u} dimensions) +`)}return(!i.metadataExists||i.fullyInitialised)&&(Ur.writeMetadata(s,{provider:c||null,model:c&&o.model?o.model:null,dimensions:c?u:null,last_indexed:null,pending:[]}),process.stdout.write(` metadata.json written +`)),{created:!0,provider:c,dimensions:u}}async function Qo(t,e){let n=$.loadConfig(),r=$.resolveProvider(n);process.stdout.write(` Initial indexing `),process.stdout.write(`---------------- `);try{await t(e||{},n,r)}catch(s){process.stderr.write(` Initial indexing hit an error: ${s.message} Project is initialised; run \`knowledge index\` later to retry. -`)}}async function yf(t,e,n){Ro();let r=_e.resolve(process.cwd(),".workflows");we.existsSync(r)||(process.stderr.write(`No .workflows/ directory found. Initialise a workflow project first. -`),process.exit(1));let s=jo(),i;try{process.stdout.write(` +`)}}async function Ef(t,e,n){qo();let r=Se.resolve(process.cwd(),".workflows");_e.existsSync(r)||(process.stderr.write(`No .workflows/ directory found. Initialise a workflow project first. +`),process.exit(1));let s=zo(),i;try{process.stdout.write(` Knowledge base setup `),process.stdout.write(`==================== -`),i=await Vo(s),await Wo(s)}finally{s.close()}await Ko(t,n),process.stdout.write(` +`),i=await Jo(s),await Zo(s)}finally{s.close()}await Qo(t,n),process.stdout.write(` Setup complete. `),i.provider?i.previouslyStub&&process.stdout.write("\nUpgraded from stub mode to a configured provider. The existing store was indexed in keyword-only mode \u2014 run `knowledge rebuild` to re-index with embeddings for full hybrid search.\n"):process.stdout.write(` Stub mode: no embedding provider configured. The knowledge base will run in keyword-only (BM25) mode. Semantic search is disabled until you configure a provider. -`)}Ho.exports={cmdSetup:yf,requireTTY:Ro,createPrompter:jo,ask:st,askYesNo:it,buildSystemConfigOpenAI:Fo,buildSystemConfigStub:Co,buildProjectConfigEmpty:Bo,detectSystemConfig:qo,detectProjectInit:$o,validateApiKey:zo,runSystemConfigStep:Vo,runProjectInitStep:Wo,runInitialIndexStep:Ko,KEYWORD_ONLY_DIMENSIONS:Lo,OPENAI_DEFAULT_MODEL:ko,OPENAI_DEFAULT_DIMENSIONS:No,OPENAI_DEFAULT_ENV_VAR:Uo}});var T=require("fs"),B=require("path"),E=xr(),Xo=Io(),{StubProvider:mf}=Ar(),{OpenAIProvider:wf}=un(),Fe=Or(),Zo=Go(),Nr=["research","discussion","investigation","specification"],_f=T.existsSync(B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?B.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):B.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),ct=[1e3,2e3,4e3],Sf=5,Ur=1536;function Qo(t){let e=[],n={},r=0;for(;r [options] +`)}ec.exports={cmdSetup:Ef,requireTTY:qo,createPrompter:zo,ask:an,askYesNo:Ce,askSecret:Vo,buildSystemConfigOpenAI:Wo,buildSystemConfigStub:Ko,buildProjectConfigEmpty:Ho,detectSystemConfig:Go,detectProjectInit:Yo,validateApiKey:ln,describeValidationError:dn,ensureOpenAIKey:Xo,runSystemConfigStep:Jo,runProjectInitStep:Zo,runInitialIndexStep:Qo,KEYWORD_ONLY_DIMENSIONS:$o,OPENAI_DEFAULT_MODEL:Fo,OPENAI_DEFAULT_DIMENSIONS:Bo}});var T=require("fs"),q=require("path"),E=vr(),sc=Ao(),{StubProvider:Af}=Dr(),{OpenAIProvider:vf}=un(),Fe=Nr(),ic=tc(),Lr=["research","discussion","investigation","specification"],Tf=T.existsSync(q.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"))?q.join(__dirname,"..","..","skills","workflow-manifest","scripts","manifest.cjs"):q.join(__dirname,"..","..","workflow-manifest","scripts","manifest.cjs"),ct=[1e3,2e3,4e3],Df=5,jr=1536;function oc(t){let e=[],n={},r=0;for(;r [options] Commands: index Index a file or all pending artifacts @@ -104,56 +138,56 @@ Options: --phase Filter by phase --topic Filter by topic --limit Limit number of results - --dry-run Preview without making changes`;function oe(){return B.resolve(process.cwd(),".workflows",".knowledge")}function ce(){return B.join(oe(),"store.msp")}function Se(){return B.join(oe(),"metadata.json")}function ve(){return B.join(oe(),".lock")}function bf(t){return new Promise(e=>setTimeout(e,t))}async function ut(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||ct,s;for(let i=0;isetTimeout(e,t))}async function ut(t,e){let n=e&&e.maxAttempts||3,r=e&&e.backoff||ct,s;for(let i=0;iRr(s,o,n,r),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexed ${c} chunks from ${s} -`),await rc(n,r,Sf)}async function Rr(t,e,n,r){let s=If(e.workUnit),i=B.join(__dirname,"..","chunking",e.phase+".json");if(!T.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(T.readFileSync(i,"utf8")),c=B.resolve(t),u=T.readFileSync(c,"utf8"),a=Xo.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let l=oe(),d=ce(),f=Se(),p=ve();T.existsSync(l)||T.mkdirSync(l,{recursive:!0});let g,y,h=T.existsSync(d),m=T.existsSync(f);h&&(g=await E.loadStore(d)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=tc(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||Ur;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),v=o.confidence||"medium",D=a.map((A,k)=>{let Te=String(k+1).padStart(3,"0"),J={id:`${e.workUnit}-${e.phase}-${e.topic}-${Te}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:v,source_file:t,timestamp:I};return _&&(J.embedding=_[k]),J});return await E.withLock(p,async()=>{h?g=await E.loadStore(d):T.existsSync(d)&&(g=await E.loadStore(d)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,d);let A=T.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function ot(t){let{execFileSync:e}=require("child_process");return e("node",[_f,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function nc(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function jr(){let t=[],e;try{let n=ot(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of Nr){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=ot(["resolve",`${r}.${s}.${o}`]).trim();a&&T.existsSync(B.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function an(t,e,n){let r=jr(),s=oe(),i=ce();T.existsSync(s)||T.mkdirSync(s,{recursive:!0});let o=null;T.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let l of r){if(o&&await nc(o,l.workUnit,l.phase,l.topic)){a++;continue}try{let d={workUnit:l.workUnit,phase:l.phase,topic:l.topic},f=await ut(()=>Rr(l.file,d,e,n),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexing ${l.file}... ${f} chunks -`),c++,u+=f,T.existsSync(i)&&(o=await E.loadStore(i))}catch(d){await Ef(l.file,d.message),process.stderr.write(`Failed to index ${l.file} after 3 attempts: ${d.message}. Added to pending queue. -`)}}await rc(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. -`)}async function Ef(t,e){let n=Se(),r=oe(),s=ve();T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;T.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function kr(t){let e=Se(),n=ve();T.existsSync(e)&&await E.withLock(n,async()=>{if(!T.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function rc(t,e,n){let r=Se();if(!T.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=B.resolve(o.file);if(!T.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. -`),await kr(o.file);continue}let u;try{u=Lr(o.file)}catch{await kr(o.file);continue}try{await ut(()=>Rr(o.file,u,t,e),{maxAttempts:3,backoff:ct}),await kr(o.file)}catch{}}}var Af={high:4,medium:3,"low-medium":2,low:1};function vf(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function Tf(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Df(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Af[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function Mf(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. + Current config has no provider configured.`)}async function Pf(t,e,n,r){if(t.length===0)return fn(e,n,r);let s=t[0],i=q.resolve(s);T.existsSync(i)||(process.stderr.write(`File not found: ${i} +`),process.exit(1));let o=Cr(s),c=await ut(()=>Fr(s,o,n,r),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexed ${c} chunks from ${s} +`),await lc(n,r,Df)}async function Fr(t,e,n,r){let s=Of(e.workUnit),i=q.join(__dirname,"..","chunking",e.phase+".json");if(!T.existsSync(i))throw new Error(`Chunking config not found: ${i}`);let o=JSON.parse(T.readFileSync(i,"utf8")),c=q.resolve(t),u=T.readFileSync(c,"utf8"),a=sc.chunk(u,o);if(a.length===0)throw new Error(`No chunks produced from ${t}. Refusing to index an empty file \u2014 this would silently wipe any existing indexed chunks for this topic. Use \`knowledge remove\` explicitly if that is what you want.`);let l=ce(),d=ue(),f=be(),p=Te();T.existsSync(l)||T.mkdirSync(l,{recursive:!0});let g,y,h=T.existsSync(d),m=T.existsSync(f);h&&(g=await E.loadStore(d)),m&&(y=E.readMetadata(f),Array.isArray(y.pending)||(y.pending=[]));let w,S;if(y){let A=uc(y,n,r);w=A.mode,S=A.provider}else r?(w="full",S=r):(w="keyword-only",S=null);if(!g){let A=S?S.dimensions():n.dimensions||jr;g=await E.createStore(A)}let _=null;if(w==="full"&&S&&a.length>0){let A=a.map(k=>k.content);_=await S.embedBatch(A)}let I=Date.now(),v=o.confidence||"medium",D=a.map((A,k)=>{let De=String(k+1).padStart(3,"0"),X={id:`${e.workUnit}-${e.phase}-${e.topic}-${De}`,content:A.content,work_unit:e.workUnit,work_type:s,phase:e.phase,topic:e.topic,confidence:v,source_file:t,timestamp:I};return _&&(X.embedding=_[k]),X});return await E.withLock(p,async()=>{h?g=await E.loadStore(d):T.existsSync(d)&&(g=await E.loadStore(d)),await E.removeByIdentity(g,{work_unit:e.workUnit,phase:e.phase,topic:e.topic});for(let k of D)await E.insertDocument(g,k);await E.saveStore(g,d);let A=T.existsSync(f)?E.readMetadata(f):null;if(A)A.last_indexed=new Date().toISOString(),Array.isArray(A.pending)||(A.pending=[]),E.writeMetadata(f,A);else{let k={provider:S?n.provider:null,model:S?S.model():null,dimensions:S?S.dimensions():null,last_indexed:new Date().toISOString(),pending:[]};E.writeMetadata(f,k)}}),D.length}function ot(t){let{execFileSync:e}=require("child_process");return e("node",[Tf,...t],{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]})}async function ac(t,e,n,r){return(await E.searchFulltext(t,{term:"",where:{work_unit:{eq:e},phase:{eq:n},topic:{eq:r}},limit:1})).length>0}function Br(){let t=[],e;try{let n=ot(["list"]);e=JSON.parse(n)}catch{return t}if(!Array.isArray(e)||e.length===0)return t;for(let n of e){let r=n.name;if(r&&n.status!=="cancelled")for(let s of Lr){let i=n.phases&&n.phases[s];if(!(!i||!i.items)){for(let[o,c]of Object.entries(i.items))if(!(!c||c.status!=="completed"))try{let a=ot(["resolve",`${r}.${s}.${o}`]).trim();a&&T.existsSync(q.resolve(a))&&t.push({file:a,workUnit:r,phase:s,topic:o})}catch{}}}}return t}async function fn(t,e,n){let r=Br(),s=ce(),i=ue();T.existsSync(s)||T.mkdirSync(s,{recursive:!0});let o=null;T.existsSync(i)&&(o=await E.loadStore(i));let c=0,u=0,a=0;for(let l of r){if(o&&await ac(o,l.workUnit,l.phase,l.topic)){a++;continue}try{let d={workUnit:l.workUnit,phase:l.phase,topic:l.topic},f=await ut(()=>Fr(l.file,d,e,n),{maxAttempts:3,backoff:ct});process.stdout.write(`Indexing ${l.file}... ${f} chunks +`),c++,u+=f,T.existsSync(i)&&(o=await E.loadStore(i))}catch(d){await kf(l.file,d.message),process.stderr.write(`Failed to index ${l.file} after 3 attempts: ${d.message}. Added to pending queue. +`)}}await lc(e,n,1/0),process.stdout.write(`Indexed ${c} files (${u} chunks). ${a} already indexed. +`)}async function kf(t,e){let n=be(),r=ce(),s=Te();T.existsSync(r)||T.mkdirSync(r,{recursive:!0}),await E.withLock(s,async()=>{let i;T.existsSync(n)?i=E.readMetadata(n):i={provider:null,model:null,dimensions:null,last_indexed:null,pending:[]},Array.isArray(i.pending)||(i.pending=[]);let o=i.pending.findIndex(u=>u.file===t),c={file:t,failed_at:new Date().toISOString(),error:e};o>=0?i.pending[o]=c:i.pending.push(c),E.writeMetadata(n,i)})}async function Rr(t){let e=be(),n=Te();T.existsSync(e)&&await E.withLock(n,async()=>{if(!T.existsSync(e))return;let r=E.readMetadata(e);Array.isArray(r.pending)&&(r.pending=r.pending.filter(s=>s.file!==t),E.writeMetadata(e,r))})}async function lc(t,e,n){let r=be();if(!T.existsSync(r))return;let s=E.readMetadata(r);if(!Array.isArray(s.pending)||s.pending.length===0)return;let i=s.pending.slice(0,n);for(let o of i){let c=q.resolve(o.file);if(!T.existsSync(c)){process.stderr.write(`Pending item ${o.file} no longer exists. Removing from queue. +`),await Rr(o.file);continue}let u;try{u=Cr(o.file)}catch{await Rr(o.file);continue}try{await ut(()=>Fr(o.file,u,t,e),{maxAttempts:3,backoff:ct}),await Rr(o.file)}catch{}}}var Nf={high:4,medium:3,"low-medium":2,low:1};function Uf(t){if(typeof t!="string")return null;let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e){let n=new Date(t);return isNaN(n.getTime())?null:n}return new Date(parseInt(e[1],10),parseInt(e[2],10)-1,parseInt(e[3],10))}function Rf(t){let e=new Date(t),n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return`${n}-${r}-${s}`}function Lf(t,e){if(t.length===0)return t;let n=Math.max(...t.map(i=>i.timestamp||0)),r=Math.min(...t.map(i=>i.timestamp||0)),s=n-r||1;return t.map(i=>{let o=i.score||0;e&&i.work_unit===e&&(o+=.1);let c=Nf[i.confidence]||0;o+=c*.01;let u=((i.timestamp||0)-r)/s;return o+=u*.05,Object.assign({},i,{score:o})}).sort((i,o)=>o.score-i.score)}function jf(t,e,n){let r=t.provider,s=t.model,i=t.dimensions;if(r==null)return n?{mode:"upgrade-available",provider:null}:{mode:"keyword-only",provider:null};if(!n)throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store was indexed with: provider=${r}, model=${s} Current config has no provider configured.`);let o=n.model(),c=n.dimensions();if(r===e.provider&&s===o&&i===c)return{mode:"full",provider:n};throw new Error(`Provider/model changed since last index. Run \`knowledge rebuild\` to reindex. Store: provider=${r}, model=${s}, dimensions=${i} - Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function Of(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] -`),process.exit(1));let s=t,i=e.limit||10,o=ce(),c=Se();if(!T.existsSync(o)){process.stdout.write(`[0 results] -`);return}let u=await E.loadStore(o),a="keyword-only",l=null,d=null;T.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=Mf(f,n,r);a=p.mode,l=p.provider,a==="keyword-only"?d="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(d="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&l){let v=await ut(()=>l.embed(_),{maxAttempts:3,backoff:ct});I=await E.searchHybrid(u,{term:_,vector:v,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let v of I){let D=m.get(v.id);(!D||v.score>D.score)&&m.set(v.id,v)}}let w=Df(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];d&&S.push(d),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=Tf(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` + Config: provider=${e.provider}, model=${o}, dimensions=${c}`)}async function Cf(t,e,n,r){t.length===0&&(process.stderr.write(`Usage: knowledge query [...] [--phase ...] [--work-type ...] [--work-unit ...] [--limit N] +`),process.exit(1));let s=t,i=e.limit||10,o=ue(),c=be();if(!T.existsSync(o)){process.stdout.write(`[0 results] +`);return}let u=await E.loadStore(o),a="keyword-only",l=null,d=null;T.existsSync(c)||(process.stderr.write("metadata.json missing but store exists. Run `knowledge rebuild` to fix.\n"),process.exit(1));let f=E.readMetadata(c),p=jf(f,n,r);a=p.mode,l=p.provider,a==="keyword-only"?d="[keyword-only mode \u2014 configure embedding provider for semantic search]":a==="upgrade-available"&&(d="[keyword-only mode but embedding provider configured \u2014 run knowledge rebuild for full hybrid search]");let g={};if(e.phase){let _=e.phase.split(",").map(I=>I.trim());g.phase=_.length===1?{eq:_[0]}:{in:_}}if(e.workType){let _=e.workType.split(",").map(I=>I.trim());g.work_type=_.length===1?{eq:_[0]}:{in:_}}if(e.topic){let _=e.topic.split(",").map(I=>I.trim());g.topic=_.length===1?{eq:_[0]}:{in:_}}let y=n.similarity_threshold||.8,h=Object.keys(g).length>0?g:void 0,m=new Map;for(let _ of s){let I;if(a==="full"&&l){let v=await ut(()=>l.embed(_),{maxAttempts:3,backoff:ct});I=await E.searchHybrid(u,{term:_,vector:v,where:h,limit:i*2,similarity:y})}else I=await E.searchFulltext(u,{term:_,where:h,limit:i*2});for(let v of I){let D=m.get(v.id);(!D||v.score>D.score)&&m.set(v.id,v)}}let w=Lf(Array.from(m.values()),e.workUnit);w.length>i&&(w=w.slice(0,i));let S=[];d&&S.push(d),S.push(`[${w.length} results]`);for(let _ of w){S.push("");let I=Rf(_.timestamp);S.push(`[${_.phase} | ${_.work_unit}/${_.topic} | ${_.confidence} | ${I}]`),S.push(_.content),S.push(`Source: ${_.source_file}`)}process.stdout.write(S.join(` `)+` -`)}async function Pf(){let t=oe(),e=B.join(t,"config.json"),n=ce();if(!T.existsSync(t)){process.stdout.write(`not-ready +`)}async function Ff(){let t=ce(),e=q.join(t,"config.json"),n=ue();if(!T.existsSync(t)){process.stdout.write(`not-ready `);return}if(!T.existsSync(e)){process.stdout.write(`not-ready `);return}if(!T.existsSync(n)){process.stdout.write(`not-ready `);return}try{await E.loadStore(n)}catch{process.stdout.write(`not-ready `);return}process.stdout.write(`ready -`)}async function kf(){let t=oe(),e=ce(),n=Se(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!T.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` +`)}async function Bf(){let t=ce(),e=ue(),n=be(),r=[];if(r.push("=== Knowledge Base Status ==="),r.push(""),!T.existsSync(e)){r.push("Store: not initialized"),r.push("Run `knowledge index` to build the index."),process.stdout.write(r.join(` `)+` -`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let l=(T.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${l} KB`),T.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Fe.loadConfig()}catch{m=null}if(m){let w=Fe.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let d=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),T.existsSync(B.resolve(h.source_file))||d.push(h.source_file));if(d.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${d.length} files`);for(let h of d)r.push(` ${h}`)}try{let h=jr(),m=[];for(let w of h)await nc(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=sc(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{ot(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` +`);return}let s=await E.loadStore(e),i=await E.searchFulltext(s,{term:"",limit:1e5});r.push(`Total chunks: ${i.length}`);let o={},c={},u={};for(let h of i)o[h.work_unit]=(o[h.work_unit]||0)+1,c[h.phase]=(c[h.phase]||0)+1,u[h.work_type]=(u[h.work_type]||0)+1;if(Object.keys(o).length>0){r.push(""),r.push("By work unit:");for(let[h,m]of Object.entries(o))r.push(` ${h}: ${m}`)}if(Object.keys(c).length>0){r.push(""),r.push("By phase:");for(let[h,m]of Object.entries(c))r.push(` ${h}: ${m}`)}if(Object.keys(u).length>0){r.push(""),r.push("By work type:");for(let[h,m]of Object.entries(u))r.push(` ${h}: ${m}`)}r.push("");let l=(T.statSync(e).size/1024).toFixed(1);if(r.push(`Store size: ${l} KB`),T.existsSync(n)){let h=E.readMetadata(n);if(r.push(`Last indexed: ${h.last_indexed||"unknown"}`),h.provider?(r.push(`Provider: ${h.provider} (model: ${h.model}, dimensions: ${h.dimensions})`),r.push("Mode: Full (hybrid search)")):(r.push("Provider: none"),r.push("Mode: Keyword-only")),Array.isArray(h.pending)&&h.pending.length>0){r.push(""),r.push(`Pending items: ${h.pending.length}`);for(let w of h.pending)r.push(` ${w.file} \u2014 ${w.error} (${w.failed_at})`)}let m;try{m=Fe.loadConfig()}catch{m=null}if(m){let w=Fe.resolveProvider(m);h.provider&&w&&(h.provider!==m.provider||h.model!==w.model()||h.dimensions!==w.dimensions())&&(r.push(""),r.push("WARNING: Config has changed since last index. Run `knowledge rebuild` to reindex.")),(h.provider===null||h.provider===void 0)&&w&&(r.push(""),r.push("NOTE: Keyword-only mode but embedding provider configured. Run `knowledge rebuild` for full hybrid search."))}}else r.push("Metadata: missing (run `knowledge rebuild` to fix)");let d=[],f=new Set;for(let h of i)f.has(h.source_file)||(f.add(h.source_file),T.existsSync(q.resolve(h.source_file))||d.push(h.source_file));if(d.length>0){r.push(""),r.push(`Orphaned chunks (source deleted): ${d.length} files`);for(let h of d)r.push(` ${h}`)}try{let h=Br(),m=[];for(let w of h)await ac(s,w.workUnit,w.phase,w.topic)||m.push(w.file);if(m.length>0){r.push(""),r.push(`Unindexed completed artifacts: ${m.length}`);for(let w of m)r.push(` ${w}`)}}catch{}let p=[];for(let h of Object.keys(o)){let m=dc(h);m&&m.status==="cancelled"&&p.push(`Cancelled work unit still indexed: ${h}`)}let g=i.filter(h=>h.phase==="specification"),y=new Set(g.map(h=>`${h.work_unit}.specification.${h.topic}`));for(let h of y)try{ot(["get",h,"status"]).trim()==="superseded"&&p.push(`Superseded spec still indexed: ${h}`)}catch{}if(p.length>0){r.push(""),r.push("Consistency warnings:");for(let h of p)r.push(` ${h}`)}process.stdout.write(r.join(` `)+` -`)}async function Nf(t,e,n,r){let s=ce(),i=Se(),o=ve();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. +`)}async function $f(t,e,n,r){let s=ue(),i=be(),o=Te();process.stderr.write(`Warning: This will delete the existing index and rebuild from scratch. This is non-deterministic \u2014 the rebuilt index will differ from the original. -Type 'rebuild' to confirm: `),await Uf()!=="rebuild"&&(process.stderr.write(`Aborted. -`),process.exit(1)),jr().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. +Type 'rebuild' to confirm: `),await qf()!=="rebuild"&&(process.stderr.write(`Aborted. +`),process.exit(1)),Br().length===0&&(process.stderr.write(`No completed artifacts found to index. Aborting rebuild \u2014 the existing index has NOT been modified. (If you believe this is wrong, check that .workflows/ exists and that work units have items with status "completed".) -`),process.exit(1)),await E.withLock(o,async()=>{T.existsSync(s)&&T.unlinkSync(s),T.existsSync(i)&&T.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||Ur,l=await E.createStore(a);await E.saveStore(l,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. -`),await an(e,n,r)}function Uf(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function Lf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] +`),process.exit(1)),await E.withLock(o,async()=>{T.existsSync(s)&&T.unlinkSync(s),T.existsSync(i)&&T.unlinkSync(i);let a=r?r.dimensions():n&&n.dimensions||jr,l=await E.createStore(a);await E.saveStore(l,s),E.writeMetadata(i,{provider:r?n.provider:null,model:r?r.model():null,dimensions:r?r.dimensions():null,last_indexed:new Date().toISOString(),pending:[]})}),process.stdout.write(`Deleted existing index. +`),await fn(e,n,r)}function qf(){return new Promise(t=>{let e="",n=!1,r=()=>{if(n)return;n=!0;let o=e.search(/\r|\n/),c=o===-1?e:e.slice(0,o);t(c.trim())};process.stdin.setEncoding("utf8");let s=o=>{e+=o,/\r|\n/.test(e)&&(process.stdin.removeListener("data",s),process.stdin.removeListener("end",i),r())},i=()=>{process.stdin.removeListener("data",s),r()};process.stdin.on("data",s),process.stdin.once("end",i),process.stdin.resume()})}async function zf(t,e){e.workUnit||(process.stderr.write(`Usage: knowledge remove --work-unit [--phase

] [--topic ] `),process.exit(1)),e.topic&&!e.phase&&(process.stderr.write(`Error: --topic requires --phase -`),process.exit(1));let n=ce(),r=ve();if(!T.existsSync(n)){let o=Jo(e);process.stdout.write(`Removed 0 chunks for ${o} -`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=Jo(e);process.stdout.write(`Removed ${s} chunks for ${i} -`)}function Jo(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function sc(t){try{let e=ot(["get",t,"status"]).trim(),n=null;try{n=ot(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function Rf(t,e,n){let r=ce(),s=ve(),i=n&&n.decay_months!==void 0?n.decay_months:Fe.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled +`),process.exit(1));let n=ue(),r=Te();if(!T.existsSync(n)){let o=rc(e);process.stdout.write(`Removed 0 chunks for ${o} +`);return}let s=0;await E.withLock(r,async()=>{let o=await E.loadStore(n),c={work_unit:{eq:e.workUnit}};e.phase&&(c.phase={eq:e.phase}),e.topic&&(c.topic={eq:e.topic}),s=await E.removeByFilter(o,c),await E.saveStore(o,n)});let i=rc(e);process.stdout.write(`Removed ${s} chunks for ${i} +`)}function rc(t){return t.topic?`${t.workUnit}/${t.phase}/${t.topic}`:t.phase?`${t.workUnit}/${t.phase}`:`${t.workUnit} (all phases)`}function dc(t){try{let e=ot(["get",t,"status"]).trim(),n=null;try{n=ot(["get",t,"completed_at"]).trim(),(n===""||n==="undefined"||n==="null")&&(n=null)}catch{}return{status:e,completed_at:n}}catch{return null}}async function Vf(t,e,n){let r=ue(),s=Te(),i=n&&n.decay_months!==void 0?n.decay_months:Fe.DEFAULTS.decay_months;if(i===!1){process.stdout.write(`Compaction disabled `);return}(!Number.isInteger(i)||i<0)&&(process.stderr.write(`Invalid decay_months: ${JSON.stringify(i)}. Expected false or a non-negative integer. -`),process.exit(1));let o=i;if(!T.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let l=await E.searchFulltext(c,{term:"",limit:1e5});if(l.length===0)return;let d={};for(let h of l)d[h.work_unit]||(d[h.work_unit]=[]),d[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(d)){let w=sc(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=vf(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let v=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:v});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` +`),process.exit(1));let o=i;if(!T.existsSync(r))return;let c=await E.loadStore(r),u=new Date,a=new Date(u);a.setMonth(a.getMonth()-o);let l=await E.searchFulltext(c,{term:"",limit:1e5});if(l.length===0)return;let d={};for(let h of l)d[h.work_unit]||(d[h.work_unit]=[]),d[h.work_unit].push(h);let f=[],p=[];for(let[h,m]of Object.entries(d)){let w=dc(h);if(!w||w.status!=="completed"||!w.completed_at)continue;let S=Uf(w.completed_at);if(!S||isNaN(S.getTime()))continue;let _=new Date(S);if(_.setMonth(_.getMonth()+o),_>u)continue;let I=m.filter(D=>D.phase!=="specification");if(I.length===0)continue;let v=new Set(I.map(D=>D.phase));f.push({workUnit:h,count:I.length,phases:v});for(let D of I)p.push({work_unit:D.work_unit,phase:D.phase,topic:D.topic})}if(f.length===0)return;let g=f.reduce((h,m)=>h+m.count,0);if(e.dryRun){let h=[];h.push(`[dry-run] Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let m of f)h.push(` \u2022 ${m.workUnit}: ${m.count} chunks (${Array.from(m.phases).join(", ")})`);process.stdout.write(h.join(` `)+` `);return}await E.withLock(s,async()=>{let h=await E.loadStore(r),m=new Set;for(let w of p){let S=`${w.work_unit}|${w.phase}|${w.topic}`;m.has(S)||(m.add(S),await E.removeByIdentity(h,w))}await E.saveStore(h,r)});let y=[];y.push(`Compacted: removed ${g} chunks from ${f.length} work units (completed > ${o} months ago)`);for(let h of f)y.push(` \u2022 ${h.workUnit}: ${h.count} chunks (${Array.from(h.phases).join(", ")})`);process.stdout.write(y.join(` `)+` -`)}async function ic(){let t=process.argv.slice(2),{positional:e,flags:n}=Qo(t),r=e[0],s=e.slice(1),i=ec(n);r||(process.stderr.write(Yo+` -`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Fe.loadConfig(),c=Fe.resolveProvider(o)),r){case"index":await xf(s,i,o,c);break;case"query":await Of(s,i,o,c);break;case"check":await Pf(s,i,o,c);break;case"status":await kf();break;case"remove":await Lf(s,i,o,c);break;case"compact":await Rf(s,i,o,c);break;case"rebuild":await Nf(s,i,o,c);break;case"setup":await Zo.cmdSetup(an,s,i);break;default:process.stderr.write(`Unknown command "${r}". +`)}async function fc(){let t=process.argv.slice(2),{positional:e,flags:n}=oc(t),r=e[0],s=e.slice(1),i=cc(n);r||(process.stderr.write(nc+` +`),process.exit(1));let o=null,c=null;switch(["index","query","rebuild","compact"].includes(r)&&(o=Fe.loadConfig(),c=Fe.resolveProvider(o)),r){case"index":await Pf(s,i,o,c);break;case"query":await Cf(s,i,o,c);break;case"check":await Ff(s,i,o,c);break;case"status":await Bf();break;case"remove":await zf(s,i,o,c);break;case"compact":await Vf(s,i,o,c);break;case"rebuild":await $f(s,i,o,c);break;case"setup":await ic.cmdSetup(fn,s,i);break;default:process.stderr.write(`Unknown command "${r}". -${Yo} -`),process.exit(1)}}module.exports={parseArgs:Qo,buildOptions:ec,deriveIdentity:Lr,resolveProviderState:tc,withRetry:ut,main:ic,cmdIndexBulk:an,StubProvider:mf,OpenAIProvider:wf,store:E,chunker:Xo,config:Fe,setup:Zo,knowledgeDir:oe,storePath:ce,metadataPath:Se,lockFilePath:ve,INDEXED_PHASES:Nr,KEYWORD_ONLY_DIMENSIONS:Ur};require.main===module&&ic().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` +${nc} +`),process.exit(1)}}module.exports={parseArgs:oc,buildOptions:cc,deriveIdentity:Cr,resolveProviderState:uc,withRetry:ut,main:fc,cmdIndexBulk:fn,StubProvider:Af,OpenAIProvider:vf,store:E,chunker:sc,config:Fe,setup:ic,knowledgeDir:ce,storePath:ue,metadataPath:be,lockFilePath:Te,INDEXED_PHASES:Lr,KEYWORD_ONLY_DIMENSIONS:jr};require.main===module&&fc().catch(t=>{process.stderr.write(String(t&&t.stack?t.stack:t)+` `),process.exit(1)}); diff --git a/src/knowledge/setup.js b/src/knowledge/setup.js index 9f61fe64c..011106dda 100644 --- a/src/knowledge/setup.js +++ b/src/knowledge/setup.js @@ -1,16 +1,18 @@ // Knowledge base interactive setup wizard. // // Human-only. Uses Node's built-in readline for prompts. Aborts cleanly -// on non-TTY invocation (Claude, pipes, CI). Idempotent — running on a -// fully configured project exits with "already set up". Running on a -// partial configuration completes the missing pieces. +// on non-TTY invocation (Claude, pipes, CI). Idempotent — per-step +// prompts detect existing state and offer skip or reconfigure. // // Wizard steps: // 1. System config at ~/.config/workflows/config.json (provider, model, -// dimensions, api_key_env — or stub mode when the user skips). -// 2. Project init at .workflows/.knowledge/ (directory, config.json, +// dimensions — no secrets). Stub mode when the user chooses "skip". +// 2. API key: read from $OPENAI_API_KEY if set, else ~/.config/workflows/ +// credentials.json (mode 0600), else prompt inline and store to that +// file. Env wins over file. +// 3. Project init at .workflows/.knowledge/ (directory, config.json, // empty store.msp, metadata.json). -// 3. Initial bulk indexing (wired in Task 2). +// 4. Initial bulk indexing via cmdIndexBulk (injected by caller). 'use strict'; @@ -24,7 +26,6 @@ const { OpenAIProvider } = require('./providers/openai'); const OPENAI_DEFAULT_MODEL = 'text-embedding-3-small'; const OPENAI_DEFAULT_DIMENSIONS = 1536; -const OPENAI_DEFAULT_ENV_VAR = 'OPENAI_API_KEY'; // Used when creating the initial store in stub / keyword-only mode — // Orama's schema requires a dimension parameter even when docs omit @@ -91,17 +92,92 @@ async function askYesNo(rl, prompt, defaultYes) { }); } +/** + * Read a line from stdin without echoing the characters — one '*' is + * written per typed/pasted character so the prompt still feels alive, + * but the secret itself never lands in the terminal scrollback. Used + * for API keys. + * + * Bypasses the readline interface temporarily: pauses `rl`, switches + * stdin to raw mode, consumes keystrokes directly, then restores + * everything on Enter. Ctrl-C exits 130; Ctrl-D submits the current + * buffer. Backspace edits as you'd expect. + */ +function askSecret(rl, prompt) { + return new Promise((resolve) => { + const stdin = process.stdin; + const stdout = process.stdout; + + // Fallback when stdin is not a TTY — no masking available, read a + // plain line. cmdSetup aborts before this in non-TTY mode, so this + // branch is defensive only. + if (!stdin.isTTY || typeof stdin.setRawMode !== 'function') { + rl.question(prompt, (ans) => resolve((ans || '').trim())); + return; + } + + stdout.write(prompt); + rl.pause(); + + const wasRaw = stdin.isRaw === true; + stdin.setRawMode(true); + stdin.resume(); + stdin.setEncoding('utf8'); + + let buf = ''; + const cleanup = () => { + stdin.removeListener('data', onData); + try { stdin.setRawMode(wasRaw); } catch (_) { /* best effort */ } + stdin.pause(); + rl.resume(); + }; + + const onData = (chunk) => { + for (const ch of chunk.toString('utf8')) { + if (ch === '\n' || ch === '\r') { + cleanup(); + stdout.write('\n'); + return resolve(buf.trim()); + } + if (ch === '\u0003') { // Ctrl-C + cleanup(); + stdout.write('\n'); + process.exit(130); + return; + } + if (ch === '\u0004') { // Ctrl-D — submit what's in the buffer + cleanup(); + stdout.write('\n'); + return resolve(buf.trim()); + } + if (ch === '\u007f' || ch === '\b') { // Backspace / DEL + if (buf.length > 0) { + buf = buf.slice(0, -1); + stdout.write('\b \b'); + } + continue; + } + // Ignore anything below space except the explicit cases above. + if (ch < ' ') continue; + buf += ch; + stdout.write('*'); + } + }; + + stdin.on('data', onData); + }); +} + // --------------------------------------------------------------------------- // Config shape builders — pure, unit-testable // --------------------------------------------------------------------------- -function buildSystemConfigOpenAI({ model, dimensions, apiKeyEnv }) { +function buildSystemConfigOpenAI({ model, dimensions }) { return { knowledge: { provider: 'openai', model, dimensions, - api_key_env: apiKeyEnv, similarity_threshold: config.DEFAULTS.similarity_threshold, decay_months: config.DEFAULTS.decay_months, }, @@ -175,6 +251,57 @@ async function validateApiKey({ apiKey, model, dimensions }) { return true; } +/** + * Map a validation error to a human-friendly description and hint. + * Returns { message, hint } — caller renders both. + */ +function describeValidationError(err) { + const msg = (err && err.message) || String(err); + + if (/401/.test(msg) || /invalid or expired/i.test(msg)) { + return { + message: 'The API key was rejected (HTTP 401).', + hint: + 'Check that the key is active and not revoked. Free-tier keys also need billing enabled ' + + 'for /v1/embeddings. Create a fresh key at https://platform.openai.com/api-keys and try again.', + }; + } + if (/403/.test(msg) || /permission/i.test(msg)) { + return { + message: 'The API key does not have permission for embeddings (HTTP 403).', + hint: + 'If this is a restricted key, check its allowed endpoints in the OpenAI dashboard. ' + + 'Create a key with Embeddings access enabled.', + }; + } + if (/429/.test(msg) || /rate limit/i.test(msg)) { + return { + message: 'Rate limit hit during validation (HTTP 429).', + hint: + 'Your account may be out of quota, or the default rate limit is saturated. ' + + 'Wait a moment and retry, or check billing at https://platform.openai.com/account.', + }; + } + if (/network error/i.test(msg) || /ENOTFOUND/.test(msg) || /ECONN/.test(msg) || /ETIMEDOUT/.test(msg)) { + return { + message: 'Could not reach OpenAI (network error).', + hint: + 'Check your internet connection, VPN, or corporate proxy. No key was written — ' + + 'you can re-run `knowledge setup` once the connection is stable.', + }; + } + if (/HTTP 5\d\d/.test(msg)) { + return { + message: 'OpenAI returned a server error during validation.', + hint: 'Transient on their side. Retry in a minute.', + }; + } + return { + message: 'API key validation failed.', + hint: `Error detail: ${msg}`, + }; +} + // --------------------------------------------------------------------------- // System config step // --------------------------------------------------------------------------- @@ -190,7 +317,6 @@ async function runSystemConfigStep(rl) { process.stdout.write(` provider: ${k.provider == null ? '(none — stub mode)' : k.provider}\n`); if (k.model) process.stdout.write(` model: ${k.model}\n`); if (k.dimensions) process.stdout.write(` dimensions: ${k.dimensions}\n`); - if (k.api_key_env) process.stdout.write(` api_key_env: ${k.api_key_env}\n`); process.stdout.write('\n'); const reconfigure = await askYesNo(rl, 'Reconfigure system settings?', false); @@ -242,36 +368,126 @@ async function runSystemConfigStep(rl) { process.stderr.write(`Invalid dimensions: "${dimsRaw}". Must be a positive integer.\n`); process.exit(1); } - const apiKeyEnv = await ask(rl, 'API key environment variable', OPENAI_DEFAULT_ENV_VAR); - // Validate env var (non-blocking — warn only). - const apiKey = process.env[apiKeyEnv]; - if (apiKey && apiKey.trim() !== '') { - process.stdout.write(`\nValidating API key via a test embed...\n`); + // Write the non-secret config first so it's on disk even if the key + // step aborts or the user interrupts mid-prompt. + config.writeConfigFile(sysPath, buildSystemConfigOpenAI({ model, dimensions })); + process.stdout.write(`\nWrote system config to ${sysPath}\n`); + + // Resolve the API key: env first, then credentials file, then prompt. + const envVar = config.PROVIDER_ENV_VARS.openai; + await ensureOpenAIKey(rl, { envVar, model, dimensions }); + + return { provider: 'openai', previouslyStub }; +} + +/** + * Ensure an OpenAI API key is available for this run and validate it. + * Resolution order: process.env → credentials file → inline prompt. + * Newly entered keys are written to the credentials file at 0600. + */ +async function ensureOpenAIKey(rl, { envVar, model, dimensions }) { + const credPath = config.credentialsPath(); + + // 1. Env var wins. Nothing is written to disk — env is authoritative. + const fromEnv = process.env[envVar]; + if (fromEnv && fromEnv.trim() !== '') { + process.stdout.write(`\nUsing API key from $${envVar} — validating via a test embed...\n`); + try { + await validateApiKey({ apiKey: fromEnv.trim(), model, dimensions }); + process.stdout.write('API key works.\n'); + } catch (err) { + const { message, hint } = describeValidationError(err); + process.stdout.write(`${message}\n ${hint}\n`); + process.stdout.write( + `The failing key came from $${envVar}. Fix or unset it in your shell, ` + + 'then re-run `knowledge setup`. Setup will continue — indexing will queue until ' + + 'the key is corrected.\n' + ); + } + return; + } + + // 2. Existing credentials file. Validate; let the user replace it if broken. + const fromFile = config.resolveApiKey('openai', { credentialsPath: credPath }); + if (fromFile) { + process.stdout.write(`\nFound an existing API key in ${credPath} — validating via a test embed...\n`); try { - await validateApiKey({ apiKey: apiKey.trim(), model, dimensions }); + await validateApiKey({ apiKey: fromFile, model, dimensions }); process.stdout.write('API key works.\n'); + return; } catch (err) { - process.stdout.write(`API key validation failed: ${err.message}\n`); - const cont = await askYesNo(rl, 'Continue anyway (you can fix the key later)?', true); - if (!cont) { - process.stdout.write('Aborting setup.\n'); - process.exit(1); + const { message, hint } = describeValidationError(err); + process.stdout.write(`${message}\n ${hint}\n`); + const replace = await askYesNo(rl, 'Enter a new key to replace it?', true); + if (!replace) { + process.stdout.write( + 'Keeping the existing stored key. Indexing will fail until it is rotated.\n' + + `Edit ${credPath} or re-run \`knowledge setup\` when you have a new key.\n` + ); + return; } + // Fall through to prompt path to collect and store a replacement. } - } else { - process.stdout.write( - `\nEnvironment variable ${apiKeyEnv} is not set. ` + - `Set it in your shell profile (e.g., ~/.zshrc) before using the knowledge base:\n` + - ` export ${apiKeyEnv}="sk-..."\n` + - `Setup will continue — the key is only needed at query/index time.\n` - ); } - config.writeConfigFile(sysPath, buildSystemConfigOpenAI({ model, dimensions, apiKeyEnv })); - process.stdout.write(`\nWrote system config to ${sysPath}\n`); + // 3. No valid key anywhere — prompt inline and store. + await promptForKeyAndStore(rl, { envVar, model, dimensions, credPath }); +} - return { provider: 'openai', previouslyStub }; +/** + * Print the OpenAI key explainer, prompt for a key, validate it, and + * write it to the credentials file at 0600. Loops on validation failure + * so the user can retry with a different key. + */ +async function promptForKeyAndStore(rl, { envVar, model, dimensions, credPath }) { + process.stdout.write( + '\nOpenAI API Key\n' + + '--------------\n' + + 'Semantic search in the knowledge base relies on OpenAI embeddings.\n' + + 'We recommend creating a dedicated key for this tool so you can rotate\n' + + 'or revoke it independently from other integrations.\n' + + '\n' + + ' 1. Create a key: https://platform.openai.com/api-keys\n' + + ` (Suggested name: "agentic-workflows")\n` + + ' 2. Paste the full key (starting with "sk-") at the prompt below.\n' + + '\n' + + `Your key will be stored at:\n` + + ` ${credPath} (mode 0600, user-private)\n` + + `Setting $${envVar} in your shell takes precedence and overrides the\n` + + 'stored key, so you can swap it without editing the file.\n\n' + ); + + while (true) { + const key = await askSecret(rl, 'API key (input hidden): '); + + if (key === '') { + process.stdout.write('Empty input — enter the key, or Ctrl-C to abort setup.\n\n'); + continue; + } + + process.stdout.write('\nValidating via a test embed...\n'); + try { + await validateApiKey({ apiKey: key, model, dimensions }); + } catch (err) { + const { message, hint } = describeValidationError(err); + process.stdout.write(`${message}\n ${hint}\n\n`); + const retry = await askYesNo(rl, 'Try a different key?', true); + if (!retry) { + process.stdout.write( + 'No key stored. Setup continues but indexing will skip until a key is provided.\n' + + `Set $${envVar} in your shell or re-run \`knowledge setup\`.\n` + ); + return; + } + continue; + } + + // Validated — write the credentials file. + config.writeCredentials(credPath, 'openai', key); + process.stdout.write(`API key works. Stored at ${credPath} (mode 0600).\n`); + return; + } } // --------------------------------------------------------------------------- @@ -413,17 +629,19 @@ module.exports = { createPrompter, ask, askYesNo, + askSecret, buildSystemConfigOpenAI, buildSystemConfigStub, buildProjectConfigEmpty, detectSystemConfig, detectProjectInit, validateApiKey, + describeValidationError, + ensureOpenAIKey, runSystemConfigStep, runProjectInitStep, runInitialIndexStep, KEYWORD_ONLY_DIMENSIONS, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_DIMENSIONS, - OPENAI_DEFAULT_ENV_VAR, }; diff --git a/tests/scripts/test-knowledge-config.cjs b/tests/scripts/test-knowledge-config.cjs index 560deb7c0..bb513b73f 100644 --- a/tests/scripts/test-knowledge-config.cjs +++ b/tests/scripts/test-knowledge-config.cjs @@ -24,6 +24,7 @@ const { buildProjectConfigEmpty, detectSystemConfig, detectProjectInit, + describeValidationError, } = require('../../src/knowledge/setup'); let tmpDir; @@ -542,16 +543,15 @@ describe('writeConfigFile', () => { // --------------------------------------------------------------------------- describe('buildSystemConfigOpenAI', () => { - it('produces a config with provider, model, dimensions, api_key_env, and defaults', () => { + it('produces a config with provider, model, dimensions, and defaults (no api_key_env)', () => { const cfg = buildSystemConfigOpenAI({ model: 'text-embedding-3-small', dimensions: 1536, - apiKeyEnv: 'OPENAI_API_KEY', }); assert.strictEqual(cfg.knowledge.provider, 'openai'); assert.strictEqual(cfg.knowledge.model, 'text-embedding-3-small'); assert.strictEqual(cfg.knowledge.dimensions, 1536); - assert.strictEqual(cfg.knowledge.api_key_env, 'OPENAI_API_KEY'); + assert.strictEqual(cfg.knowledge.api_key_env, undefined); assert.strictEqual(cfg.knowledge.similarity_threshold, DEFAULTS.similarity_threshold); assert.strictEqual(cfg.knowledge.decay_months, DEFAULTS.decay_months); }); @@ -638,6 +638,38 @@ describe('detectSystemConfig', () => { }); }); +describe('describeValidationError', () => { + it('maps 401 to an invalid-key hint', () => { + const { message, hint } = describeValidationError(new Error('OpenAI API key is invalid or expired. Check your OPENAI_API_KEY environment variable.')); + assert.match(message, /rejected/i); + assert.match(hint, /active|revoked|create a fresh key/i); + }); + + it('maps 429 to a rate-limit hint', () => { + const { message, hint } = describeValidationError(new Error('OpenAI rate limit exceeded (HTTP 429).')); + assert.match(message, /rate limit/i); + assert.match(hint, /quota|retry/i); + }); + + it('maps network errors to a connection hint', () => { + const { message, hint } = describeValidationError(new Error('OpenAI embedding request failed (network error): fetch failed')); + assert.match(message, /Could not reach OpenAI/i); + assert.match(hint, /connection|VPN|proxy/i); + }); + + it('maps 5xx to a transient-server hint', () => { + const { message, hint } = describeValidationError(new Error('OpenAI embedding request failed (HTTP 503): service unavailable')); + assert.match(message, /server error/i); + assert.match(hint, /retry/i); + }); + + it('falls back to a generic message for unknown errors', () => { + const { message, hint } = describeValidationError(new Error('something weird happened')); + assert.match(message, /validation failed/i); + assert.match(hint, /something weird happened/); + }); +}); + describe('detectProjectInit', () => { beforeEach(setup); afterEach(teardown); From 6e5d3253c8d9a3bf86dc12b9e9bf563295a48f95 Mon Sep 17 00:00:00 2001 From: Lee Overy Date: Sun, 19 Apr 2026 20:05:21 +0100 Subject: [PATCH 5/5] fix(manifest): readProjectManifest aborts on corrupt JSON instead of silently returning {} MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous try/catch swallowed every read error, including JSON parse failures on a corrupt manifest. Callers then initialised work_units = {}, merged in their own entry, and wrote back — erasing every previously-registered work unit. This silently ate 7 of 8 work_units in a real project (tick) when an unrelated Go refactor commit introduced a trailing comma into the manifest and the next workflow command hit the swallow path. Now distinguishes ENOENT (legitimate first-write, return {}) from parse errors and other I/O errors (die with a clear message pointing the user at the file). Corrupt manifests are preserved on disk — they're surfaced, not silently overwritten. Test covers the exact clobber pattern: trailing-comma manifest + init command. Asserts exit 1, error mentions "not valid JSON" and "by hand", and the corrupt file is still corrupt afterwards (no write happened). Also a positive test that missing manifest is treated as first-write. Co-Authored-By: Claude Opus 4.7 (1M context) --- skills/workflow-manifest/scripts/manifest.cjs | 26 +++++++++-- tests/scripts/test-workflow-manifest.sh | 46 +++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/skills/workflow-manifest/scripts/manifest.cjs b/skills/workflow-manifest/scripts/manifest.cjs index 7c7ab9d91..57f6a16c5 100644 --- a/skills/workflow-manifest/scripts/manifest.cjs +++ b/skills/workflow-manifest/scripts/manifest.cjs @@ -140,10 +140,30 @@ function projectLockPath() { function readProjectManifest() { const p = projectManifestPath(); + let raw; try { - return JSON.parse(fs.readFileSync(p, 'utf8')); - } catch (_) { - return {}; + raw = fs.readFileSync(p, 'utf8'); + } catch (e) { + // Missing file is a legitimate first-write state — callers can + // populate and write. Any other read error (permissions, I/O) + // must surface loudly rather than producing a fresh empty manifest + // that would then be written back, clobbering on-disk state. + if (e.code === 'ENOENT') return {}; + die(`Failed to read project manifest at ${p}: ${e.message}`); + } + try { + return JSON.parse(raw); + } catch (e) { + // Corrupt JSON in an existing manifest — abort instead of silently + // returning an empty object. Returning {} here and letting callers + // write would erase every registered work unit. Force the user to + // inspect and repair rather than destroying state. + die( + `Project manifest at ${p} is not valid JSON: ${e.message}\n` + + 'Inspect the file and fix it by hand, then re-run the command. ' + + 'Do not let another workflow command write to it first — a write ' + + 'against a corrupt manifest would replace all registered work units.' + ); } } diff --git a/tests/scripts/test-workflow-manifest.sh b/tests/scripts/test-workflow-manifest.sh index ac0da37a8..aff6fc589 100755 --- a/tests/scripts/test-workflow-manifest.sh +++ b/tests/scripts/test-workflow-manifest.sh @@ -1664,6 +1664,52 @@ assert_contains "$output" "auth-flow/discussion/auth-flow.md" "Path returned eve echo "" +# ---------------------------------------------------------------------------- + +echo -e "${YELLOW}Test: corrupt project manifest aborts with clear error (no silent clobber)${NC}" +setup_fixture +# Write a corrupt project manifest — invalid JSON with a trailing comma +# (the exact pattern that silently wiped tick's work_units). +cat > "$TEST_DIR/.workflows/manifest.json" <<'BADJSON' +{ + "work_units": { + "existing-unit": { + "work_type": "feature" + }, + } +} +BADJSON + +# Single invocation: capture both exit code and output. init creates the +# work-unit directory before touching the project manifest, so a second +# invocation would fail with "already exists" and mask the real error. +combined=$(cd "$TEST_DIR" && node "$MANIFEST_JS" init new-unit --work-type bugfix --description "x" 2>&1; echo "__EXIT__=$?") +exit_code=$(echo "$combined" | grep -o '__EXIT__=[0-9]*' | tail -1 | cut -d= -f2) +output=$(echo "$combined" | grep -v '__EXIT__=') + +assert_equals "$exit_code" "1" "Corrupt manifest exits 1" +assert_contains "$output" "not valid JSON" "Error mentions invalid JSON" +assert_contains "$output" "by hand" "Error tells user to fix manually" + +# Verify the corrupt manifest was NOT overwritten — the trailing comma +# should still be on disk. +manifest_still_corrupt=$(cat "$TEST_DIR/.workflows/manifest.json" | node -e "let s=''; process.stdin.on('data',c=>s+=c); process.stdin.on('end',()=>{try{JSON.parse(s);console.log('parsed');}catch(e){console.log('still-corrupt');}});") +assert_equals "$manifest_still_corrupt" "still-corrupt" "Corrupt manifest preserved on disk (not clobbered)" + +echo "" + +# ---------------------------------------------------------------------------- + +echo -e "${YELLOW}Test: missing project manifest is treated as first-write (not an error)${NC}" +setup_fixture +# No manifest.json on disk — init should create it fresh. +exit_code=$(run_cli_exit_code init first-unit --work-type feature --description "x") +assert_equals "$exit_code" "0" "First init succeeds without existing manifest" +registered=$(node -e "console.log(Object.keys(JSON.parse(require('fs').readFileSync('$TEST_DIR/.workflows/manifest.json', 'utf8')).work_units).join(','))" 2>/dev/null) +assert_equals "$registered" "first-unit" "Manifest registers the first work unit" + +echo "" + # ============================================================================ # SUMMARY # ============================================================================