@warlock.js/ai 4.4.0 → 4.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -52
- package/cjs/index.cjs +240 -14147
- package/cjs/src-Bmajk4Qg.cjs +30 -0
- package/cjs/src-OZyDYHxm.cjs +25089 -0
- package/cjs/src-OZyDYHxm.cjs.map +1 -0
- package/esm/agent/agent-config.type.d.mts +119 -1
- package/esm/agent/agent-config.type.d.mts.map +1 -1
- package/esm/agent/agent-input-builder.mjs +27 -6
- package/esm/agent/agent-input-builder.mjs.map +1 -1
- package/esm/agent/agent.d.mts +40 -1
- package/esm/agent/agent.d.mts.map +1 -1
- package/esm/agent/agent.mjs +328 -36
- package/esm/agent/agent.mjs.map +1 -1
- package/esm/agent/index.d.mts +2 -1
- package/esm/agent/index.mjs +1 -0
- package/esm/agent/judge-config.type.d.mts +33 -0
- package/esm/agent/judge-config.type.d.mts.map +1 -0
- package/esm/agent/judge-config.type.mjs +13 -0
- package/esm/agent/judge-config.type.mjs.map +1 -0
- package/esm/agent/signature.mjs +57 -0
- package/esm/agent/signature.mjs.map +1 -0
- package/esm/agent/snapshot.mjs +101 -0
- package/esm/agent/snapshot.mjs.map +1 -0
- package/esm/ai-openai/src/embedder.mjs +4 -0
- package/esm/ai-openai/src/image.mjs +5 -0
- package/esm/ai-openai/src/index.mjs +7 -0
- package/esm/ai-openai/src/model.mjs +5 -0
- package/esm/ai-openai/src/sdk.mjs +9 -0
- package/esm/ai-openai/src/speech.mjs +5 -0
- package/esm/ai-openai/src/transcription.mjs +6 -0
- package/esm/ai-openai/src/utils/index.mjs +5 -0
- package/esm/ai-openai/src/utils/to-openai-messages.mjs +3 -0
- package/esm/ai-openai/src/utils/to-openai-tools.mjs +3 -0
- package/esm/ai-openai/src/utils/wrap-openai-error.mjs +4 -0
- package/esm/ai.d.mts +164 -53
- package/esm/ai.d.mts.map +1 -1
- package/esm/ai.mjs +79 -8
- package/esm/ai.mjs.map +1 -1
- package/esm/batch/batch.d.mts.map +1 -1
- package/esm/batch/batch.mjs +21 -1
- package/esm/batch/batch.mjs.map +1 -1
- package/esm/batch/batch.type.d.mts +11 -4
- package/esm/batch/batch.type.d.mts.map +1 -1
- package/esm/config.d.mts +39 -3
- package/esm/config.d.mts.map +1 -1
- package/esm/config.mjs +26 -2
- package/esm/config.mjs.map +1 -1
- package/esm/contracts/agent/agent-options.type.d.mts +33 -5
- package/esm/contracts/agent/agent-options.type.d.mts.map +1 -1
- package/esm/contracts/agent/agent-snapshot.type.d.mts +90 -0
- package/esm/contracts/agent/agent-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/agent/agent.contract.d.mts +29 -1
- package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
- package/esm/contracts/agent/eval.type.d.mts +43 -2
- package/esm/contracts/agent/eval.type.d.mts.map +1 -1
- package/esm/contracts/agent/index.d.mts +2 -1
- package/esm/contracts/attachment-policy.type.d.mts +51 -0
- package/esm/contracts/attachment-policy.type.d.mts.map +1 -0
- package/esm/contracts/attachment.type.d.mts +16 -7
- package/esm/contracts/attachment.type.d.mts.map +1 -1
- package/esm/contracts/content-part.type.d.mts +14 -5
- package/esm/contracts/content-part.type.d.mts.map +1 -1
- package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -1
- package/esm/contracts/image-model.contract.d.mts +156 -0
- package/esm/contracts/image-model.contract.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +13 -6
- package/esm/contracts/model.contract.d.mts +11 -8
- package/esm/contracts/model.contract.d.mts.map +1 -1
- package/esm/contracts/orchestrator/index.d.mts +1 -0
- package/esm/contracts/orchestrator/orchestrator-config.type.d.mts +31 -2
- package/esm/contracts/orchestrator/orchestrator-config.type.d.mts.map +1 -1
- package/esm/contracts/orchestrator/session-lock.contract.d.mts +47 -0
- package/esm/contracts/orchestrator/session-lock.contract.d.mts.map +1 -0
- package/esm/contracts/planner/index.d.mts +3 -2
- package/esm/contracts/planner/planner-config.type.d.mts +61 -0
- package/esm/contracts/planner/planner-config.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts +60 -1
- package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-result.type.d.mts +8 -0
- package/esm/contracts/planner/planner-result.type.d.mts.map +1 -1
- package/esm/contracts/planner/planner-snapshot.type.d.mts +77 -0
- package/esm/contracts/planner/planner-snapshot.type.d.mts.map +1 -0
- package/esm/contracts/planner/planner.contract.d.mts +21 -1
- package/esm/contracts/planner/planner.contract.d.mts.map +1 -1
- package/esm/contracts/result/agent-result.type.d.mts +6 -4
- package/esm/contracts/result/agent-result.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.d.mts +21 -3
- package/esm/contracts/result/base-report.type.d.mts.map +1 -1
- package/esm/contracts/result/base-report.type.mjs.map +1 -1
- package/esm/contracts/result/execution-report.type.d.mts +53 -1
- package/esm/contracts/result/execution-report.type.d.mts.map +1 -1
- package/esm/contracts/result/supervisor-result.type.d.mts +14 -2
- package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
- package/esm/contracts/result/workflow-result.type.d.mts +2 -1
- package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
- package/esm/contracts/sdk-adapter.contract.d.mts +37 -0
- package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -1
- package/esm/contracts/speech-model.contract.d.mts +97 -0
- package/esm/contracts/speech-model.contract.d.mts.map +1 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts +29 -0
- package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
- package/esm/contracts/system-prompt.contract.d.mts +103 -1
- package/esm/contracts/system-prompt.contract.d.mts.map +1 -1
- package/esm/contracts/team/index.d.mts +1 -0
- package/esm/contracts/team/team-config.type.d.mts +127 -0
- package/esm/contracts/team/team-config.type.d.mts.map +1 -0
- package/esm/contracts/tool.contract.d.mts +4 -2
- package/esm/contracts/tool.contract.d.mts.map +1 -1
- package/esm/contracts/transcription-model.contract.d.mts +101 -0
- package/esm/contracts/transcription-model.contract.d.mts.map +1 -0
- package/esm/contracts/workflow/step.contract.d.mts +30 -5
- package/esm/contracts/workflow/step.contract.d.mts.map +1 -1
- package/esm/contracts/workflow/workflow.contract.d.mts +16 -0
- package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
- package/esm/errors/agent-drift-error.d.mts +32 -0
- package/esm/errors/agent-drift-error.d.mts.map +1 -0
- package/esm/errors/agent-drift-error.mjs +31 -0
- package/esm/errors/agent-drift-error.mjs.map +1 -0
- package/esm/errors/error-code.type.d.mts +1 -1
- package/esm/errors/index.d.mts +3 -0
- package/esm/errors/index.mjs +3 -0
- package/esm/errors/outbound-policy-error.d.mts +27 -0
- package/esm/errors/outbound-policy-error.d.mts.map +1 -0
- package/esm/errors/outbound-policy-error.mjs +32 -0
- package/esm/errors/outbound-policy-error.mjs.map +1 -0
- package/esm/errors/planner-drift-error.d.mts +34 -0
- package/esm/errors/planner-drift-error.d.mts.map +1 -0
- package/esm/errors/planner-drift-error.mjs +33 -0
- package/esm/errors/planner-drift-error.mjs.map +1 -0
- package/esm/eval/dataset.d.mts +28 -0
- package/esm/eval/dataset.d.mts.map +1 -0
- package/esm/eval/dataset.mjs +112 -0
- package/esm/eval/dataset.mjs.map +1 -0
- package/esm/eval/dataset.type.d.mts +53 -0
- package/esm/eval/dataset.type.d.mts.map +1 -0
- package/esm/eval/eval-runner.d.mts.map +1 -1
- package/esm/eval/eval-runner.mjs +16 -2
- package/esm/eval/eval-runner.mjs.map +1 -1
- package/esm/eval/index.d.mts +20 -1
- package/esm/eval/index.d.mts.map +1 -1
- package/esm/eval/index.mjs +20 -2
- package/esm/eval/index.mjs.map +1 -1
- package/esm/eval/regression.d.mts +30 -0
- package/esm/eval/regression.d.mts.map +1 -0
- package/esm/eval/regression.mjs +51 -0
- package/esm/eval/regression.mjs.map +1 -0
- package/esm/eval/report-json.d.mts +30 -0
- package/esm/eval/report-json.d.mts.map +1 -0
- package/esm/eval/report-json.mjs +33 -0
- package/esm/eval/report-json.mjs.map +1 -0
- package/esm/eval/report-junit.d.mts +22 -0
- package/esm/eval/report-junit.d.mts.map +1 -0
- package/esm/eval/report-junit.mjs +60 -0
- package/esm/eval/report-junit.mjs.map +1 -0
- package/esm/guard/contracts/guard-options.type.d.mts +165 -0
- package/esm/guard/contracts/guard-options.type.d.mts.map +1 -0
- package/esm/guard/contracts/guardrail.contract.d.mts +78 -0
- package/esm/guard/contracts/guardrail.contract.d.mts.map +1 -0
- package/esm/guard/contracts/index.d.mts +4 -0
- package/esm/guard/contracts/openai-client.contract.d.mts +51 -0
- package/esm/guard/contracts/openai-client.contract.d.mts.map +1 -0
- package/esm/guard/contracts/verdict.type.d.mts +76 -0
- package/esm/guard/contracts/verdict.type.d.mts.map +1 -0
- package/esm/guard/detectors/index.d.mts +4 -0
- package/esm/guard/detectors/index.mjs +6 -0
- package/esm/guard/detectors/injection.d.mts +34 -0
- package/esm/guard/detectors/injection.d.mts.map +1 -0
- package/esm/guard/detectors/injection.mjs +254 -0
- package/esm/guard/detectors/injection.mjs.map +1 -0
- package/esm/guard/detectors/moderation.d.mts +32 -0
- package/esm/guard/detectors/moderation.d.mts.map +1 -0
- package/esm/guard/detectors/moderation.mjs +134 -0
- package/esm/guard/detectors/moderation.mjs.map +1 -0
- package/esm/guard/detectors/pii.d.mts +41 -0
- package/esm/guard/detectors/pii.d.mts.map +1 -0
- package/esm/guard/detectors/pii.mjs +199 -0
- package/esm/guard/detectors/pii.mjs.map +1 -0
- package/esm/guard/detectors/topic.d.mts +29 -0
- package/esm/guard/detectors/topic.d.mts.map +1 -0
- package/esm/guard/detectors/topic.mjs +99 -0
- package/esm/guard/detectors/topic.mjs.map +1 -0
- package/esm/guard/errors.d.mts +12 -0
- package/esm/guard/errors.d.mts.map +1 -0
- package/esm/guard/errors.mjs +18 -0
- package/esm/guard/errors.mjs.map +1 -0
- package/esm/guard/guard.d.mts +67 -0
- package/esm/guard/guard.d.mts.map +1 -0
- package/esm/guard/guard.mjs +209 -0
- package/esm/guard/guard.mjs.map +1 -0
- package/esm/guard/guardrail.d.mts +39 -0
- package/esm/guard/guardrail.d.mts.map +1 -0
- package/esm/guard/guardrail.mjs +22 -0
- package/esm/guard/guardrail.mjs.map +1 -0
- package/esm/human/contracts/approval.type.d.mts +154 -0
- package/esm/human/contracts/approval.type.d.mts.map +1 -0
- package/esm/human/contracts/human-approval.type.d.mts +38 -0
- package/esm/human/contracts/human-approval.type.d.mts.map +1 -0
- package/esm/human/contracts/index.d.mts +4 -0
- package/esm/human/contracts/interrupt-store.contract.d.mts +112 -0
- package/esm/human/contracts/interrupt-store.contract.d.mts.map +1 -0
- package/esm/human/contracts/resume.type.d.mts +77 -0
- package/esm/human/contracts/resume.type.d.mts.map +1 -0
- package/esm/human/errors.d.mts +84 -0
- package/esm/human/errors.d.mts.map +1 -0
- package/esm/human/errors.mjs +60 -0
- package/esm/human/errors.mjs.map +1 -0
- package/esm/human/human-approval.d.mts +57 -0
- package/esm/human/human-approval.d.mts.map +1 -0
- package/esm/human/human-approval.mjs +170 -0
- package/esm/human/human-approval.mjs.map +1 -0
- package/esm/human/policy.d.mts +55 -0
- package/esm/human/policy.d.mts.map +1 -0
- package/esm/human/policy.mjs +67 -0
- package/esm/human/policy.mjs.map +1 -0
- package/esm/human/register.mjs +37 -0
- package/esm/human/register.mjs.map +1 -0
- package/esm/human/resume-seed.mjs +53 -0
- package/esm/human/resume-seed.mjs.map +1 -0
- package/esm/human/resume.d.mts +54 -0
- package/esm/human/resume.d.mts.map +1 -0
- package/esm/human/resume.mjs +121 -0
- package/esm/human/resume.mjs.map +1 -0
- package/esm/human/stores/index.mjs +5 -0
- package/esm/human/stores/memory.d.mts +30 -0
- package/esm/human/stores/memory.d.mts.map +1 -0
- package/esm/human/stores/memory.mjs +91 -0
- package/esm/human/stores/memory.mjs.map +1 -0
- package/esm/human/stores/pg.d.mts +59 -0
- package/esm/human/stores/pg.d.mts.map +1 -0
- package/esm/human/stores/pg.mjs +220 -0
- package/esm/human/stores/pg.mjs.map +1 -0
- package/esm/human/stores/redis.d.mts +56 -0
- package/esm/human/stores/redis.d.mts.map +1 -0
- package/esm/human/stores/redis.mjs +201 -0
- package/esm/human/stores/redis.mjs.map +1 -0
- package/esm/image/image-cost.d.mts +32 -0
- package/esm/image/image-cost.d.mts.map +1 -0
- package/esm/image/image-cost.mjs +55 -0
- package/esm/image/image-cost.mjs.map +1 -0
- package/esm/image/image.d.mts +92 -0
- package/esm/image/image.d.mts.map +1 -0
- package/esm/image/image.mjs +113 -0
- package/esm/image/image.mjs.map +1 -0
- package/esm/image/index.mjs +4 -0
- package/esm/index.d.mts +137 -24
- package/esm/index.mjs +101 -11
- package/esm/middleware/builtins/budget.mjs +6 -2
- package/esm/middleware/builtins/budget.mjs.map +1 -1
- package/esm/middleware/utils/extract-user-text.d.mts +8 -1
- package/esm/middleware/utils/extract-user-text.d.mts.map +1 -1
- package/esm/middleware/utils/extract-user-text.mjs +8 -1
- package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
- package/esm/mock/index.d.mts +3 -0
- package/esm/mock/index.mjs +3 -0
- package/esm/mock/mock-config.type.d.mts +22 -0
- package/esm/mock/mock-config.type.d.mts.map +1 -1
- package/esm/mock/mock-image-model.d.mts +41 -0
- package/esm/mock/mock-image-model.d.mts.map +1 -0
- package/esm/mock/mock-image-model.mjs +52 -0
- package/esm/mock/mock-image-model.mjs.map +1 -0
- package/esm/mock/mock-sdk.d.mts +7 -1
- package/esm/mock/mock-sdk.d.mts.map +1 -1
- package/esm/mock/mock-sdk.mjs +27 -0
- package/esm/mock/mock-sdk.mjs.map +1 -1
- package/esm/mock/mock-speech-model.d.mts +31 -0
- package/esm/mock/mock-speech-model.d.mts.map +1 -0
- package/esm/mock/mock-speech-model.mjs +39 -0
- package/esm/mock/mock-speech-model.mjs.map +1 -0
- package/esm/mock/mock-transcription-model.d.mts +32 -0
- package/esm/mock/mock-transcription-model.d.mts.map +1 -0
- package/esm/mock/mock-transcription-model.mjs +36 -0
- package/esm/mock/mock-transcription-model.mjs.map +1 -0
- package/esm/object-stream/index.d.mts +2 -0
- package/esm/object-stream/index.mjs +4 -0
- package/esm/object-stream/parse-partial-json.d.mts +22 -0
- package/esm/object-stream/parse-partial-json.d.mts.map +1 -0
- package/esm/object-stream/parse-partial-json.mjs +78 -0
- package/esm/object-stream/parse-partial-json.mjs.map +1 -0
- package/esm/object-stream/stream-object.d.mts +68 -0
- package/esm/object-stream/stream-object.d.mts.map +1 -0
- package/esm/object-stream/stream-object.mjs +104 -0
- package/esm/object-stream/stream-object.mjs.map +1 -0
- package/esm/observe/index.mjs +4 -0
- package/esm/observe/observer-registry.d.mts +30 -0
- package/esm/observe/observer-registry.d.mts.map +1 -0
- package/esm/observe/observer-registry.mjs +51 -0
- package/esm/observe/observer-registry.mjs.map +1 -0
- package/esm/observe/observer.contract.d.mts +40 -0
- package/esm/observe/observer.contract.d.mts.map +1 -0
- package/esm/observe/resolve-observers.d.mts +40 -0
- package/esm/observe/resolve-observers.d.mts.map +1 -0
- package/esm/observe/resolve-observers.mjs +73 -0
- package/esm/observe/resolve-observers.mjs.map +1 -0
- package/esm/orchestrator/execution.d.mts.map +1 -1
- package/esm/orchestrator/execution.mjs +5 -2
- package/esm/orchestrator/execution.mjs.map +1 -1
- package/esm/orchestrator/index.d.mts +1 -0
- package/esm/orchestrator/index.mjs +1 -0
- package/esm/orchestrator/orchestrator.d.mts.map +1 -1
- package/esm/orchestrator/orchestrator.mjs +39 -6
- package/esm/orchestrator/orchestrator.mjs.map +1 -1
- package/esm/orchestrator/session-lock.d.mts +25 -0
- package/esm/orchestrator/session-lock.d.mts.map +1 -0
- package/esm/orchestrator/session-lock.mjs +83 -0
- package/esm/orchestrator/session-lock.mjs.map +1 -0
- package/esm/planner/dag-scheduler.mjs +97 -0
- package/esm/planner/dag-scheduler.mjs.map +1 -0
- package/esm/planner/plan-prompt.d.mts +1 -1
- package/esm/planner/plan-prompt.d.mts.map +1 -1
- package/esm/planner/plan-prompt.mjs +2 -1
- package/esm/planner/plan-prompt.mjs.map +1 -1
- package/esm/planner/planner-run.d.mts +8 -0
- package/esm/planner/planner-run.d.mts.map +1 -1
- package/esm/planner/planner-run.mjs +457 -31
- package/esm/planner/planner-run.mjs.map +1 -1
- package/esm/planner/planner.d.mts.map +1 -1
- package/esm/planner/planner.mjs +26 -2
- package/esm/planner/planner.mjs.map +1 -1
- package/esm/planner/snapshot.mjs +95 -0
- package/esm/planner/snapshot.mjs.map +1 -0
- package/esm/prompt/errors.d.mts +57 -0
- package/esm/prompt/errors.d.mts.map +1 -0
- package/esm/prompt/errors.mjs +73 -0
- package/esm/prompt/errors.mjs.map +1 -0
- package/esm/prompt/index.d.mts +3 -0
- package/esm/prompt/index.mjs +4 -0
- package/esm/prompt/prompt-langfuse-sync.mjs +104 -0
- package/esm/prompt/prompt-langfuse-sync.mjs.map +1 -0
- package/esm/prompt/prompt-langfuse-sync.type.d.mts +32 -0
- package/esm/prompt/prompt-langfuse-sync.type.d.mts.map +1 -0
- package/esm/prompt/prompt-validate.mjs +170 -0
- package/esm/prompt/prompt-validate.mjs.map +1 -0
- package/esm/prompt/prompt.d.mts +54 -0
- package/esm/prompt/prompt.d.mts.map +1 -0
- package/esm/prompt/prompt.mjs +218 -0
- package/esm/prompt/prompt.mjs.map +1 -0
- package/esm/prompt/prompt.type.d.mts +174 -0
- package/esm/prompt/prompt.type.d.mts.map +1 -0
- package/esm/prompts/index.d.mts +3 -0
- package/esm/prompts/index.mjs +3 -0
- package/esm/prompts/prompts-manager.contract.d.mts +154 -0
- package/esm/prompts/prompts-manager.contract.d.mts.map +1 -0
- package/esm/prompts/prompts-manager.d.mts +38 -0
- package/esm/prompts/prompts-manager.d.mts.map +1 -0
- package/esm/prompts/prompts-manager.mjs +410 -0
- package/esm/prompts/prompts-manager.mjs.map +1 -0
- package/esm/prompts/prompts-manager.type.d.mts +172 -0
- package/esm/prompts/prompts-manager.type.d.mts.map +1 -0
- package/esm/prompts/prompts-validate.mjs +200 -0
- package/esm/prompts/prompts-validate.mjs.map +1 -0
- package/esm/rag/as-tool.mjs +48 -0
- package/esm/rag/as-tool.mjs.map +1 -0
- package/esm/rag/chunk/chunk.d.mts +24 -0
- package/esm/rag/chunk/chunk.d.mts.map +1 -0
- package/esm/rag/chunk/chunk.mjs +44 -0
- package/esm/rag/chunk/chunk.mjs.map +1 -0
- package/esm/rag/chunk/fixed.mjs +32 -0
- package/esm/rag/chunk/fixed.mjs.map +1 -0
- package/esm/rag/chunk/markdown.mjs +75 -0
- package/esm/rag/chunk/markdown.mjs.map +1 -0
- package/esm/rag/chunk/recursive.mjs +132 -0
- package/esm/rag/chunk/recursive.mjs.map +1 -0
- package/esm/rag/chunk/sentence.mjs +73 -0
- package/esm/rag/chunk/sentence.mjs.map +1 -0
- package/esm/rag/contracts/chunk-options.type.d.mts +35 -0
- package/esm/rag/contracts/chunk-options.type.d.mts.map +1 -0
- package/esm/rag/contracts/citation.type.d.mts +35 -0
- package/esm/rag/contracts/citation.type.d.mts.map +1 -0
- package/esm/rag/contracts/index.d.mts +4 -0
- package/esm/rag/contracts/rag-config.type.d.mts +68 -0
- package/esm/rag/contracts/rag-config.type.d.mts.map +1 -0
- package/esm/rag/contracts/rag-document.type.d.mts +21 -0
- package/esm/rag/contracts/rag-document.type.d.mts.map +1 -0
- package/esm/rag/hybrid/bm25.d.mts +23 -0
- package/esm/rag/hybrid/bm25.d.mts.map +1 -0
- package/esm/rag/hybrid/bm25.mjs +51 -0
- package/esm/rag/hybrid/bm25.mjs.map +1 -0
- package/esm/rag/hybrid/hybrid-rank.d.mts +33 -0
- package/esm/rag/hybrid/hybrid-rank.d.mts.map +1 -0
- package/esm/rag/hybrid/hybrid-rank.mjs +29 -0
- package/esm/rag/hybrid/hybrid-rank.mjs.map +1 -0
- package/esm/rag/hybrid/rrf.d.mts +25 -0
- package/esm/rag/hybrid/rrf.d.mts.map +1 -0
- package/esm/rag/hybrid/rrf.mjs +30 -0
- package/esm/rag/hybrid/rrf.mjs.map +1 -0
- package/esm/rag/index.d.mts +22 -0
- package/esm/rag/index.mjs +18 -0
- package/esm/rag/loaders/errors.d.mts +19 -0
- package/esm/rag/loaders/errors.d.mts.map +1 -0
- package/esm/rag/loaders/errors.mjs +25 -0
- package/esm/rag/loaders/errors.mjs.map +1 -0
- package/esm/rag/loaders/index.mjs +7 -0
- package/esm/rag/loaders/load-html.d.mts +26 -0
- package/esm/rag/loaders/load-html.d.mts.map +1 -0
- package/esm/rag/loaders/load-html.mjs +138 -0
- package/esm/rag/loaders/load-html.mjs.map +1 -0
- package/esm/rag/loaders/load-pdf.d.mts +38 -0
- package/esm/rag/loaders/load-pdf.d.mts.map +1 -0
- package/esm/rag/loaders/load-pdf.mjs +150 -0
- package/esm/rag/loaders/load-pdf.mjs.map +1 -0
- package/esm/rag/loaders/load-text.d.mts +47 -0
- package/esm/rag/loaders/load-text.d.mts.map +1 -0
- package/esm/rag/loaders/load-text.mjs +60 -0
- package/esm/rag/loaders/load-text.mjs.map +1 -0
- package/esm/rag/loaders/load-web.d.mts +42 -0
- package/esm/rag/loaders/load-web.d.mts.map +1 -0
- package/esm/rag/loaders/load-web.mjs +89 -0
- package/esm/rag/loaders/load-web.mjs.map +1 -0
- package/esm/rag/loaders/loader.type.d.mts +89 -0
- package/esm/rag/loaders/loader.type.d.mts.map +1 -0
- package/esm/rag/rag.d.mts +38 -0
- package/esm/rag/rag.d.mts.map +1 -0
- package/esm/rag/rag.mjs +126 -0
- package/esm/rag/rag.mjs.map +1 -0
- package/esm/rag/rerank/keyword-reranker.d.mts +32 -0
- package/esm/rag/rerank/keyword-reranker.d.mts.map +1 -0
- package/esm/rag/rerank/keyword-reranker.mjs +58 -0
- package/esm/rag/rerank/keyword-reranker.mjs.map +1 -0
- package/esm/rag/rerank/llm-reranker.d.mts +36 -0
- package/esm/rag/rerank/llm-reranker.d.mts.map +1 -0
- package/esm/rag/rerank/llm-reranker.mjs +85 -0
- package/esm/rag/rerank/llm-reranker.mjs.map +1 -0
- package/esm/rag/rerank/reranker.contract.d.mts +28 -0
- package/esm/rag/rerank/reranker.contract.d.mts.map +1 -0
- package/esm/rag/retrieve.mjs +68 -0
- package/esm/rag/retrieve.mjs.map +1 -0
- package/esm/rag/store/cache-vector-store.d.mts +27 -0
- package/esm/rag/store/cache-vector-store.d.mts.map +1 -0
- package/esm/rag/store/cache-vector-store.mjs +48 -0
- package/esm/rag/store/cache-vector-store.mjs.map +1 -0
- package/esm/rag/store/pg-vector-store.d.mts +139 -0
- package/esm/rag/store/pg-vector-store.d.mts.map +1 -0
- package/esm/rag/store/pg-vector-store.mjs +328 -0
- package/esm/rag/store/pg-vector-store.mjs.map +1 -0
- package/esm/rag/store/vector-store.contract.d.mts +38 -0
- package/esm/rag/store/vector-store.contract.d.mts.map +1 -0
- package/esm/rag/transforms/multi-query.d.mts +27 -0
- package/esm/rag/transforms/multi-query.d.mts.map +1 -0
- package/esm/rag/transforms/multi-query.mjs +41 -0
- package/esm/rag/transforms/multi-query.mjs.map +1 -0
- package/esm/security/index.mjs +5 -0
- package/esm/security/outbound-policy.d.mts +46 -0
- package/esm/security/outbound-policy.d.mts.map +1 -0
- package/esm/security/outbound-policy.mjs +187 -0
- package/esm/security/outbound-policy.mjs.map +1 -0
- package/esm/security/outbound-policy.type.d.mts +74 -0
- package/esm/security/outbound-policy.type.d.mts.map +1 -0
- package/esm/security/private-ip.d.mts +15 -0
- package/esm/security/private-ip.d.mts.map +1 -0
- package/esm/security/private-ip.mjs +48 -0
- package/esm/security/private-ip.mjs.map +1 -0
- package/esm/security/redact.d.mts +59 -0
- package/esm/security/redact.d.mts.map +1 -0
- package/esm/security/redact.mjs +122 -0
- package/esm/security/redact.mjs.map +1 -0
- package/esm/serve/serve.d.mts +50 -0
- package/esm/serve/serve.d.mts.map +1 -0
- package/esm/serve/serve.mjs +90 -0
- package/esm/serve/serve.mjs.map +1 -0
- package/esm/serve/sse.d.mts +20 -0
- package/esm/serve/sse.d.mts.map +1 -0
- package/esm/serve/sse.mjs +25 -0
- package/esm/serve/sse.mjs.map +1 -0
- package/esm/serve/stream-to-sse.d.mts +29 -0
- package/esm/serve/stream-to-sse.d.mts.map +1 -0
- package/esm/serve/stream-to-sse.mjs +37 -0
- package/esm/serve/stream-to-sse.mjs.map +1 -0
- package/esm/skills/catalog.d.mts +49 -0
- package/esm/skills/catalog.d.mts.map +1 -0
- package/esm/skills/catalog.mjs +140 -0
- package/esm/skills/catalog.mjs.map +1 -0
- package/esm/skills/contracts/skill-record.type.d.mts +37 -0
- package/esm/skills/contracts/skill-record.type.d.mts.map +1 -0
- package/esm/skills/contracts/skills-config.type.d.mts +108 -0
- package/esm/skills/contracts/skills-config.type.d.mts.map +1 -0
- package/esm/skills/contracts/skills-store.contract.d.mts +28 -0
- package/esm/skills/contracts/skills-store.contract.d.mts.map +1 -0
- package/esm/skills/contracts/skills.contract.d.mts +43 -0
- package/esm/skills/contracts/skills.contract.d.mts.map +1 -0
- package/esm/skills/index.d.mts +16 -0
- package/esm/skills/index.mjs +14 -0
- package/esm/skills/load-skill-tool.d.mts +38 -0
- package/esm/skills/load-skill-tool.d.mts.map +1 -0
- package/esm/skills/load-skill-tool.mjs +65 -0
- package/esm/skills/load-skill-tool.mjs.map +1 -0
- package/esm/skills/review-gate.d.mts +33 -0
- package/esm/skills/review-gate.d.mts.map +1 -0
- package/esm/skills/review-gate.mjs +60 -0
- package/esm/skills/review-gate.mjs.map +1 -0
- package/esm/skills/save-skill-tool.d.mts +39 -0
- package/esm/skills/save-skill-tool.d.mts.map +1 -0
- package/esm/skills/save-skill-tool.mjs +65 -0
- package/esm/skills/save-skill-tool.mjs.map +1 -0
- package/esm/skills/skills.d.mts +33 -0
- package/esm/skills/skills.d.mts.map +1 -0
- package/esm/skills/skills.mjs +109 -0
- package/esm/skills/skills.mjs.map +1 -0
- package/esm/skills/sources/directory-source.d.mts +19 -0
- package/esm/skills/sources/directory-source.d.mts.map +1 -0
- package/esm/skills/sources/directory-source.mjs +108 -0
- package/esm/skills/sources/directory-source.mjs.map +1 -0
- package/esm/skills/sources/index.d.mts +18 -0
- package/esm/skills/sources/index.d.mts.map +1 -0
- package/esm/skills/sources/index.mjs +27 -0
- package/esm/skills/sources/index.mjs.map +1 -0
- package/esm/skills/sources/parse-frontmatter.d.mts +27 -0
- package/esm/skills/sources/parse-frontmatter.d.mts.map +1 -0
- package/esm/skills/sources/parse-frontmatter.mjs +46 -0
- package/esm/skills/sources/parse-frontmatter.mjs.map +1 -0
- package/esm/skills/sources/store-source.d.mts +14 -0
- package/esm/skills/sources/store-source.d.mts.map +1 -0
- package/esm/skills/sources/store-source.mjs +15 -0
- package/esm/skills/sources/store-source.mjs.map +1 -0
- package/esm/skills/sources/url-source.d.mts +29 -0
- package/esm/skills/sources/url-source.d.mts.map +1 -0
- package/esm/skills/sources/url-source.mjs +117 -0
- package/esm/skills/sources/url-source.mjs.map +1 -0
- package/esm/skills/store/mock-skills-store.d.mts +57 -0
- package/esm/skills/store/mock-skills-store.d.mts.map +1 -0
- package/esm/skills/store/mock-skills-store.mjs +100 -0
- package/esm/skills/store/mock-skills-store.mjs.map +1 -0
- package/esm/skills/store/procedural-skill-store.d.mts +30 -0
- package/esm/skills/store/procedural-skill-store.d.mts.map +1 -0
- package/esm/skills/store/procedural-skill-store.mjs +125 -0
- package/esm/skills/store/procedural-skill-store.mjs.map +1 -0
- package/esm/speech/index.mjs +3 -0
- package/esm/speech/speech.d.mts +65 -0
- package/esm/speech/speech.d.mts.map +1 -0
- package/esm/speech/speech.mjs +123 -0
- package/esm/speech/speech.mjs.map +1 -0
- package/esm/supervisor/as-tool.mjs +2 -2
- package/esm/supervisor/as-tool.mjs.map +1 -1
- package/esm/supervisor/entries.mjs +2 -2
- package/esm/supervisor/entries.mjs.map +1 -1
- package/esm/supervisor/execution.d.mts.map +1 -1
- package/esm/supervisor/execution.mjs +31 -28
- package/esm/supervisor/execution.mjs.map +1 -1
- package/esm/supervisor/supervisor.d.mts.map +1 -1
- package/esm/supervisor/supervisor.mjs +8 -3
- package/esm/supervisor/supervisor.mjs.map +1 -1
- package/esm/system-prompt/index.d.mts +4 -0
- package/esm/system-prompt/system-prompt.d.mts +68 -4
- package/esm/system-prompt/system-prompt.d.mts.map +1 -1
- package/esm/system-prompt/system-prompt.mjs +89 -5
- package/esm/system-prompt/system-prompt.mjs.map +1 -1
- package/esm/team/gates.mjs +48 -0
- package/esm/team/gates.mjs.map +1 -0
- package/esm/team/index.d.mts +1 -0
- package/esm/team/index.mjs +3 -0
- package/esm/team/team.d.mts +42 -0
- package/esm/team/team.d.mts.map +1 -0
- package/esm/team/team.mjs +94 -0
- package/esm/team/team.mjs.map +1 -0
- package/esm/tool/executable-as-tool.d.mts.map +1 -1
- package/esm/tool/executable-as-tool.mjs +2 -2
- package/esm/tool/executable-as-tool.mjs.map +1 -1
- package/esm/tool/tool.d.mts.map +1 -1
- package/esm/tool/tool.mjs +2 -2
- package/esm/tool/tool.mjs.map +1 -1
- package/esm/transcribe/audio-input.d.mts +47 -0
- package/esm/transcribe/audio-input.d.mts.map +1 -0
- package/esm/transcribe/audio-input.mjs +84 -0
- package/esm/transcribe/audio-input.mjs.map +1 -0
- package/esm/transcribe/index.mjs +4 -0
- package/esm/transcribe/transcribe.d.mts +64 -0
- package/esm/transcribe/transcribe.d.mts.map +1 -0
- package/esm/transcribe/transcribe.mjs +128 -0
- package/esm/transcribe/transcribe.mjs.map +1 -0
- package/esm/utils/compute-cost.d.mts +17 -1
- package/esm/utils/compute-cost.d.mts.map +1 -1
- package/esm/utils/compute-cost.mjs +26 -1
- package/esm/utils/compute-cost.mjs.map +1 -1
- package/esm/utils/extract-json-lenient.d.mts +42 -0
- package/esm/utils/extract-json-lenient.d.mts.map +1 -0
- package/esm/utils/extract-json-lenient.mjs +97 -0
- package/esm/utils/extract-json-lenient.mjs.map +1 -0
- package/esm/utils/index.d.mts +4 -2
- package/esm/utils/index.mjs +3 -1
- package/esm/utils/json-schema.d.mts +1 -1
- package/esm/utils/prepare-attachment-part.d.mts +10 -1
- package/esm/utils/prepare-attachment-part.d.mts.map +1 -1
- package/esm/utils/prepare-attachment-part.mjs +103 -11
- package/esm/utils/prepare-attachment-part.mjs.map +1 -1
- package/esm/utils/resolve-attachment.d.mts +4 -3
- package/esm/utils/resolve-attachment.d.mts.map +1 -1
- package/esm/utils/resolve-attachment.mjs +4 -3
- package/esm/utils/resolve-attachment.mjs.map +1 -1
- package/esm/utils/run-context.d.mts +94 -0
- package/esm/utils/run-context.d.mts.map +1 -0
- package/esm/utils/run-context.mjs +98 -0
- package/esm/utils/run-context.mjs.map +1 -0
- package/esm/vcr/cassette-io.mjs +57 -0
- package/esm/vcr/cassette-io.mjs.map +1 -0
- package/esm/vcr/errors.d.mts +42 -0
- package/esm/vcr/errors.d.mts.map +1 -0
- package/esm/vcr/errors.mjs +37 -0
- package/esm/vcr/errors.mjs.map +1 -0
- package/esm/vcr/hash-request.d.mts +28 -0
- package/esm/vcr/hash-request.d.mts.map +1 -0
- package/esm/vcr/hash-request.mjs +118 -0
- package/esm/vcr/hash-request.mjs.map +1 -0
- package/esm/vcr/index.d.mts +4 -0
- package/esm/vcr/index.mjs +5 -0
- package/esm/vcr/vcr.d.mts +32 -0
- package/esm/vcr/vcr.d.mts.map +1 -0
- package/esm/vcr/vcr.mjs +248 -0
- package/esm/vcr/vcr.mjs.map +1 -0
- package/esm/vcr/vcr.type.d.mts +118 -0
- package/esm/vcr/vcr.type.d.mts.map +1 -0
- package/esm/workflow/as-tool.mjs +2 -2
- package/esm/workflow/as-tool.mjs.map +1 -1
- package/esm/workflow/engine.mjs +1 -0
- package/esm/workflow/engine.mjs.map +1 -1
- package/esm/workflow/step-runner.mjs +19 -20
- package/esm/workflow/step-runner.mjs.map +1 -1
- package/esm/workflow/workflow.d.mts.map +1 -1
- package/esm/workflow/workflow.mjs +8 -3
- package/esm/workflow/workflow.mjs.map +1 -1
- package/llms-full.txt +2572 -204
- package/llms.txt +21 -4
- package/package.json +7 -3
- package/skills/README.md +44 -4
- package/skills/ai-dx-helpers/SKILL.md +2 -2
- package/skills/approve-tool-calls/SKILL.md +134 -0
- package/skills/attach-ai-middleware/SKILL.md +1 -1
- package/skills/detect-and-redact-pii/SKILL.md +104 -0
- package/skills/durable-agent-runs/SKILL.md +135 -0
- package/skills/durable-resume/SKILL.md +128 -0
- package/skills/escalate-block-to-human/SKILL.md +85 -0
- package/skills/eval-datasets-and-ci/SKILL.md +117 -0
- package/skills/generate-images/SKILL.md +138 -0
- package/skills/generate-speech/SKILL.md +139 -0
- package/skills/guard-input-output/SKILL.md +117 -0
- package/skills/manage-prompts/SKILL.md +186 -0
- package/skills/observe-ai-flows/SKILL.md +94 -0
- package/skills/rag-loaders-and-stores/SKILL.md +164 -0
- package/skills/record-replay-llm/SKILL.md +92 -0
- package/skills/run-ai-agent/SKILL.md +26 -1
- package/skills/run-ai-rag/SKILL.md +139 -0
- package/skills/run-ai-team/SKILL.md +107 -0
- package/skills/run-orchestrator/SKILL.md +2 -0
- package/skills/run-planner/SKILL.md +73 -8
- package/skills/run-supervisor/SKILL.md +20 -1
- package/skills/transcribe-audio/SKILL.md +157 -0
- package/skills/use-runtime-skills/SKILL.md +106 -0
- package/skills/write-system-prompt/SKILL.md +30 -1
- package/cjs/index.cjs.map +0 -1
- package/esm/contracts/result/index.d.mts +0 -15
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-html.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-html.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAiKgB,QAAA,CACd,IAAA,UACA,OAAA,GAAS,eAAA,GACR,eAAe"}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-html.ts
|
|
2
|
+
/** Default `id` when the caller supplies none. */
|
|
3
|
+
const DEFAULT_ID = "document";
|
|
4
|
+
/**
|
|
5
|
+
* Elements whose *content* is not human-readable text and must be removed
|
|
6
|
+
* wholesale (open tag → close tag → everything in between) before tags are
|
|
7
|
+
* stripped. `script` / `style` would otherwise leak code into the chunked
|
|
8
|
+
* text; `noscript` / `template` / `head` / `svg` are non-prose noise.
|
|
9
|
+
*/
|
|
10
|
+
const STRIPPED_ELEMENTS = [
|
|
11
|
+
"script",
|
|
12
|
+
"style",
|
|
13
|
+
"noscript",
|
|
14
|
+
"template",
|
|
15
|
+
"head",
|
|
16
|
+
"svg"
|
|
17
|
+
];
|
|
18
|
+
/**
|
|
19
|
+
* Block-level tags that imply a line break in the readable text. Replacing
|
|
20
|
+
* them with `\n` BEFORE the generic tag strip keeps paragraph / list / table
|
|
21
|
+
* structure (so the recursive splitter still sees `\n\n` boundaries) instead
|
|
22
|
+
* of collapsing the whole page onto one line.
|
|
23
|
+
*/
|
|
24
|
+
const BLOCK_TAGS = /<\/?(?:p|div|section|article|header|footer|main|aside|nav|h[1-6]|ul|ol|li|table|tr|td|th|thead|tbody|blockquote|pre|hr|br)\b[^>]*>/gi;
|
|
25
|
+
/** Named HTML entities common in prose. Numeric entities are decoded generically. */
|
|
26
|
+
const NAMED_ENTITIES = {
|
|
27
|
+
amp: "&",
|
|
28
|
+
lt: "<",
|
|
29
|
+
gt: ">",
|
|
30
|
+
quot: "\"",
|
|
31
|
+
apos: "'",
|
|
32
|
+
nbsp: " ",
|
|
33
|
+
copy: "©",
|
|
34
|
+
reg: "®",
|
|
35
|
+
trade: "™",
|
|
36
|
+
hellip: "…",
|
|
37
|
+
mdash: "—",
|
|
38
|
+
ndash: "–",
|
|
39
|
+
lsquo: "‘",
|
|
40
|
+
rsquo: "’",
|
|
41
|
+
ldquo: "“",
|
|
42
|
+
rdquo: "”",
|
|
43
|
+
laquo: "«",
|
|
44
|
+
raquo: "»",
|
|
45
|
+
middot: "·",
|
|
46
|
+
bull: "•"
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Decode the HTML entities that survive tag stripping: named (`&`),
|
|
50
|
+
* decimal (`©`), and hex (`©`). Unknown named entities are left
|
|
51
|
+
* verbatim rather than dropped, so unusual markup never silently loses text.
|
|
52
|
+
*/
|
|
53
|
+
function decodeEntities(text) {
|
|
54
|
+
return text.replace(/&(#x?[0-9a-f]+|[a-z][a-z0-9]*);/gi, (match, body) => {
|
|
55
|
+
if (body[0] === "#") {
|
|
56
|
+
const codePoint = body[1] === "x" || body[1] === "X" ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);
|
|
57
|
+
if (Number.isNaN(codePoint) || codePoint < 0 || codePoint > 1114111) return match;
|
|
58
|
+
try {
|
|
59
|
+
return String.fromCodePoint(codePoint);
|
|
60
|
+
} catch {
|
|
61
|
+
return match;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return NAMED_ENTITIES[body.toLowerCase()] ?? match;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Pull the `<title>` text out of the document, decoded and trimmed, or
|
|
69
|
+
* `undefined` when there is none. Read BEFORE `<head>` is stripped.
|
|
70
|
+
*/
|
|
71
|
+
function extractTitle(html) {
|
|
72
|
+
const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
|
|
73
|
+
if (!match) return;
|
|
74
|
+
const title = decodeEntities(match[1]).replace(/\s+/g, " ").trim();
|
|
75
|
+
return title.length > 0 ? title : void 0;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Strip HTML markup down to readable plain text — a lightweight,
|
|
79
|
+
* dependency-free pass (no DOM parser): drop comments and non-prose elements
|
|
80
|
+
* (`script` / `style` / `head` / `svg` / …) content-and-all, convert block
|
|
81
|
+
* tags to line breaks to preserve paragraph structure, remove every
|
|
82
|
+
* remaining tag, decode entities, then collapse runs of whitespace while
|
|
83
|
+
* keeping blank-line paragraph separators.
|
|
84
|
+
*/
|
|
85
|
+
function htmlToText(html) {
|
|
86
|
+
let text = html;
|
|
87
|
+
text = text.replace(/<!--[\s\S]*?-->/g, " ");
|
|
88
|
+
for (const tag of STRIPPED_ELEMENTS) {
|
|
89
|
+
const element = new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/${tag}>`, "gi");
|
|
90
|
+
text = text.replace(element, " ");
|
|
91
|
+
text = text.replace(new RegExp(`<\\/?${tag}\\b[^>]*>`, "gi"), " ");
|
|
92
|
+
}
|
|
93
|
+
text = text.replace(BLOCK_TAGS, "\n");
|
|
94
|
+
text = text.replace(/<[^>]+>/g, "");
|
|
95
|
+
text = decodeEntities(text);
|
|
96
|
+
text = text.replace(/[^\S\n]+/g, " ").replace(/[ \t]*\n[ \t]*/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
97
|
+
return text;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Load an HTML string into a single {@link RagDocument} of readable text.
|
|
101
|
+
* Scripts, styles, and other non-prose elements are dropped content-and-all,
|
|
102
|
+
* block tags become line breaks (so paragraph structure survives for the
|
|
103
|
+
* splitter), remaining tags are stripped, and HTML entities are decoded — a
|
|
104
|
+
* lightweight regex pass, no heavy DOM dependency.
|
|
105
|
+
*
|
|
106
|
+
* The document's `metadata.title` is set from the page's `<title>` (unless
|
|
107
|
+
* the caller overrode it), and `metadata.loader` is `"html"`. The output is
|
|
108
|
+
* the exact shape `index()` consumes.
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* const kb = ai.rag({ embedder, store });
|
|
112
|
+
* await kb.index(loadHtml(rawHtmlString, { id: "landing-page" }));
|
|
113
|
+
*
|
|
114
|
+
* @param html - The raw HTML markup.
|
|
115
|
+
* @param options - Shared `id` / `metadata` / `tags` ({@link LoadHtmlOptions}).
|
|
116
|
+
* @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.
|
|
117
|
+
*/
|
|
118
|
+
function loadHtml(html, options = {}) {
|
|
119
|
+
const id = options.id ?? DEFAULT_ID;
|
|
120
|
+
const title = extractTitle(html);
|
|
121
|
+
const text = htmlToText(html);
|
|
122
|
+
if (text.length === 0) return [];
|
|
123
|
+
return [{
|
|
124
|
+
id,
|
|
125
|
+
text,
|
|
126
|
+
metadata: {
|
|
127
|
+
source: id,
|
|
128
|
+
loader: "html",
|
|
129
|
+
...title !== void 0 ? { title } : {},
|
|
130
|
+
...options.metadata
|
|
131
|
+
},
|
|
132
|
+
tags: options.tags
|
|
133
|
+
}];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
//#endregion
|
|
137
|
+
export { extractTitle, htmlToText, loadHtml };
|
|
138
|
+
//# sourceMappingURL=load-html.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-html.mjs","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-html.ts"],"sourcesContent":["import type { RagDocument } from \"../contracts/rag-document.type\";\nimport type { LoadHtmlOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Default `id` when the caller supplies none. */\nconst DEFAULT_ID = \"document\";\n\n/**\n * Elements whose *content* is not human-readable text and must be removed\n * wholesale (open tag → close tag → everything in between) before tags are\n * stripped. `script` / `style` would otherwise leak code into the chunked\n * text; `noscript` / `template` / `head` / `svg` are non-prose noise.\n */\nconst STRIPPED_ELEMENTS = [\n \"script\",\n \"style\",\n \"noscript\",\n \"template\",\n \"head\",\n \"svg\",\n];\n\n/**\n * Block-level tags that imply a line break in the readable text. Replacing\n * them with `\\n` BEFORE the generic tag strip keeps paragraph / list / table\n * structure (so the recursive splitter still sees `\\n\\n` boundaries) instead\n * of collapsing the whole page onto one line.\n */\nconst BLOCK_TAGS =\n /<\\/?(?:p|div|section|article|header|footer|main|aside|nav|h[1-6]|ul|ol|li|table|tr|td|th|thead|tbody|blockquote|pre|hr|br)\\b[^>]*>/gi;\n\n/** Named HTML entities common in prose. Numeric entities are decoded generically. */\nconst NAMED_ENTITIES: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n copy: \"©\",\n reg: \"®\",\n trade: \"™\",\n hellip: \"…\",\n mdash: \"—\",\n ndash: \"–\",\n lsquo: \"‘\",\n rsquo: \"’\",\n ldquo: \"“\",\n rdquo: \"”\",\n laquo: \"«\",\n raquo: \"»\",\n middot: \"·\",\n bull: \"•\",\n};\n\n/**\n * Decode the HTML entities that survive tag stripping: named (`&`),\n * decimal (`©`), and hex (`©`). Unknown named entities are left\n * verbatim rather than dropped, so unusual markup never silently loses text.\n */\nfunction decodeEntities(text: string): string {\n return text.replace(/&(#x?[0-9a-f]+|[a-z][a-z0-9]*);/gi, (match, body: string) => {\n if (body[0] === \"#\") {\n const codePoint =\n body[1] === \"x\" || body[1] === \"X\"\n ? Number.parseInt(body.slice(2), 16)\n : Number.parseInt(body.slice(1), 10);\n\n if (Number.isNaN(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {\n return match;\n }\n\n try {\n return String.fromCodePoint(codePoint);\n } catch {\n return match;\n }\n }\n\n const named = NAMED_ENTITIES[body.toLowerCase()];\n\n return named ?? match;\n });\n}\n\n/**\n * Pull the `<title>` text out of the document, decoded and trimmed, or\n * `undefined` when there is none. Read BEFORE `<head>` is stripped.\n */\nfunction extractTitle(html: string): string | undefined {\n const match = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html);\n\n if (!match) {\n return undefined;\n }\n\n const title = decodeEntities(match[1]).replace(/\\s+/g, \" \").trim();\n\n return title.length > 0 ? title : undefined;\n}\n\n/**\n * Strip HTML markup down to readable plain text — a lightweight,\n * dependency-free pass (no DOM parser): drop comments and non-prose elements\n * (`script` / `style` / `head` / `svg` / …) content-and-all, convert block\n * tags to line breaks to preserve paragraph structure, remove every\n * remaining tag, decode entities, then collapse runs of whitespace while\n * keeping blank-line paragraph separators.\n */\nfunction htmlToText(html: string): string {\n let text = html;\n\n // 1. Comments first — a commented-out `<script>` must not survive.\n text = text.replace(/<!--[\\s\\S]*?-->/g, \" \");\n\n // 2. Non-prose elements, content and all.\n for (const tag of STRIPPED_ELEMENTS) {\n const element = new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\");\n text = text.replace(element, \" \");\n // Defensively drop a self-closing / unterminated open tag too.\n text = text.replace(new RegExp(`<\\\\/?${tag}\\\\b[^>]*>`, \"gi\"), \" \");\n }\n\n // 3. Block tags → newlines, so paragraph / list structure survives.\n text = text.replace(BLOCK_TAGS, \"\\n\");\n\n // 4. Every remaining tag → gone.\n text = text.replace(/<[^>]+>/g, \"\");\n\n // 5. Entities → characters.\n text = decodeEntities(text);\n\n // 6. Normalize whitespace: trim each line, drop blank runs to a single\n // blank line (a paragraph separator the recursive splitter honors).\n text = text\n .replace(/[^\\S\\n]+/g, \" \")\n .replace(/[ \\t]*\\n[ \\t]*/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n\n return text;\n}\n\n/**\n * Load an HTML string into a single {@link RagDocument} of readable text.\n * Scripts, styles, and other non-prose elements are dropped content-and-all,\n * block tags become line breaks (so paragraph structure survives for the\n * splitter), remaining tags are stripped, and HTML entities are decoded — a\n * lightweight regex pass, no heavy DOM dependency.\n *\n * The document's `metadata.title` is set from the page's `<title>` (unless\n * the caller overrode it), and `metadata.loader` is `\"html\"`. The output is\n * the exact shape `index()` consumes.\n *\n * @example\n * const kb = ai.rag({ embedder, store });\n * await kb.index(loadHtml(rawHtmlString, { id: \"landing-page\" }));\n *\n * @param html - The raw HTML markup.\n * @param options - Shared `id` / `metadata` / `tags` ({@link LoadHtmlOptions}).\n * @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.\n */\nexport function loadHtml(\n html: string,\n options: LoadHtmlOptions = {},\n): RagLoaderResult {\n const id = options.id ?? DEFAULT_ID;\n const title = extractTitle(html);\n const text = htmlToText(html);\n\n // An all-markup / empty page strips to nothing; emit no document so\n // index() never receives a no-op record (matches loadText's behavior).\n if (text.length === 0) {\n return [];\n }\n\n // Derived keys (source, loader, title) sit UNDER the caller's metadata so\n // an explicit override always wins.\n const doc: RagDocument = {\n id,\n text,\n metadata: {\n source: id,\n loader: \"html\",\n ...(title !== undefined ? { title } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n };\n\n return [doc];\n}\n\n/** Internal — exported for the web loader so it shares the exact strip pass. */\nexport { htmlToText, extractTitle };\n"],"mappings":";;AAIA,MAAM,aAAa;;;;;;;AAQnB,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,aACJ;;AAGF,MAAM,iBAAyC;CAC7C,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,OAAO;CACP,QAAQ;CACR,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,QAAQ;CACR,MAAM;AACR;;;;;;AAOA,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,QAAQ,sCAAsC,OAAO,SAAiB;EAChF,IAAI,KAAK,OAAO,KAAK;GACnB,MAAM,YACJ,KAAK,OAAO,OAAO,KAAK,OAAO,MAC3B,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IACjC,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE;GAEvC,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,KAAK,YAAY,SAC1D,OAAO;GAGT,IAAI;IACF,OAAO,OAAO,cAAc,SAAS;GACvC,QAAQ;IACN,OAAO;GACT;EACF;EAIA,OAFc,eAAe,KAAK,YAAY,MAE9B;CAClB,CAAC;AACH;;;;;AAMA,SAAS,aAAa,MAAkC;CACtD,MAAM,QAAQ,mCAAmC,KAAK,IAAI;CAE1D,IAAI,CAAC,OACH;CAGF,MAAM,QAAQ,eAAe,MAAM,EAAE,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAEjE,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;;;AAUA,SAAS,WAAW,MAAsB;CACxC,IAAI,OAAO;CAGX,OAAO,KAAK,QAAQ,oBAAoB,GAAG;CAG3C,KAAK,MAAM,OAAO,mBAAmB;EACnC,MAAM,UAAU,IAAI,OAAO,IAAI,IAAI,yBAAyB,IAAI,IAAI,IAAI;EACxE,OAAO,KAAK,QAAQ,SAAS,GAAG;EAEhC,OAAO,KAAK,QAAQ,IAAI,OAAO,QAAQ,IAAI,YAAY,IAAI,GAAG,GAAG;CACnE;CAGA,OAAO,KAAK,QAAQ,YAAY,IAAI;CAGpC,OAAO,KAAK,QAAQ,YAAY,EAAE;CAGlC,OAAO,eAAe,IAAI;CAI1B,OAAO,KACJ,QAAQ,aAAa,GAAG,CAAC,CACzB,QAAQ,mBAAmB,IAAI,CAAC,CAChC,QAAQ,WAAW,MAAM,CAAC,CAC1B,KAAK;CAER,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SACd,MACA,UAA2B,CAAC,GACX;CACjB,MAAM,KAAK,QAAQ,MAAM;CACzB,MAAM,QAAQ,aAAa,IAAI;CAC/B,MAAM,OAAO,WAAW,IAAI;CAI5B,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAiBV,OAAO,CAAC;EAXN;EACA;EACA,UAAU;GACR,QAAQ;GACR,QAAQ;GACR,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;GACvC,GAAG,QAAQ;EACb;EACA,MAAM,QAAQ;CAGN,CAAC;AACb"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { LoadPdfOptions, RagLoaderResult } from "./loader.type.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-pdf.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Load a PDF's bytes into {@link RagDocument}(s) via the OPTIONAL `pdf-parse`
|
|
6
|
+
* peer. The peer is resolved lazily on the FIRST call (not at import) so
|
|
7
|
+
* importing `@warlock.js/ai` never forces it to be installed; when it is
|
|
8
|
+
* absent the curated {@link PDF_PARSE_INSTALL_INSTRUCTIONS} is thrown as a
|
|
9
|
+
* plain `Error` (a missing optional peer is an infrastructure fault, not a
|
|
10
|
+
* content problem).
|
|
11
|
+
*
|
|
12
|
+
* By default the whole PDF becomes a single document carrying
|
|
13
|
+
* `metadata.pageCount`. With `perPage: true`, each page becomes its own
|
|
14
|
+
* document (`id` suffixed `#p<n>`, `metadata.page` set) so citations stay
|
|
15
|
+
* page-precise. Document `metadata.title` comes from the PDF info
|
|
16
|
+
* dictionary's `Title` (unless overridden), and `metadata.loader` is
|
|
17
|
+
* `"pdf"`. The output is the exact shape `index()` consumes.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* import { readFile } from "node:fs/promises";
|
|
21
|
+
* const kb = ai.rag({ embedder, store });
|
|
22
|
+
* await kb.index(await loadPdf(await readFile("guide.pdf"), { id: "guide" }));
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* // One document per page for page-precise citations:
|
|
26
|
+
* await kb.index(await loadPdf(bytes, { id: "manual", perPage: true }));
|
|
27
|
+
*
|
|
28
|
+
* @param input - The PDF bytes (`Buffer`, `ArrayBuffer`, or `Uint8Array`).
|
|
29
|
+
* @param options - `perPage` plus shared `id` / `metadata` / `tags`
|
|
30
|
+
* ({@link LoadPdfOptions}).
|
|
31
|
+
* @returns A {@link RagLoaderResult} ready for `rag.index()`.
|
|
32
|
+
* @throws {Error} carrying {@link PDF_PARSE_INSTALL_INSTRUCTIONS} when the
|
|
33
|
+
* `pdf-parse` peer is not installed.
|
|
34
|
+
*/
|
|
35
|
+
declare function loadPdf(input: Buffer | ArrayBuffer | Uint8Array, options?: LoadPdfOptions): Promise<RagLoaderResult>;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { loadPdf };
|
|
38
|
+
//# sourceMappingURL=load-pdf.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-pdf.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-pdf.ts"],"mappings":";;;;;AA8HA;;;;;;;;;;;;;;;;;;;;AAG0B;;;;;;;;;iBAHJ,OAAA,CACpB,KAAA,EAAO,MAAA,GAAS,WAAA,GAAc,UAAA,EAC9B,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,eAAA"}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { PDF_PARSE_INSTALL_INSTRUCTIONS } from "./errors.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-pdf.ts
|
|
4
|
+
/** Default `id` when the caller supplies none. */
|
|
5
|
+
const DEFAULT_ID = "document";
|
|
6
|
+
let pdfParse;
|
|
7
|
+
let isModuleExists;
|
|
8
|
+
let loadingPromise;
|
|
9
|
+
/**
|
|
10
|
+
* Settle the lazy import of `pdf-parse` once, concurrency-safe. A bare
|
|
11
|
+
* `catch` flips the flag to `false`; the curated
|
|
12
|
+
* {@link PDF_PARSE_INSTALL_INSTRUCTIONS} surfaces at first
|
|
13
|
+
* {@link loadPdf} call, never a raw module-resolution stack trace. Mirrors
|
|
14
|
+
* the guard moderation detector's `loadOpenAi`.
|
|
15
|
+
*/
|
|
16
|
+
function loadPdfParse() {
|
|
17
|
+
if (isModuleExists !== void 0) return Promise.resolve();
|
|
18
|
+
if (loadingPromise) return loadingPromise;
|
|
19
|
+
loadingPromise = (async () => {
|
|
20
|
+
try {
|
|
21
|
+
const mod = await import("pdf-parse");
|
|
22
|
+
pdfParse = mod.default ?? mod;
|
|
23
|
+
isModuleExists = typeof pdfParse === "function";
|
|
24
|
+
} catch {
|
|
25
|
+
isModuleExists = false;
|
|
26
|
+
}
|
|
27
|
+
})();
|
|
28
|
+
return loadingPromise;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Coerce a {@link RagDocument}-compatible binary input into a `Buffer` for
|
|
32
|
+
* `pdf-parse`. Accepts a Node `Buffer`, an `ArrayBuffer`, or a typed array
|
|
33
|
+
* (`Uint8Array`) — the shapes a file read / fetch body hands back.
|
|
34
|
+
*/
|
|
35
|
+
function toBuffer(input) {
|
|
36
|
+
if (Buffer.isBuffer(input)) return input;
|
|
37
|
+
if (input instanceof ArrayBuffer) return Buffer.from(input);
|
|
38
|
+
return Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Load a PDF's bytes into {@link RagDocument}(s) via the OPTIONAL `pdf-parse`
|
|
42
|
+
* peer. The peer is resolved lazily on the FIRST call (not at import) so
|
|
43
|
+
* importing `@warlock.js/ai` never forces it to be installed; when it is
|
|
44
|
+
* absent the curated {@link PDF_PARSE_INSTALL_INSTRUCTIONS} is thrown as a
|
|
45
|
+
* plain `Error` (a missing optional peer is an infrastructure fault, not a
|
|
46
|
+
* content problem).
|
|
47
|
+
*
|
|
48
|
+
* By default the whole PDF becomes a single document carrying
|
|
49
|
+
* `metadata.pageCount`. With `perPage: true`, each page becomes its own
|
|
50
|
+
* document (`id` suffixed `#p<n>`, `metadata.page` set) so citations stay
|
|
51
|
+
* page-precise. Document `metadata.title` comes from the PDF info
|
|
52
|
+
* dictionary's `Title` (unless overridden), and `metadata.loader` is
|
|
53
|
+
* `"pdf"`. The output is the exact shape `index()` consumes.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* import { readFile } from "node:fs/promises";
|
|
57
|
+
* const kb = ai.rag({ embedder, store });
|
|
58
|
+
* await kb.index(await loadPdf(await readFile("guide.pdf"), { id: "guide" }));
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* // One document per page for page-precise citations:
|
|
62
|
+
* await kb.index(await loadPdf(bytes, { id: "manual", perPage: true }));
|
|
63
|
+
*
|
|
64
|
+
* @param input - The PDF bytes (`Buffer`, `ArrayBuffer`, or `Uint8Array`).
|
|
65
|
+
* @param options - `perPage` plus shared `id` / `metadata` / `tags`
|
|
66
|
+
* ({@link LoadPdfOptions}).
|
|
67
|
+
* @returns A {@link RagLoaderResult} ready for `rag.index()`.
|
|
68
|
+
* @throws {Error} carrying {@link PDF_PARSE_INSTALL_INSTRUCTIONS} when the
|
|
69
|
+
* `pdf-parse` peer is not installed.
|
|
70
|
+
*/
|
|
71
|
+
async function loadPdf(input, options = {}) {
|
|
72
|
+
await loadPdfParse();
|
|
73
|
+
if (!isModuleExists || !pdfParse) throw new Error(PDF_PARSE_INSTALL_INSTRUCTIONS);
|
|
74
|
+
const id = options.id ?? DEFAULT_ID;
|
|
75
|
+
if (options.perPage ?? false) return loadPerPage(input, id, options);
|
|
76
|
+
const parsed = await pdfParse(toBuffer(input));
|
|
77
|
+
const text = parsed.text.trim();
|
|
78
|
+
const title = parsed.info?.Title?.trim();
|
|
79
|
+
if (text.length === 0) return [];
|
|
80
|
+
return [{
|
|
81
|
+
id,
|
|
82
|
+
text,
|
|
83
|
+
metadata: {
|
|
84
|
+
source: id,
|
|
85
|
+
loader: "pdf",
|
|
86
|
+
pageCount: parsed.numpages,
|
|
87
|
+
...title ? { title } : {},
|
|
88
|
+
...options.metadata
|
|
89
|
+
},
|
|
90
|
+
tags: options.tags
|
|
91
|
+
}];
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Per-page variant: render each page separately via `pdf-parse`'s
|
|
95
|
+
* `pagerender` hook, accumulating one document per non-empty page. Each
|
|
96
|
+
* carries `metadata.page` (1-based) and `metadata.pageCount`, and its id is
|
|
97
|
+
* the base id suffixed `#p<n>` so every page-document is distinctly
|
|
98
|
+
* identified for citation.
|
|
99
|
+
*
|
|
100
|
+
* `pdf-parse` calls `pagerender` once per page in document order and
|
|
101
|
+
* `await`s the returned string, so capturing each page's joined text content
|
|
102
|
+
* here gives reliable page boundaries the concatenated `text` lacks.
|
|
103
|
+
*/
|
|
104
|
+
async function loadPerPage(input, id, options) {
|
|
105
|
+
const pages = [];
|
|
106
|
+
const parsed = await pdfParse(toBuffer(input), { pagerender: async (page) => {
|
|
107
|
+
const rendered = await renderPage(page);
|
|
108
|
+
pages.push(rendered);
|
|
109
|
+
return rendered;
|
|
110
|
+
} });
|
|
111
|
+
const title = parsed.info?.Title?.trim();
|
|
112
|
+
const docs = [];
|
|
113
|
+
pages.forEach((pageText, index) => {
|
|
114
|
+
const text = pageText.trim();
|
|
115
|
+
if (text.length === 0) return;
|
|
116
|
+
const pageNumber = index + 1;
|
|
117
|
+
docs.push({
|
|
118
|
+
id: `${id}#p${pageNumber}`,
|
|
119
|
+
text,
|
|
120
|
+
metadata: {
|
|
121
|
+
source: id,
|
|
122
|
+
loader: "pdf",
|
|
123
|
+
page: pageNumber,
|
|
124
|
+
pageCount: parsed.numpages,
|
|
125
|
+
...title ? { title } : {},
|
|
126
|
+
...options.metadata
|
|
127
|
+
},
|
|
128
|
+
tags: options.tags
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
return docs;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Join a single page's text-layer items in reading order, inserting a space
|
|
135
|
+
* between items so adjacent words do not run together. Mirrors the essence
|
|
136
|
+
* of `pdf-parse`'s default renderer without depending on its internals, so
|
|
137
|
+
* the per-page hook stays stable across `pdf-parse` versions. A page with no
|
|
138
|
+
* text layer (scanned image) renders to an empty string and is dropped.
|
|
139
|
+
*/
|
|
140
|
+
async function renderPage(page) {
|
|
141
|
+
if (typeof page?.getTextContent !== "function") return "";
|
|
142
|
+
return (await page.getTextContent({
|
|
143
|
+
normalizeWhitespace: true,
|
|
144
|
+
disableCombineTextItems: false
|
|
145
|
+
})).items.map((item) => item.str).join(" ").replace(/\s+/g, " ").trim();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
//#endregion
|
|
149
|
+
export { loadPdf };
|
|
150
|
+
//# sourceMappingURL=load-pdf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-pdf.mjs","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-pdf.ts"],"sourcesContent":["import type { RagDocument } from \"../contracts/rag-document.type\";\nimport { PDF_PARSE_INSTALL_INSTRUCTIONS } from \"./errors\";\nimport type { LoadPdfOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Default `id` when the caller supplies none. */\nconst DEFAULT_ID = \"document\";\n\n/**\n * The slice of `pdf-parse`'s result we consume. The peer returns more\n * (`info`, `metadata`, `version`); we only need the extracted `text` and\n * page count, so we type just those to keep the dependency at arm's length.\n */\ntype PdfParseResult = {\n /** Concatenated text of every page. */\n text: string;\n /** Number of pages in the document. */\n numpages: number;\n /** Document info dictionary — `Title` lifted into metadata when present. */\n info?: { Title?: string } & Record<string, unknown>;\n};\n\n/** The `pdf-parse` module's callable default export. */\ntype PdfParseFn = (\n data: Buffer | Uint8Array,\n options?: {\n /**\n * Per-page renderer `pdf-parse` calls once per page in document order and\n * `await`s — may return the page text synchronously or as a promise.\n */\n pagerender?: (page: unknown) => string | Promise<string>;\n },\n) => Promise<PdfParseResult>;\n\n// ============================================================\n// Lazily-loaded pdf-parse (OPTIONAL peer)\n// ============================================================\n\nlet pdfParse: PdfParseFn | undefined;\nlet isModuleExists: boolean | undefined;\nlet loadingPromise: Promise<void> | undefined;\n\n/**\n * Settle the lazy import of `pdf-parse` once, concurrency-safe. A bare\n * `catch` flips the flag to `false`; the curated\n * {@link PDF_PARSE_INSTALL_INSTRUCTIONS} surfaces at first\n * {@link loadPdf} call, never a raw module-resolution stack trace. Mirrors\n * the guard moderation detector's `loadOpenAi`.\n */\nfunction loadPdfParse(): Promise<void> {\n if (isModuleExists !== undefined) {\n return Promise.resolve();\n }\n\n if (loadingPromise) {\n return loadingPromise;\n }\n\n loadingPromise = (async () => {\n try {\n // Literal specifier so `vi.mock(\"pdf-parse\")` can intercept it in tests.\n // Typed via the ambient `pdf-parse` shim in this directory, so the bare\n // import resolves even though the OPTIONAL peer is not a dependency.\n const mod = (await import(\"pdf-parse\")) as {\n default?: PdfParseFn;\n } & Partial<PdfParseFn>;\n // pdf-parse ships CommonJS — the callable is `module.exports`, surfaced\n // as `default` under ESM interop. Fall back to the namespace itself for\n // bundlers that hoist the callable to the top level.\n pdfParse = mod.default ?? (mod as unknown as PdfParseFn);\n isModuleExists = typeof pdfParse === \"function\";\n } catch {\n isModuleExists = false;\n }\n })();\n\n return loadingPromise;\n}\n\n/**\n * Coerce a {@link RagDocument}-compatible binary input into a `Buffer` for\n * `pdf-parse`. Accepts a Node `Buffer`, an `ArrayBuffer`, or a typed array\n * (`Uint8Array`) — the shapes a file read / fetch body hands back.\n */\nfunction toBuffer(input: Buffer | ArrayBuffer | Uint8Array): Buffer {\n if (Buffer.isBuffer(input)) {\n return input;\n }\n\n if (input instanceof ArrayBuffer) {\n return Buffer.from(input);\n }\n\n return Buffer.from(input.buffer, input.byteOffset, input.byteLength);\n}\n\n/**\n * Load a PDF's bytes into {@link RagDocument}(s) via the OPTIONAL `pdf-parse`\n * peer. The peer is resolved lazily on the FIRST call (not at import) so\n * importing `@warlock.js/ai` never forces it to be installed; when it is\n * absent the curated {@link PDF_PARSE_INSTALL_INSTRUCTIONS} is thrown as a\n * plain `Error` (a missing optional peer is an infrastructure fault, not a\n * content problem).\n *\n * By default the whole PDF becomes a single document carrying\n * `metadata.pageCount`. With `perPage: true`, each page becomes its own\n * document (`id` suffixed `#p<n>`, `metadata.page` set) so citations stay\n * page-precise. Document `metadata.title` comes from the PDF info\n * dictionary's `Title` (unless overridden), and `metadata.loader` is\n * `\"pdf\"`. The output is the exact shape `index()` consumes.\n *\n * @example\n * import { readFile } from \"node:fs/promises\";\n * const kb = ai.rag({ embedder, store });\n * await kb.index(await loadPdf(await readFile(\"guide.pdf\"), { id: \"guide\" }));\n *\n * @example\n * // One document per page for page-precise citations:\n * await kb.index(await loadPdf(bytes, { id: \"manual\", perPage: true }));\n *\n * @param input - The PDF bytes (`Buffer`, `ArrayBuffer`, or `Uint8Array`).\n * @param options - `perPage` plus shared `id` / `metadata` / `tags`\n * ({@link LoadPdfOptions}).\n * @returns A {@link RagLoaderResult} ready for `rag.index()`.\n * @throws {Error} carrying {@link PDF_PARSE_INSTALL_INSTRUCTIONS} when the\n * `pdf-parse` peer is not installed.\n */\nexport async function loadPdf(\n input: Buffer | ArrayBuffer | Uint8Array,\n options: LoadPdfOptions = {},\n): Promise<RagLoaderResult> {\n await loadPdfParse();\n\n if (!isModuleExists || !pdfParse) {\n throw new Error(PDF_PARSE_INSTALL_INSTRUCTIONS);\n }\n\n const id = options.id ?? DEFAULT_ID;\n const perPage = options.perPage ?? false;\n\n if (perPage) {\n return loadPerPage(input, id, options);\n }\n\n const parsed = await pdfParse(toBuffer(input));\n const text = parsed.text.trim();\n const title = parsed.info?.Title?.trim();\n\n // An image-only / empty PDF extracts no text — emit nothing so index()\n // never receives a no-op record.\n if (text.length === 0) {\n return [];\n }\n\n const doc: RagDocument = {\n id,\n text,\n metadata: {\n source: id,\n loader: \"pdf\",\n pageCount: parsed.numpages,\n ...(title ? { title } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n };\n\n return [doc];\n}\n\n/** One page of a parsed PDF — the text-layer item list `pagerender` sees. */\ntype PdfPage = {\n getTextContent: (\n options?: unknown,\n ) => Promise<{ items: { str: string }[] }>;\n};\n\n/**\n * Per-page variant: render each page separately via `pdf-parse`'s\n * `pagerender` hook, accumulating one document per non-empty page. Each\n * carries `metadata.page` (1-based) and `metadata.pageCount`, and its id is\n * the base id suffixed `#p<n>` so every page-document is distinctly\n * identified for citation.\n *\n * `pdf-parse` calls `pagerender` once per page in document order and\n * `await`s the returned string, so capturing each page's joined text content\n * here gives reliable page boundaries the concatenated `text` lacks.\n */\nasync function loadPerPage(\n input: Buffer | ArrayBuffer | Uint8Array,\n id: string,\n options: LoadPdfOptions,\n): Promise<RagDocument[]> {\n const pages: string[] = [];\n\n const parsed = await pdfParse!(toBuffer(input), {\n pagerender: async (page: unknown): Promise<string> => {\n const rendered = await renderPage(page as PdfPage);\n pages.push(rendered);\n return rendered;\n },\n });\n\n const title = parsed.info?.Title?.trim();\n const docs: RagDocument[] = [];\n\n pages.forEach((pageText, index) => {\n const text = pageText.trim();\n\n if (text.length === 0) {\n return;\n }\n\n const pageNumber = index + 1;\n\n docs.push({\n id: `${id}#p${pageNumber}`,\n text,\n metadata: {\n source: id,\n loader: \"pdf\",\n page: pageNumber,\n pageCount: parsed.numpages,\n ...(title ? { title } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n });\n });\n\n return docs;\n}\n\n/**\n * Join a single page's text-layer items in reading order, inserting a space\n * between items so adjacent words do not run together. Mirrors the essence\n * of `pdf-parse`'s default renderer without depending on its internals, so\n * the per-page hook stays stable across `pdf-parse` versions. A page with no\n * text layer (scanned image) renders to an empty string and is dropped.\n */\nasync function renderPage(page: PdfPage): Promise<string> {\n if (typeof page?.getTextContent !== \"function\") {\n return \"\";\n }\n\n const content = await page.getTextContent({\n normalizeWhitespace: true,\n disableCombineTextItems: false,\n });\n\n return content.items\n .map((item) => item.str)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n"],"mappings":";;;;AAKA,MAAM,aAAa;AAgCnB,IAAI;AACJ,IAAI;AACJ,IAAI;;;;;;;;AASJ,SAAS,eAA8B;CACrC,IAAI,mBAAmB,QACrB,OAAO,QAAQ,QAAQ;CAGzB,IAAI,gBACF,OAAO;CAGT,kBAAkB,YAAY;EAC5B,IAAI;GAIF,MAAM,MAAO,MAAM,OAAO;GAM1B,WAAW,IAAI,WAAY;GAC3B,iBAAiB,OAAO,aAAa;EACvC,QAAQ;GACN,iBAAiB;EACnB;CACF,EAAC,CAAE;CAEH,OAAO;AACT;;;;;;AAOA,SAAS,SAAS,OAAkD;CAClE,IAAI,OAAO,SAAS,KAAK,GACvB,OAAO;CAGT,IAAI,iBAAiB,aACnB,OAAO,OAAO,KAAK,KAAK;CAG1B,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU;AACrE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,eAAsB,QACpB,OACA,UAA0B,CAAC,GACD;CAC1B,MAAM,aAAa;CAEnB,IAAI,CAAC,kBAAkB,CAAC,UACtB,MAAM,IAAI,MAAM,8BAA8B;CAGhD,MAAM,KAAK,QAAQ,MAAM;CAGzB,IAFgB,QAAQ,WAAW,OAGjC,OAAO,YAAY,OAAO,IAAI,OAAO;CAGvC,MAAM,SAAS,MAAM,SAAS,SAAS,KAAK,CAAC;CAC7C,MAAM,OAAO,OAAO,KAAK,KAAK;CAC9B,MAAM,QAAQ,OAAO,MAAM,OAAO,KAAK;CAIvC,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAgBV,OAAO,CAAC;EAZN;EACA;EACA,UAAU;GACR,QAAQ;GACR,QAAQ;GACR,WAAW,OAAO;GAClB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;GACzB,GAAG,QAAQ;EACb;EACA,MAAM,QAAQ;CAGN,CAAC;AACb;;;;;;;;;;;;AAoBA,eAAe,YACb,OACA,IACA,SACwB;CACxB,MAAM,QAAkB,CAAC;CAEzB,MAAM,SAAS,MAAM,SAAU,SAAS,KAAK,GAAG,EAC9C,YAAY,OAAO,SAAmC;EACpD,MAAM,WAAW,MAAM,WAAW,IAAe;EACjD,MAAM,KAAK,QAAQ;EACnB,OAAO;CACT,EACF,CAAC;CAED,MAAM,QAAQ,OAAO,MAAM,OAAO,KAAK;CACvC,MAAM,OAAsB,CAAC;CAE7B,MAAM,SAAS,UAAU,UAAU;EACjC,MAAM,OAAO,SAAS,KAAK;EAE3B,IAAI,KAAK,WAAW,GAClB;EAGF,MAAM,aAAa,QAAQ;EAE3B,KAAK,KAAK;GACR,IAAI,GAAG,GAAG,IAAI;GACd;GACA,UAAU;IACR,QAAQ;IACR,QAAQ;IACR,MAAM;IACN,WAAW,OAAO;IAClB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;IACzB,GAAG,QAAQ;GACb;GACA,MAAM,QAAQ;EAChB,CAAC;CACH,CAAC;CAED,OAAO;AACT;;;;;;;;AASA,eAAe,WAAW,MAAgC;CACxD,IAAI,OAAO,MAAM,mBAAmB,YAClC,OAAO;CAQT,QAAO,MALe,KAAK,eAAe;EACxC,qBAAqB;EACrB,yBAAyB;CAC3B,CAAC,EAEa,CAAC,MACZ,KAAK,SAAS,KAAK,GAAG,CAAC,CACvB,KAAK,GAAG,CAAC,CACT,QAAQ,QAAQ,GAAG,CAAC,CACpB,KAAK;AACV"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { LoadTextOptions, RagLoaderResult } from "./loader.type.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-text.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* One raw text item — a bare string, or a `{ id, text, … }` record giving the
|
|
6
|
+
* item its own id / metadata / tags. Passing records lets a single
|
|
7
|
+
* {@link loadText} call turn many strings into many distinctly-identified
|
|
8
|
+
* {@link RagDocument}s.
|
|
9
|
+
*/
|
|
10
|
+
type TextInput = string | {
|
|
11
|
+
/** Stable id for this item. Falls back to the option `id` + index. */id?: string; /** The text body. */
|
|
12
|
+
text: string; /** Per-item metadata, merged under the shared option `metadata`. */
|
|
13
|
+
metadata?: Record<string, unknown>; /** Per-item tags (override the shared option `tags` when present). */
|
|
14
|
+
tags?: string[];
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Load plain text into {@link RagDocument}(s) — the zero-dependency base
|
|
18
|
+
* loader every other loader ultimately funnels into. Accepts a single
|
|
19
|
+
* string, a single `{ id, text }` record, or an array mixing both; each
|
|
20
|
+
* input becomes one document carrying `metadata.loader = "text"` plus a
|
|
21
|
+
* `metadata.source` (the resolved id).
|
|
22
|
+
*
|
|
23
|
+
* Caller `metadata` always wins over the loader-derived keys, and per-item
|
|
24
|
+
* `metadata` / `tags` (when an item is a record) layer on top of the shared
|
|
25
|
+
* option values. Empty / whitespace-only items are dropped — they would
|
|
26
|
+
* chunk to nothing anyway, so the result never carries a no-op document.
|
|
27
|
+
*
|
|
28
|
+
* The output is the exact shape `index()` consumes:
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* const kb = ai.rag({ embedder, store });
|
|
32
|
+
* await kb.index(loadText("a long string of notes…"));
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* await kb.index(loadText([
|
|
36
|
+
* { id: "faq-1", text: "…", metadata: { section: "billing" } },
|
|
37
|
+
* { id: "faq-2", text: "…" },
|
|
38
|
+
* ]));
|
|
39
|
+
*
|
|
40
|
+
* @param input - A string, a `{ id, text }` record, or an array of either.
|
|
41
|
+
* @param options - Shared `id` / `metadata` / `tags` ({@link LoadTextOptions}).
|
|
42
|
+
* @returns A {@link RagLoaderResult} ready to hand to `rag.index()`.
|
|
43
|
+
*/
|
|
44
|
+
declare function loadText(input: TextInput | TextInput[], options?: LoadTextOptions): RagLoaderResult;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { TextInput, loadText };
|
|
47
|
+
//# sourceMappingURL=load-text.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-text.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-text.ts"],"mappings":";;;;;AAYA;;;;KAAY,SAAA;EAMN,sEAFA,EAAA,WAIW;EAFX,IAAA,UAII;EAFJ,QAAA,GAAW,MAAM,mBAiCP;EA/BV,IAAA;AAAA;;;;;;;;;;;;;;AAkCY;;;;;;;;;;;;;;;iBAHF,QAAA,CACd,KAAA,EAAO,SAAA,GAAY,SAAA,IACnB,OAAA,GAAS,eAAA,GACR,eAAA"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-text.ts
|
|
2
|
+
/** Default `id` when the caller supplies neither `id` nor an item id. */
|
|
3
|
+
const DEFAULT_ID = "document";
|
|
4
|
+
/**
|
|
5
|
+
* Load plain text into {@link RagDocument}(s) — the zero-dependency base
|
|
6
|
+
* loader every other loader ultimately funnels into. Accepts a single
|
|
7
|
+
* string, a single `{ id, text }` record, or an array mixing both; each
|
|
8
|
+
* input becomes one document carrying `metadata.loader = "text"` plus a
|
|
9
|
+
* `metadata.source` (the resolved id).
|
|
10
|
+
*
|
|
11
|
+
* Caller `metadata` always wins over the loader-derived keys, and per-item
|
|
12
|
+
* `metadata` / `tags` (when an item is a record) layer on top of the shared
|
|
13
|
+
* option values. Empty / whitespace-only items are dropped — they would
|
|
14
|
+
* chunk to nothing anyway, so the result never carries a no-op document.
|
|
15
|
+
*
|
|
16
|
+
* The output is the exact shape `index()` consumes:
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* const kb = ai.rag({ embedder, store });
|
|
20
|
+
* await kb.index(loadText("a long string of notes…"));
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* await kb.index(loadText([
|
|
24
|
+
* { id: "faq-1", text: "…", metadata: { section: "billing" } },
|
|
25
|
+
* { id: "faq-2", text: "…" },
|
|
26
|
+
* ]));
|
|
27
|
+
*
|
|
28
|
+
* @param input - A string, a `{ id, text }` record, or an array of either.
|
|
29
|
+
* @param options - Shared `id` / `metadata` / `tags` ({@link LoadTextOptions}).
|
|
30
|
+
* @returns A {@link RagLoaderResult} ready to hand to `rag.index()`.
|
|
31
|
+
*/
|
|
32
|
+
function loadText(input, options = {}) {
|
|
33
|
+
const items = Array.isArray(input) ? input : [input];
|
|
34
|
+
const baseId = options.id ?? DEFAULT_ID;
|
|
35
|
+
const multiple = items.length > 1;
|
|
36
|
+
const docs = [];
|
|
37
|
+
items.forEach((item, index) => {
|
|
38
|
+
const text = typeof item === "string" ? item : item.text;
|
|
39
|
+
if (text.trim().length === 0) return;
|
|
40
|
+
const id = (typeof item === "string" ? void 0 : item.id) ?? (multiple ? `${baseId}#${index}` : baseId);
|
|
41
|
+
const itemMetadata = typeof item === "string" ? void 0 : item.metadata;
|
|
42
|
+
const itemTags = typeof item === "string" ? void 0 : item.tags;
|
|
43
|
+
docs.push({
|
|
44
|
+
id,
|
|
45
|
+
text,
|
|
46
|
+
metadata: {
|
|
47
|
+
source: id,
|
|
48
|
+
loader: "text",
|
|
49
|
+
...options.metadata,
|
|
50
|
+
...itemMetadata
|
|
51
|
+
},
|
|
52
|
+
tags: itemTags ?? options.tags
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
return docs;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//#endregion
|
|
59
|
+
export { loadText };
|
|
60
|
+
//# sourceMappingURL=load-text.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-text.mjs","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-text.ts"],"sourcesContent":["import type { RagDocument } from \"../contracts/rag-document.type\";\nimport type { LoadTextOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Default `id` when the caller supplies neither `id` nor an item id. */\nconst DEFAULT_ID = \"document\";\n\n/**\n * One raw text item — a bare string, or a `{ id, text, … }` record giving the\n * item its own id / metadata / tags. Passing records lets a single\n * {@link loadText} call turn many strings into many distinctly-identified\n * {@link RagDocument}s.\n */\nexport type TextInput =\n | string\n | {\n /** Stable id for this item. Falls back to the option `id` + index. */\n id?: string;\n /** The text body. */\n text: string;\n /** Per-item metadata, merged under the shared option `metadata`. */\n metadata?: Record<string, unknown>;\n /** Per-item tags (override the shared option `tags` when present). */\n tags?: string[];\n };\n\n/**\n * Load plain text into {@link RagDocument}(s) — the zero-dependency base\n * loader every other loader ultimately funnels into. Accepts a single\n * string, a single `{ id, text }` record, or an array mixing both; each\n * input becomes one document carrying `metadata.loader = \"text\"` plus a\n * `metadata.source` (the resolved id).\n *\n * Caller `metadata` always wins over the loader-derived keys, and per-item\n * `metadata` / `tags` (when an item is a record) layer on top of the shared\n * option values. Empty / whitespace-only items are dropped — they would\n * chunk to nothing anyway, so the result never carries a no-op document.\n *\n * The output is the exact shape `index()` consumes:\n *\n * @example\n * const kb = ai.rag({ embedder, store });\n * await kb.index(loadText(\"a long string of notes…\"));\n *\n * @example\n * await kb.index(loadText([\n * { id: \"faq-1\", text: \"…\", metadata: { section: \"billing\" } },\n * { id: \"faq-2\", text: \"…\" },\n * ]));\n *\n * @param input - A string, a `{ id, text }` record, or an array of either.\n * @param options - Shared `id` / `metadata` / `tags` ({@link LoadTextOptions}).\n * @returns A {@link RagLoaderResult} ready to hand to `rag.index()`.\n */\nexport function loadText(\n input: TextInput | TextInput[],\n options: LoadTextOptions = {},\n): RagLoaderResult {\n const items = Array.isArray(input) ? input : [input];\n const baseId = options.id ?? DEFAULT_ID;\n const multiple = items.length > 1;\n\n const docs: RagDocument[] = [];\n\n items.forEach((item, index) => {\n const text = typeof item === \"string\" ? item : item.text;\n\n // Drop empties up front — they chunk to nothing, so emitting them would\n // only add a no-op document for index() to skip.\n if (text.trim().length === 0) {\n return;\n }\n\n const itemId =\n typeof item === \"string\" ? undefined : item.id;\n // A single input keeps the bare base id; multiple inputs are suffixed so\n // every emitted document has a distinct, stable id.\n const id = itemId ?? (multiple ? `${baseId}#${index}` : baseId);\n\n const itemMetadata =\n typeof item === \"string\" ? undefined : item.metadata;\n const itemTags = typeof item === \"string\" ? undefined : item.tags;\n\n docs.push({\n id,\n text,\n // Loader-derived keys first, then the shared option metadata, then the\n // per-item metadata — caller intent always overrides the derived keys.\n metadata: {\n source: id,\n loader: \"text\",\n ...options.metadata,\n ...itemMetadata,\n },\n tags: itemTags ?? options.tags,\n });\n });\n\n return docs;\n}\n"],"mappings":";;AAIA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDnB,SAAgB,SACd,OACA,UAA2B,CAAC,GACX;CACjB,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;CACnD,MAAM,SAAS,QAAQ,MAAM;CAC7B,MAAM,WAAW,MAAM,SAAS;CAEhC,MAAM,OAAsB,CAAC;CAE7B,MAAM,SAAS,MAAM,UAAU;EAC7B,MAAM,OAAO,OAAO,SAAS,WAAW,OAAO,KAAK;EAIpD,IAAI,KAAK,KAAK,CAAC,CAAC,WAAW,GACzB;EAOF,MAAM,MAHJ,OAAO,SAAS,WAAW,SAAY,KAAK,QAGxB,WAAW,GAAG,OAAO,GAAG,UAAU;EAExD,MAAM,eACJ,OAAO,SAAS,WAAW,SAAY,KAAK;EAC9C,MAAM,WAAW,OAAO,SAAS,WAAW,SAAY,KAAK;EAE7D,KAAK,KAAK;GACR;GACA;GAGA,UAAU;IACR,QAAQ;IACR,QAAQ;IACR,GAAG,QAAQ;IACX,GAAG;GACL;GACA,MAAM,YAAY,QAAQ;EAC5B,CAAC;CACH,CAAC;CAED,OAAO;AACT"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { LoadWebOptions, RagLoaderResult } from "./loader.type.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-web.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fetch a URL through the SSRF-safe outbound policy and load it into a single
|
|
6
|
+
* {@link RagDocument} of readable text. The fetch ALWAYS goes through
|
|
7
|
+
* `guardedFetch` — never a raw `fetch` — so the scheme allowlist, host
|
|
8
|
+
* allowlist, post-DNS private-IP guard, timeout, and response-size cap from
|
|
9
|
+
* {@link LoadWebOptions.policy} (or the strict defaults) always apply.
|
|
10
|
+
*
|
|
11
|
+
* HTML responses are run through the same tag-strip pass as {@link loadHtml}
|
|
12
|
+
* (scripts/styles dropped, entities decoded, paragraph structure kept);
|
|
13
|
+
* non-HTML text responses (`text/plain`, markdown, …) are used verbatim.
|
|
14
|
+
* The document's `metadata.source` is the resolved URL, `metadata.title` is
|
|
15
|
+
* the page `<title>` (HTML only, unless overridden), `metadata.contentType`
|
|
16
|
+
* is the server-reported type, and `metadata.loader` is `"web"`.
|
|
17
|
+
*
|
|
18
|
+
* The output is the exact shape `index()` consumes, so a load feeds straight
|
|
19
|
+
* in:
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* const kb = ai.rag({ embedder, store });
|
|
23
|
+
* await kb.index(await loadWeb("https://example.com/guide"));
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* // Tighten the SSRF policy to a single host:
|
|
27
|
+
* await kb.index(await loadWeb(url, {
|
|
28
|
+
* policy: { hostAllowlist: ["docs.example.com"], maxBytes: 2_000_000 },
|
|
29
|
+
* tags: ["docs"],
|
|
30
|
+
* }));
|
|
31
|
+
*
|
|
32
|
+
* @param url - The absolute URL to fetch. Validated by the outbound policy.
|
|
33
|
+
* @param options - `policy` (the {@link OutboundPolicy}) plus shared
|
|
34
|
+
* `id` / `metadata` / `tags` ({@link LoadWebOptions}).
|
|
35
|
+
* @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.
|
|
36
|
+
* @throws {OutboundPolicyError} when the policy blocks the URL, the request
|
|
37
|
+
* times out, the body exceeds the cap, or the response is not OK.
|
|
38
|
+
*/
|
|
39
|
+
declare function loadWeb(url: string, options?: LoadWebOptions): Promise<RagLoaderResult>;
|
|
40
|
+
//#endregion
|
|
41
|
+
export { loadWeb };
|
|
42
|
+
//# sourceMappingURL=load-web.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-web.d.mts","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-web.ts"],"mappings":";;;;;AAgEA;;;;;;;;;;;;;;AAG0B;;;;;;;;;;;;;;;;;;;iBAHJ,OAAA,CACpB,GAAA,UACA,OAAA,GAAS,cAAA,GACR,OAAA,CAAQ,eAAA"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { OutboundPolicyError } from "../../errors/outbound-policy-error.mjs";
|
|
2
|
+
import "../../errors/index.mjs";
|
|
3
|
+
import { guardedFetch, readTextCapped, resolveOutboundPolicy } from "../../security/outbound-policy.mjs";
|
|
4
|
+
import { extractTitle, htmlToText } from "./load-html.mjs";
|
|
5
|
+
|
|
6
|
+
//#region ../@warlock.js/ai/src/rag/loaders/load-web.ts
|
|
7
|
+
/** Browser-ish UA so servers that gate on it still return prose. */
|
|
8
|
+
const DEFAULT_USER_AGENT = "warlock-ai-rag-loader/1.0 (+https://github.com/warlock-js)";
|
|
9
|
+
/**
|
|
10
|
+
* Whether a `content-type` header names an HTML document (so it is run
|
|
11
|
+
* through the tag-strip pass) versus already-plain text (used verbatim).
|
|
12
|
+
*/
|
|
13
|
+
function isHtmlContentType(contentType) {
|
|
14
|
+
if (!contentType) return true;
|
|
15
|
+
const lower = contentType.toLowerCase();
|
|
16
|
+
return lower.includes("text/html") || lower.includes("application/xhtml");
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Fetch a URL through the SSRF-safe outbound policy and load it into a single
|
|
20
|
+
* {@link RagDocument} of readable text. The fetch ALWAYS goes through
|
|
21
|
+
* `guardedFetch` — never a raw `fetch` — so the scheme allowlist, host
|
|
22
|
+
* allowlist, post-DNS private-IP guard, timeout, and response-size cap from
|
|
23
|
+
* {@link LoadWebOptions.policy} (or the strict defaults) always apply.
|
|
24
|
+
*
|
|
25
|
+
* HTML responses are run through the same tag-strip pass as {@link loadHtml}
|
|
26
|
+
* (scripts/styles dropped, entities decoded, paragraph structure kept);
|
|
27
|
+
* non-HTML text responses (`text/plain`, markdown, …) are used verbatim.
|
|
28
|
+
* The document's `metadata.source` is the resolved URL, `metadata.title` is
|
|
29
|
+
* the page `<title>` (HTML only, unless overridden), `metadata.contentType`
|
|
30
|
+
* is the server-reported type, and `metadata.loader` is `"web"`.
|
|
31
|
+
*
|
|
32
|
+
* The output is the exact shape `index()` consumes, so a load feeds straight
|
|
33
|
+
* in:
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* const kb = ai.rag({ embedder, store });
|
|
37
|
+
* await kb.index(await loadWeb("https://example.com/guide"));
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* // Tighten the SSRF policy to a single host:
|
|
41
|
+
* await kb.index(await loadWeb(url, {
|
|
42
|
+
* policy: { hostAllowlist: ["docs.example.com"], maxBytes: 2_000_000 },
|
|
43
|
+
* tags: ["docs"],
|
|
44
|
+
* }));
|
|
45
|
+
*
|
|
46
|
+
* @param url - The absolute URL to fetch. Validated by the outbound policy.
|
|
47
|
+
* @param options - `policy` (the {@link OutboundPolicy}) plus shared
|
|
48
|
+
* `id` / `metadata` / `tags` ({@link LoadWebOptions}).
|
|
49
|
+
* @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.
|
|
50
|
+
* @throws {OutboundPolicyError} when the policy blocks the URL, the request
|
|
51
|
+
* times out, the body exceeds the cap, or the response is not OK.
|
|
52
|
+
*/
|
|
53
|
+
async function loadWeb(url, options = {}) {
|
|
54
|
+
const policy = resolveOutboundPolicy(options.policy);
|
|
55
|
+
const response = await guardedFetch(url, policy, {
|
|
56
|
+
headers: {
|
|
57
|
+
"user-agent": DEFAULT_USER_AGENT,
|
|
58
|
+
accept: "text/html,text/*"
|
|
59
|
+
},
|
|
60
|
+
redirect: "follow"
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok) throw new OutboundPolicyError(`loadWeb: fetching "${url}" returned ${response.status} ${response.statusText}`, { context: {
|
|
63
|
+
url,
|
|
64
|
+
status: response.status
|
|
65
|
+
} });
|
|
66
|
+
const contentType = response.headers.get("content-type") ?? void 0;
|
|
67
|
+
const raw = await readTextCapped(response, policy.maxBytes);
|
|
68
|
+
const isHtml = isHtmlContentType(contentType);
|
|
69
|
+
const text = isHtml ? htmlToText(raw) : raw.trim();
|
|
70
|
+
const title = isHtml ? extractTitle(raw) : void 0;
|
|
71
|
+
const id = options.id ?? url;
|
|
72
|
+
if (text.length === 0) return [];
|
|
73
|
+
return [{
|
|
74
|
+
id,
|
|
75
|
+
text,
|
|
76
|
+
metadata: {
|
|
77
|
+
source: url,
|
|
78
|
+
loader: "web",
|
|
79
|
+
...title !== void 0 ? { title } : {},
|
|
80
|
+
...contentType !== void 0 ? { contentType } : {},
|
|
81
|
+
...options.metadata
|
|
82
|
+
},
|
|
83
|
+
tags: options.tags
|
|
84
|
+
}];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
//#endregion
|
|
88
|
+
export { loadWeb };
|
|
89
|
+
//# sourceMappingURL=load-web.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-web.mjs","names":[],"sources":["../../../../../../../../@warlock.js/ai/src/rag/loaders/load-web.ts"],"sourcesContent":["import {\n guardedFetch,\n readTextCapped,\n resolveOutboundPolicy,\n} from \"../../security/outbound-policy\";\nimport { OutboundPolicyError } from \"../../errors\";\nimport type { RagDocument } from \"../contracts/rag-document.type\";\nimport { htmlToText, extractTitle } from \"./load-html\";\nimport type { LoadWebOptions, RagLoaderResult } from \"./loader.type\";\n\n/** Browser-ish UA so servers that gate on it still return prose. */\nconst DEFAULT_USER_AGENT =\n \"warlock-ai-rag-loader/1.0 (+https://github.com/warlock-js)\";\n\n/**\n * Whether a `content-type` header names an HTML document (so it is run\n * through the tag-strip pass) versus already-plain text (used verbatim).\n */\nfunction isHtmlContentType(contentType: string | undefined): boolean {\n if (!contentType) {\n // No header — assume HTML, the common case for a fetched URL.\n return true;\n }\n\n const lower = contentType.toLowerCase();\n\n return lower.includes(\"text/html\") || lower.includes(\"application/xhtml\");\n}\n\n/**\n * Fetch a URL through the SSRF-safe outbound policy and load it into a single\n * {@link RagDocument} of readable text. The fetch ALWAYS goes through\n * `guardedFetch` — never a raw `fetch` — so the scheme allowlist, host\n * allowlist, post-DNS private-IP guard, timeout, and response-size cap from\n * {@link LoadWebOptions.policy} (or the strict defaults) always apply.\n *\n * HTML responses are run through the same tag-strip pass as {@link loadHtml}\n * (scripts/styles dropped, entities decoded, paragraph structure kept);\n * non-HTML text responses (`text/plain`, markdown, …) are used verbatim.\n * The document's `metadata.source` is the resolved URL, `metadata.title` is\n * the page `<title>` (HTML only, unless overridden), `metadata.contentType`\n * is the server-reported type, and `metadata.loader` is `\"web\"`.\n *\n * The output is the exact shape `index()` consumes, so a load feeds straight\n * in:\n *\n * @example\n * const kb = ai.rag({ embedder, store });\n * await kb.index(await loadWeb(\"https://example.com/guide\"));\n *\n * @example\n * // Tighten the SSRF policy to a single host:\n * await kb.index(await loadWeb(url, {\n * policy: { hostAllowlist: [\"docs.example.com\"], maxBytes: 2_000_000 },\n * tags: [\"docs\"],\n * }));\n *\n * @param url - The absolute URL to fetch. Validated by the outbound policy.\n * @param options - `policy` (the {@link OutboundPolicy}) plus shared\n * `id` / `metadata` / `tags` ({@link LoadWebOptions}).\n * @returns A {@link RagLoaderResult} (one document) ready for `rag.index()`.\n * @throws {OutboundPolicyError} when the policy blocks the URL, the request\n * times out, the body exceeds the cap, or the response is not OK.\n */\nexport async function loadWeb(\n url: string,\n options: LoadWebOptions = {},\n): Promise<RagLoaderResult> {\n const policy = resolveOutboundPolicy(options.policy);\n\n const response = await guardedFetch(url, policy, {\n headers: { \"user-agent\": DEFAULT_USER_AGENT, accept: \"text/html,text/*\" },\n redirect: \"follow\",\n });\n\n if (!response.ok) {\n throw new OutboundPolicyError(\n `loadWeb: fetching \"${url}\" returned ${response.status} ${response.statusText}`,\n { context: { url, status: response.status } },\n );\n }\n\n const contentType = response.headers.get(\"content-type\") ?? undefined;\n const raw = await readTextCapped(response, policy.maxBytes);\n\n const isHtml = isHtmlContentType(contentType);\n const text = isHtml ? htmlToText(raw) : raw.trim();\n const title = isHtml ? extractTitle(raw) : undefined;\n\n const id = options.id ?? url;\n\n // An empty body / all-markup page yields no document, so index() never\n // receives a no-op record.\n if (text.length === 0) {\n return [];\n }\n\n // Derived keys sit UNDER the caller's metadata so an explicit override wins.\n const doc: RagDocument = {\n id,\n text,\n metadata: {\n source: url,\n loader: \"web\",\n ...(title !== undefined ? { title } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n ...options.metadata,\n },\n tags: options.tags,\n };\n\n return [doc];\n}\n"],"mappings":";;;;;;;AAWA,MAAM,qBACJ;;;;;AAMF,SAAS,kBAAkB,aAA0C;CACnE,IAAI,CAAC,aAEH,OAAO;CAGT,MAAM,QAAQ,YAAY,YAAY;CAEtC,OAAO,MAAM,SAAS,WAAW,KAAK,MAAM,SAAS,mBAAmB;AAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,QACpB,KACA,UAA0B,CAAC,GACD;CAC1B,MAAM,SAAS,sBAAsB,QAAQ,MAAM;CAEnD,MAAM,WAAW,MAAM,aAAa,KAAK,QAAQ;EAC/C,SAAS;GAAE,cAAc;GAAoB,QAAQ;EAAmB;EACxE,UAAU;CACZ,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,oBACR,sBAAsB,IAAI,aAAa,SAAS,OAAO,GAAG,SAAS,cACnE,EAAE,SAAS;EAAE;EAAK,QAAQ,SAAS;CAAO,EAAE,CAC9C;CAGF,MAAM,cAAc,SAAS,QAAQ,IAAI,cAAc,KAAK;CAC5D,MAAM,MAAM,MAAM,eAAe,UAAU,OAAO,QAAQ;CAE1D,MAAM,SAAS,kBAAkB,WAAW;CAC5C,MAAM,OAAO,SAAS,WAAW,GAAG,IAAI,IAAI,KAAK;CACjD,MAAM,QAAQ,SAAS,aAAa,GAAG,IAAI;CAE3C,MAAM,KAAK,QAAQ,MAAM;CAIzB,IAAI,KAAK,WAAW,GAClB,OAAO,CAAC;CAiBV,OAAO,CAAC;EAZN;EACA;EACA,UAAU;GACR,QAAQ;GACR,QAAQ;GACR,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;GACvC,GAAI,gBAAgB,SAAY,EAAE,YAAY,IAAI,CAAC;GACnD,GAAG,QAAQ;EACb;EACA,MAAM,QAAQ;CAGN,CAAC;AACb"}
|