@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,1224 @@
|
|
|
1
|
+
// The `docs` helper of pane code, behind the @mallory/documents package: extraction, chunking with
|
|
2
|
+
// provenance, a pluggable embedder, a bounded cosine index and a portable
|
|
3
|
+
// corpus file. Pure and self-contained (no imports, no network, no storage), loaded
|
|
4
|
+
// into the sandbox as the module mallory:docs (src/runtime/sources.js), so it runs
|
|
5
|
+
// under the canvas's rules and cannot reach the page; the
|
|
6
|
+
// tests import it directly.
|
|
7
|
+
//
|
|
8
|
+
// Positions. `start`/`end` are character offsets (UTF-16 code units, end
|
|
9
|
+
// exclusive) into the document's *extracted text*: for plain text and Markdown
|
|
10
|
+
// that is the source (CRLF made LF, a BOM dropped), for HTML and PDF it is the
|
|
11
|
+
// text the extractor read from the markup/pages, kept in `doc.text`.
|
|
12
|
+
// A chunk's text is exactly `doc.text.slice(start, end)`.
|
|
13
|
+
|
|
14
|
+
export const LIMITS = { maxDocs: 200, maxBytes: 5 * 1024 * 1024, maxChars: 2_000_000, maxChunks: 20000, maxK: 50, maxDim: 2048, maxImportChars: 64 * 1024 * 1024 };
|
|
15
|
+
export const FORMAT = "mallory-doc-index";
|
|
16
|
+
|
|
17
|
+
// ---- hashing (not cryptographic: ids, fingerprints and the embedder's buckets) ----
|
|
18
|
+
|
|
19
|
+
/** A 53-bit hash of strings and byte arrays, as 14 hex digits. */
|
|
20
|
+
export function hashOf(...parts) {
|
|
21
|
+
let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
|
|
22
|
+
const feed = (c) => {
|
|
23
|
+
h1 = Math.imul(h1 ^ c, 2654435761);
|
|
24
|
+
h2 = Math.imul(h2 ^ c, 1597334677);
|
|
25
|
+
};
|
|
26
|
+
for (const part of parts) {
|
|
27
|
+
if (typeof part === "string") for (let i = 0; i < part.length; i++) feed(part.charCodeAt(i));
|
|
28
|
+
else for (let i = 0; i < part.length; i++) feed(part[i]);
|
|
29
|
+
feed(0x1f); // a separator, so ("ab","c") and ("a","bc") differ
|
|
30
|
+
}
|
|
31
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
32
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
33
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---- reading a source ----
|
|
37
|
+
|
|
38
|
+
const KIND_BY_EXT = { txt: "text", text: "text", log: "text", csv: "text", md: "markdown", markdown: "markdown", mdx: "markdown", html: "html", htm: "html", xhtml: "html", pdf: "pdf", docx: "docx", epub: "epub", png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", bmp: "image", tif: "image", tiff: "image" };
|
|
39
|
+
const KIND_BY_MIME = { "text/plain": "text", "text/markdown": "markdown", "text/x-markdown": "markdown", "text/html": "html", "application/xhtml+xml": "html", "application/pdf": "pdf", "text/csv": "text", "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx", "application/epub+zip": "epub", "image/png": "image", "image/jpeg": "image", "image/gif": "image", "image/webp": "image", "image/bmp": "image", "image/tiff": "image" };
|
|
40
|
+
const KINDS = ["text", "markdown", "html", "pdf", "docx", "epub", "image"];
|
|
41
|
+
|
|
42
|
+
const isBlobLike = (v) => v && typeof v === "object" && typeof v.arrayBuffer === "function" && typeof v.size === "number";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One input document, whatever shape it came in: a string, `{ name, text }`,
|
|
46
|
+
* `{ name, file }` (a media value or a Blob), a bare media value or Blob. Returns
|
|
47
|
+
* `{ name, kind?, text?, bytes?, type, problem? }`; `kind` is the requested one, or undefined to decide later.
|
|
48
|
+
*/
|
|
49
|
+
export async function readSource(input, index = 0) {
|
|
50
|
+
const fallback = `document-${index + 1}`;
|
|
51
|
+
if (typeof input === "string") return { name: fallback, text: input, type: "" };
|
|
52
|
+
if (!input || typeof input !== "object") return { name: fallback, problem: { status: "unsupported", reason: "not a document: give text, a file or { name, text | file }" } };
|
|
53
|
+
const item = isBlobLike(input) ? { file: input } : input.$media && isBlobLike(input.blob) ? { file: input } : input;
|
|
54
|
+
const file = item.file ?? item.blob;
|
|
55
|
+
const blob = isBlobLike(file) ? file : file?.$media && isBlobLike(file.blob) ? file.blob : undefined;
|
|
56
|
+
const meta = file?.$media ? file : item;
|
|
57
|
+
const name = String(item.name ?? meta?.name ?? blob?.name ?? fallback);
|
|
58
|
+
const type = String(item.type ?? blob?.type ?? "").split(";")[0].toLowerCase();
|
|
59
|
+
const requested = item.kind && item.kind !== "auto" ? String(item.kind) : undefined;
|
|
60
|
+
if (requested && !KINDS.includes(requested)) return { name, type, problem: { status: "unsupported", reason: `unsupported kind "${requested}": use text, markdown, html, pdf, docx, epub or image` } };
|
|
61
|
+
if (typeof item.text === "string") return { name, kind: requested, text: item.text, type };
|
|
62
|
+
if (blob) {
|
|
63
|
+
if (blob.size > LIMITS.maxBytes) return { name, type, problem: { status: "too-large", reason: `${blob.size} bytes is over the ${LIMITS.maxBytes} byte limit` } };
|
|
64
|
+
return { name, kind: requested, bytes: new Uint8Array(await blob.arrayBuffer()), type };
|
|
65
|
+
}
|
|
66
|
+
return { name, problem: { status: "unsupported", reason: "no text or file: give { name, text } or { name, file }" } };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function decideKind(src) {
|
|
70
|
+
if (src.kind) return src.kind;
|
|
71
|
+
if (src.bytes && src.bytes.length >= 5 && String.fromCharCode(...src.bytes.slice(0, 5)) === "%PDF-") return "pdf";
|
|
72
|
+
const ext = /\.([A-Za-z0-9]+)$/.exec(src.name)?.[1]?.toLowerCase();
|
|
73
|
+
// DOCX, EPUB and images are binary: a text value (no bytes) with such a name or type is not one of them
|
|
74
|
+
const known = (k) => ((k === "docx" || k === "epub" || k === "image") && src.bytes === undefined ? undefined : k);
|
|
75
|
+
if (ext && KIND_BY_EXT[ext]) return known(KIND_BY_EXT[ext]);
|
|
76
|
+
if (KIND_BY_MIME[src.type]) return known(KIND_BY_MIME[src.type]);
|
|
77
|
+
if (src.type.startsWith("text/")) return "text";
|
|
78
|
+
if (!src.type && !ext && src.text !== undefined) return "text";
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The hash of a source's content and kind, before any extraction: what "unchanged" means. */
|
|
83
|
+
export function sourceHash(src) {
|
|
84
|
+
return hashOf(src.name, src.kind ?? "", src.type ?? "", src.text ?? src.bytes ?? "");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---- extraction ----
|
|
88
|
+
|
|
89
|
+
const normalizeText = (t) => t.replace(/^/, "").replace(/\r\n?/g, "\n");
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Extract one source. Always resolves to `{ name, kind, status, reason?, text, headings, pages?, fingerprint, warnings }`:
|
|
93
|
+
* `status` is `ok`, `partial` (some of it was read), or says why it was not read:
|
|
94
|
+
* `unsupported`, `encrypted`, `scanned`, `empty`, `too-large`. Nothing in the source is run. `adapters` are the opt-in
|
|
95
|
+
* `{ pdfjs, ocr }`: the pdf.js module reads PDFs instead of the built-in reader, and an `ocr` function ({ name, type, bytes } to
|
|
96
|
+
* text) reads images and pages without text. Without them nothing changes.
|
|
97
|
+
*/
|
|
98
|
+
export async function extractDocument(src, adapters = {}) {
|
|
99
|
+
const base = { name: src.name, kind: "unknown", status: "ok", text: "", headings: [], warnings: [] };
|
|
100
|
+
const fail = (status, reason, kind = base.kind) => ({ ...base, kind, status, reason, fingerprint: hashOf(src.name, status, reason) });
|
|
101
|
+
if (src.problem) return fail(src.problem.status, src.problem.reason);
|
|
102
|
+
const { pdfjs, ocr } = adapters ?? {};
|
|
103
|
+
if (ocr !== undefined && typeof ocr !== "function") return fail("unsupported", "the ocr adapter must be a function: ({ name, type, bytes }) => text");
|
|
104
|
+
const kind = decideKind(src);
|
|
105
|
+
if (!kind) return fail("unsupported", `unsupported type ${src.type || "(unknown)"}: use text, Markdown, HTML, PDF, DOCX or EPUB (images need an ocr adapter)`);
|
|
106
|
+
base.kind = kind;
|
|
107
|
+
let result;
|
|
108
|
+
if (kind === "pdf" || kind === "docx" || kind === "epub" || kind === "image") {
|
|
109
|
+
if (!src.bytes) return fail("unsupported", `${kind === "pdf" ? "a PDF" : kind === "docx" ? "a DOCX" : kind === "epub" ? "an EPUB" : "an image"} needs its file bytes, not text`, kind);
|
|
110
|
+
if (kind === "image") {
|
|
111
|
+
if (!ocr) return fail("unsupported", `unsupported type ${src.type || "image"}: an image is read only with an ocr adapter (it is not OCR'd otherwise)`, kind);
|
|
112
|
+
try { result = await extractImage(src, ocr); } catch (e) { return fail("unsupported", `OCR failed: ${e?.message ?? e}`, kind); }
|
|
113
|
+
} else if (kind === "docx") result = await extractDocx(src.bytes);
|
|
114
|
+
else if (kind === "epub") result = await extractEpub(src.bytes);
|
|
115
|
+
else if (pdfjs) result = await extractPdfWithPdfjs(src.bytes, pdfjs, { ocr });
|
|
116
|
+
else result = await extractPdf(src.bytes);
|
|
117
|
+
} else {
|
|
118
|
+
let text = src.text;
|
|
119
|
+
if (text === undefined) {
|
|
120
|
+
if (src.bytes.includes(0)) return fail("unsupported", "binary content (a NUL byte): not text", kind);
|
|
121
|
+
text = new TextDecoder("utf-8").decode(src.bytes);
|
|
122
|
+
const bad = (text.match(/\ufffd/g) ?? []).length;
|
|
123
|
+
if (bad > 8 && bad / text.length > 0.01) return fail("unsupported", "not valid UTF-8 text", kind);
|
|
124
|
+
}
|
|
125
|
+
if (text.length > LIMITS.maxChars) return fail("too-large", `${text.length} characters is over the ${LIMITS.maxChars} character limit`, kind);
|
|
126
|
+
text = normalizeText(text);
|
|
127
|
+
result = kind === "html" ? htmlToText(text) : kind === "markdown" ? { text, headings: markdownHeadings(text) } : { text, headings: [] };
|
|
128
|
+
}
|
|
129
|
+
if (result.status && result.status !== "partial") return fail(result.status, result.reason, kind);
|
|
130
|
+
const text = result.text;
|
|
131
|
+
if (text.length > LIMITS.maxChars) return fail("too-large", `${text.length} extracted characters is over the ${LIMITS.maxChars} character limit`, kind);
|
|
132
|
+
if (!text.trim()) return fail("empty", "no text was found", kind);
|
|
133
|
+
return {
|
|
134
|
+
...base, kind, text, headings: result.headings ?? [], ...(result.pages ? { pages: result.pages } : {}),
|
|
135
|
+
status: result.status ?? "ok", ...(result.reason ? { reason: result.reason } : {}), warnings: result.warnings ?? [],
|
|
136
|
+
fingerprint: hashOf(src.name, kind, text),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** ATX (`# x`) and setext (`x` over `===`) headings outside fenced code, as `{ level, title, start }`. */
|
|
141
|
+
export function markdownHeadings(text) {
|
|
142
|
+
const out = [];
|
|
143
|
+
let fence = null;
|
|
144
|
+
let pos = 0;
|
|
145
|
+
const lines = text.split("\n");
|
|
146
|
+
for (let i = 0; i < lines.length; i++) {
|
|
147
|
+
const line = lines[i];
|
|
148
|
+
const f = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
|
149
|
+
if (f) {
|
|
150
|
+
if (!fence) fence = f[1][0];
|
|
151
|
+
else if (f[1][0] === fence) fence = null;
|
|
152
|
+
} else if (!fence) {
|
|
153
|
+
const atx = /^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/.exec(line);
|
|
154
|
+
if (atx && atx[2]) out.push({ level: atx[1].length, title: atx[2].trim(), start: pos + line.indexOf("#") });
|
|
155
|
+
else if (line.trim() && i + 1 < lines.length && /^ {0,3}(=+|-+)[ \t]*$/.test(lines[i + 1]) && !/^\s*([-*+]|\d+[.)])\s/.test(line)) {
|
|
156
|
+
out.push({ level: lines[i + 1].trim()[0] === "=" ? 1 : 2, title: line.trim(), start: pos + (line.length - line.trimStart().length) });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
pos += line.length + 1;
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®", trade: "™", mdash: "—", ndash: "–", hellip: "…", lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”", bull: "•", middot: "·", euro: "€", laquo: "«", raquo: "»", times: "×", deg: "°" };
|
|
165
|
+
export function decodeEntities(s) {
|
|
166
|
+
return s.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,8});/g, (m, e) => {
|
|
167
|
+
if (e[0] === "#") {
|
|
168
|
+
const cp = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
169
|
+
return cp > 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff) ? String.fromCodePoint(cp) : "�";
|
|
170
|
+
}
|
|
171
|
+
return ENTITIES[e] ?? m;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const SKIP_CONTENT = new Set(["script", "style", "template", "noscript", "iframe", "object", "svg", "math", "title"]);
|
|
176
|
+
const BLOCK = new Set(["p", "div", "section", "article", "header", "footer", "main", "nav", "aside", "ul", "ol", "li", "dl", "dt", "dd", "table", "tr", "thead", "tbody", "tfoot", "caption", "blockquote", "pre", "figure", "figcaption", "form", "fieldset", "details", "summary", "address", "hr", "br", "h1", "h2", "h3", "h4", "h5", "h6"]);
|
|
177
|
+
const PARA = new Set(["p", "div", "section", "article", "ul", "ol", "table", "blockquote", "pre", "figure", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "form", "details"]);
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* HTML to text with a small tokenizer; it never builds a DOM and never loads or runs anything.
|
|
181
|
+
* Script/style/template/svg/iframe/object content, comments, doctypes and CDATA are dropped, block
|
|
182
|
+
* elements break lines, whitespace is collapsed (except in <pre>), entities are decoded.
|
|
183
|
+
* Headings are returned with their offsets in the text.
|
|
184
|
+
*/
|
|
185
|
+
export function htmlToText(html) {
|
|
186
|
+
let out = "";
|
|
187
|
+
let pending = 0; // newlines owed before the next text
|
|
188
|
+
let space = false;
|
|
189
|
+
let pre = 0;
|
|
190
|
+
const headings = [];
|
|
191
|
+
let open = null;
|
|
192
|
+
const emit = (s) => {
|
|
193
|
+
if (!s) return;
|
|
194
|
+
if (!out) pending = 0;
|
|
195
|
+
if (pending) { out += "\n".repeat(pending); pending = 0; space = false; }
|
|
196
|
+
else if (space && out && !out.endsWith("\n")) out += " ";
|
|
197
|
+
space = false;
|
|
198
|
+
if (open && open.start === undefined) open.start = out.length;
|
|
199
|
+
out += s;
|
|
200
|
+
};
|
|
201
|
+
const text = (raw) => {
|
|
202
|
+
const s = decodeEntities(raw);
|
|
203
|
+
if (pre) { emit(s); return; }
|
|
204
|
+
const collapsed = s.replace(/[ \t\n\r\f ]+/g, " ");
|
|
205
|
+
const trimmed = collapsed.trim();
|
|
206
|
+
if (!trimmed) { if (collapsed) space = true; return; }
|
|
207
|
+
if (collapsed[0] === " ") space = true;
|
|
208
|
+
emit(trimmed);
|
|
209
|
+
if (collapsed.endsWith(" ")) space = true;
|
|
210
|
+
};
|
|
211
|
+
const n = html.length;
|
|
212
|
+
let i = 0;
|
|
213
|
+
while (i < n) {
|
|
214
|
+
const lt = html.indexOf("<", i);
|
|
215
|
+
if (lt < 0) { text(html.slice(i)); break; }
|
|
216
|
+
if (lt > i) text(html.slice(i, lt));
|
|
217
|
+
if (html.startsWith("<!--", lt)) { const e = html.indexOf("-->", lt + 4); i = e < 0 ? n : e + 3; continue; }
|
|
218
|
+
if (html.startsWith("<![CDATA[", lt)) { const e = html.indexOf("]]>", lt); i = e < 0 ? n : e + 3; continue; }
|
|
219
|
+
const m = /^<(\/?)([a-zA-Z][a-zA-Z0-9:-]*)/.exec(html.slice(lt, lt + 40));
|
|
220
|
+
if (!m) {
|
|
221
|
+
if (html[lt + 1] === "!" || html[lt + 1] === "?") { const e = html.indexOf(">", lt); i = e < 0 ? n : e + 1; continue; }
|
|
222
|
+
text("<"); i = lt + 1; continue;
|
|
223
|
+
}
|
|
224
|
+
// the end of the tag, honouring quoted attribute values
|
|
225
|
+
let j = lt + m[0].length, q = "";
|
|
226
|
+
while (j < n) {
|
|
227
|
+
const c = html[j];
|
|
228
|
+
if (q) { if (c === q) q = ""; } else if (c === '"' || c === "'") q = c; else if (c === ">") break;
|
|
229
|
+
j++;
|
|
230
|
+
}
|
|
231
|
+
if (j >= n) break; // an unterminated tag at the end is dropped
|
|
232
|
+
const closing = m[1] === "/";
|
|
233
|
+
const name = m[2].toLowerCase();
|
|
234
|
+
const selfClosing = html[j - 1] === "/";
|
|
235
|
+
i = j + 1;
|
|
236
|
+
if (!closing && SKIP_CONTENT.has(name) && !selfClosing) {
|
|
237
|
+
const re = new RegExp(`</${escapeRegExp(name)}\\s*>`, "i");
|
|
238
|
+
const rest = html.slice(i);
|
|
239
|
+
const hit = re.exec(rest);
|
|
240
|
+
i = hit ? i + hit.index + hit[0].length : n;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (name === "pre") pre = Math.max(0, pre + (closing ? -1 : 1));
|
|
244
|
+
if (BLOCK.has(name)) pending = Math.max(pending, PARA.has(name) ? 2 : 1);
|
|
245
|
+
else if (name === "td" || name === "th") { if (!closing) space = true; }
|
|
246
|
+
if (/^h[1-6]$/.test(name)) {
|
|
247
|
+
if (!closing) open = { level: Number(name[1]) };
|
|
248
|
+
else if (open) {
|
|
249
|
+
if (open.start !== undefined) {
|
|
250
|
+
const title = out.slice(open.start).replace(/\s+/g, " ").trim();
|
|
251
|
+
if (title) headings.push({ level: open.level, title, start: open.start });
|
|
252
|
+
}
|
|
253
|
+
open = null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { text: out.replace(/\s+$/, ""), headings };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---- PDF (best effort, no dependency) ----
|
|
261
|
+
// Reads uncompressed and FlateDecode content streams of simple-font text and
|
|
262
|
+
// follows the page tree; says precisely what it cannot read: encryption,
|
|
263
|
+
// object/xref streams (PDF 1.5 compressed objects), composite (Type0) fonts,
|
|
264
|
+
// other stream filters and pages with images but no text (scans).
|
|
265
|
+
|
|
266
|
+
const latin1 = (bytes) => { let s = ""; for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode(...bytes.subarray(i, i + 8192)); return s; };
|
|
267
|
+
const toBytes = (s) => { const b = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i) & 255; return b; };
|
|
268
|
+
|
|
269
|
+
async function inflate(bytes) {
|
|
270
|
+
if (typeof DecompressionStream !== "function") throw new Error("this runtime has no DecompressionStream");
|
|
271
|
+
const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
|
|
272
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function parseObjects(s) {
|
|
276
|
+
const objs = new Map();
|
|
277
|
+
const re = /(\d+)\s+(\d+)\s+obj\b/g;
|
|
278
|
+
let m;
|
|
279
|
+
while ((m = re.exec(s))) {
|
|
280
|
+
const end = s.indexOf("endobj", re.lastIndex);
|
|
281
|
+
const body = s.slice(re.lastIndex, end < 0 ? s.length : end);
|
|
282
|
+
const sm = /\bstream\r?\n/.exec(body);
|
|
283
|
+
let dict = body, data = null;
|
|
284
|
+
if (sm) {
|
|
285
|
+
dict = body.slice(0, sm.index);
|
|
286
|
+
const e = body.lastIndexOf("endstream");
|
|
287
|
+
let raw = body.slice(sm.index + sm[0].length, e < 0 ? body.length : e);
|
|
288
|
+
const len = /\/Length\s+(\d+)(?!\s+\d+\s+R)/.exec(dict)?.[1];
|
|
289
|
+
raw = len !== undefined && Number(len) <= raw.length ? raw.slice(0, Number(len)) : raw.replace(/\r?\n$/, "");
|
|
290
|
+
data = raw;
|
|
291
|
+
}
|
|
292
|
+
objs.set(Number(m[1]), { dict, data });
|
|
293
|
+
if (end > 0) re.lastIndex = end;
|
|
294
|
+
}
|
|
295
|
+
return objs;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// A sandbox module imports nothing, so this is its own copy of src/util/regexp.js escapeRegExp: a name interpolated into a RegExp is text, never syntax.
|
|
299
|
+
const escapeRegExp = (text) => String(text).replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
|
|
300
|
+
|
|
301
|
+
const refOf = (dict, key) => { const m = new RegExp(`/${escapeRegExp(key)}\\s+(\\d+)\\s+\\d+\\s+R`).exec(dict); return m ? Number(m[1]) : null; };
|
|
302
|
+
|
|
303
|
+
function pdfString(src, pos) {
|
|
304
|
+
// src[pos] === "("; returns [bytesAsLatin1String, nextPos]
|
|
305
|
+
let depth = 1, out = "", i = pos + 1;
|
|
306
|
+
while (i < src.length && depth > 0) {
|
|
307
|
+
const c = src[i];
|
|
308
|
+
if (c === "\\") {
|
|
309
|
+
const d = src[i + 1];
|
|
310
|
+
if (d === "n") out += "\n"; else if (d === "r") out += "\r"; else if (d === "t") out += "\t"; else if (d === "b") out += "\b"; else if (d === "f") out += "\f";
|
|
311
|
+
else if (/[0-7]/.test(d)) { const o = /^[0-7]{1,3}/.exec(src.slice(i + 1, i + 4))[0]; out += String.fromCharCode(parseInt(o, 8) & 255); i += o.length - 1; }
|
|
312
|
+
else if (d === "\n") { /* line continuation */ } else if (d === "\r") { if (src[i + 2] === "\n") i++; } else out += d;
|
|
313
|
+
i += 2; continue;
|
|
314
|
+
}
|
|
315
|
+
if (c === "(") depth++;
|
|
316
|
+
else if (c === ")") { depth--; if (!depth) break; }
|
|
317
|
+
out += c; i++;
|
|
318
|
+
}
|
|
319
|
+
return [out, i + 1];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The text of one content stream: strings shown by the Tj, TJ and quote operators, with line breaks from the positioning operators. */
|
|
323
|
+
function contentText(src, composite) {
|
|
324
|
+
let out = "";
|
|
325
|
+
let stack = [];
|
|
326
|
+
let i = 0, lastY = null;
|
|
327
|
+
const nl = () => { if (out && !out.endsWith("\n")) out += "\n"; };
|
|
328
|
+
while (i < src.length) {
|
|
329
|
+
const c = src[i];
|
|
330
|
+
if (c === "(") { const [s, next] = pdfString(src, i); stack.push({ s }); i = next; continue; }
|
|
331
|
+
if (c === "<" && src[i + 1] !== "<") {
|
|
332
|
+
const e = src.indexOf(">", i);
|
|
333
|
+
if (e < 0) break;
|
|
334
|
+
const hex = src.slice(i + 1, e).replace(/\s+/g, "");
|
|
335
|
+
stack.push({ hex: composite ? null : hex.length % 2 ? `${hex}0` : hex });
|
|
336
|
+
i = e + 1; continue;
|
|
337
|
+
}
|
|
338
|
+
if (c === "[") { stack.push({ open: true }); i++; continue; }
|
|
339
|
+
if (c === "]") {
|
|
340
|
+
const at = stack.map((x) => x.open).lastIndexOf(true);
|
|
341
|
+
const items = stack.splice(at < 0 ? 0 : at);
|
|
342
|
+
stack.push({ array: items.slice(1) }); i++; continue;
|
|
343
|
+
}
|
|
344
|
+
if (c === "%") { const e = src.indexOf("\n", i); i = e < 0 ? src.length : e + 1; continue; }
|
|
345
|
+
if (/[\s]/.test(c)) { i++; continue; }
|
|
346
|
+
const tok = /^[^\s()<>[\]/%]+/.exec(src.slice(i, i + 40))?.[0];
|
|
347
|
+
if (c === "/") { const t = /^\/[^\s()<>[\]/%]*/.exec(src.slice(i, i + 80))[0]; stack.push({ name: t }); i += t.length; continue; }
|
|
348
|
+
if (!tok) { i++; continue; }
|
|
349
|
+
i += tok.length;
|
|
350
|
+
if (/^[+-]?(\d+\.?\d*|\.\d+)$/.test(tok)) { stack.push({ num: Number(tok) }); continue; }
|
|
351
|
+
const str = (x) => (x.s !== undefined ? x.s : x.hex ? x.hex.replace(/../g, (h) => String.fromCharCode(parseInt(h, 16))) : "");
|
|
352
|
+
if (tok === "Tj" || tok === "'" || tok === '"') {
|
|
353
|
+
if (tok !== "Tj") nl();
|
|
354
|
+
const last = stack[stack.length - 1];
|
|
355
|
+
if (last) out += str(last);
|
|
356
|
+
} else if (tok === "TJ") {
|
|
357
|
+
const last = stack[stack.length - 1];
|
|
358
|
+
for (const x of last?.array ?? []) { if (x.num !== undefined) { if (x.num < -200 && out && !/\s$/.test(out)) out += " "; } else out += str(x); }
|
|
359
|
+
} else if (tok === "T*" || tok === "ET") nl();
|
|
360
|
+
else if (tok === "Td" || tok === "TD") { const y = stack[stack.length - 1]?.num; if (y !== 0) nl(); else if (out && !/\s$/.test(out)) out += " "; }
|
|
361
|
+
else if (tok === "Tm") { const y = stack[stack.length - 1]?.num; if (lastY !== null && y !== lastY) nl(); lastY = y; }
|
|
362
|
+
stack = [];
|
|
363
|
+
}
|
|
364
|
+
return out;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export async function extractPdf(bytes) {
|
|
368
|
+
const s = latin1(bytes);
|
|
369
|
+
if (!s.startsWith("%PDF-")) return { status: "unsupported", reason: "not a PDF (no %PDF- header)" };
|
|
370
|
+
if (/\/Encrypt\s+(\d+\s+\d+\s+R|<<)/.test(s)) return { status: "encrypted", reason: "the PDF is encrypted: decrypt it first (mallory reads no encrypted PDFs)" };
|
|
371
|
+
const objs = parseObjects(s);
|
|
372
|
+
if (!objs.size) return { status: "unsupported", reason: "no readable PDF objects" };
|
|
373
|
+
const composite = [...objs.values()].some((o) => /\/Subtype\s*\/Type0\b/.test(o.dict));
|
|
374
|
+
const hasObjStm = [...objs.values()].some((o) => /\/Type\s*\/(ObjStm|XRef)\b/.test(o.dict));
|
|
375
|
+
const isPage = (o) => /\/Type\s*\/Page\b(?!s)/.test(o.dict);
|
|
376
|
+
// page order: the catalog's page tree; else the file order
|
|
377
|
+
const order = [];
|
|
378
|
+
const catalog = [...objs.values()].find((o) => /\/Type\s*\/Catalog\b/.test(o.dict));
|
|
379
|
+
const walk = (id, depth) => {
|
|
380
|
+
const o = objs.get(id);
|
|
381
|
+
if (!o || depth > 32) return;
|
|
382
|
+
if (isPage(o)) { order.push(id); return; }
|
|
383
|
+
const kids = /\/Kids\s*\[([^\]]*)\]/.exec(o.dict)?.[1];
|
|
384
|
+
for (const k of kids?.matchAll(/(\d+)\s+\d+\s+R/g) ?? []) walk(Number(k[1]), depth + 1);
|
|
385
|
+
};
|
|
386
|
+
const root = catalog ? refOf(catalog.dict, "Pages") : null;
|
|
387
|
+
if (root) walk(root, 0);
|
|
388
|
+
if (!order.length) for (const [id, o] of objs) if (isPage(o)) order.push(id);
|
|
389
|
+
if (!order.length) return { status: "unsupported", reason: hasObjStm ? "the page tree is inside a compressed object stream (PDF 1.5 object streams are not read)" : "no pages found" };
|
|
390
|
+
const warnings = [];
|
|
391
|
+
const sawImages = [];
|
|
392
|
+
const pages = [];
|
|
393
|
+
let text = "";
|
|
394
|
+
let skipped = 0;
|
|
395
|
+
for (let p = 0; p < order.length; p++) {
|
|
396
|
+
const page = objs.get(order[p]);
|
|
397
|
+
const refs = [];
|
|
398
|
+
const arr = /\/Contents\s*\[([^\]]*)\]/.exec(page.dict)?.[1];
|
|
399
|
+
if (arr) for (const m of arr.matchAll(/(\d+)\s+\d+\s+R/g)) refs.push(Number(m[1]));
|
|
400
|
+
else { const one = refOf(page.dict, "Contents"); if (one) refs.push(one); }
|
|
401
|
+
let pageText = "";
|
|
402
|
+
let unreadable = false;
|
|
403
|
+
for (const ref of refs) {
|
|
404
|
+
const o = objs.get(ref);
|
|
405
|
+
if (!o || o.data === null) continue;
|
|
406
|
+
let data = o.data;
|
|
407
|
+
const filters = [...o.dict.matchAll(/\/(FlateDecode|Fl|ASCII85Decode|ASCIIHexDecode|LZWDecode|RunLengthDecode|DCTDecode|CCITTFaxDecode|JBIG2Decode|JPXDecode|Crypt)\b/g)].map((m) => m[1]);
|
|
408
|
+
if (filters.length > 1 || (filters[0] && filters[0] !== "FlateDecode" && filters[0] !== "Fl")) { unreadable = true; warnings.push(`page ${p + 1}: content filter ${filters.join("+")} is not read`); continue; }
|
|
409
|
+
try {
|
|
410
|
+
if (filters.length) data = latin1(await inflate(toBytes(data)));
|
|
411
|
+
} catch (e) { unreadable = true; warnings.push(`page ${p + 1}: could not decompress its content (${e.message})`); continue; }
|
|
412
|
+
pageText += `${contentText(data, composite)}\n`;
|
|
413
|
+
if (/\bDo\b/.test(data)) sawImages.push(p + 1);
|
|
414
|
+
}
|
|
415
|
+
pageText = pageText.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
416
|
+
if (unreadable) skipped++;
|
|
417
|
+
if (/\/XObject/.test(page.dict) && !sawImages.includes(p + 1) && !pageText) sawImages.push(p + 1);
|
|
418
|
+
if (text) text += "\n\n";
|
|
419
|
+
const start = text.length;
|
|
420
|
+
text += pageText;
|
|
421
|
+
pages.push({ page: p + 1, start, end: text.length });
|
|
422
|
+
}
|
|
423
|
+
if (composite) warnings.push("composite (Type0/CID) fonts: their text needs a font map and was skipped");
|
|
424
|
+
const readable = text.trim().length;
|
|
425
|
+
if (!readable) {
|
|
426
|
+
if (sawImages.length || /\/Subtype\s*\/Image\b/.test(s)) return { status: "scanned", reason: "the pages hold images and no text (a scan): run OCR first" };
|
|
427
|
+
return { status: composite ? "unsupported" : "empty", reason: composite ? "its text is in composite fonts, which are not read" : "no text was found" };
|
|
428
|
+
}
|
|
429
|
+
return { text, headings: [], pages, warnings, ...(skipped || composite || sawImages.length ? { status: "partial", reason: [skipped && `${skipped} page(s) unreadable`, composite && "composite fonts skipped", sawImages.length && `pages ${sawImages.slice(0, 5).join(", ")} also hold images`].filter(Boolean).join("; ") } : {}) };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// ---- DOCX and EPUB (ZIP containers read with the platform's inflate; nothing in them is run) ----
|
|
433
|
+
|
|
434
|
+
const ZIP_LIMITS = { maxEntries: 5000, maxEntryBytes: 32 * 1024 * 1024, maxTotalBytes: 96 * 1024 * 1024 };
|
|
435
|
+
|
|
436
|
+
async function inflateRaw(bytes, limit) {
|
|
437
|
+
if (typeof DecompressionStream !== "function") throw new Error("this runtime has no DecompressionStream");
|
|
438
|
+
const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader();
|
|
439
|
+
const parts = [];
|
|
440
|
+
let size = 0;
|
|
441
|
+
for (;;) {
|
|
442
|
+
const { done, value } = await reader.read();
|
|
443
|
+
if (done) break;
|
|
444
|
+
size += value.length;
|
|
445
|
+
if (size > limit) { await reader.cancel(); throw new Error(`an entry inflates to more than ${limit} bytes`); }
|
|
446
|
+
parts.push(value);
|
|
447
|
+
}
|
|
448
|
+
const out = new Uint8Array(size);
|
|
449
|
+
let at = 0;
|
|
450
|
+
for (const p of parts) { out.set(p, at); at += p.length; }
|
|
451
|
+
return out;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The central directory of a ZIP file: `{ names, has(name), read(name) }`. `read` resolves to the entry's bytes (stored or
|
|
456
|
+
* deflated) and refuses an entry that inflates past the limits (a zip bomb) or that is encrypted. ZIP64 archives are refused.
|
|
457
|
+
*/
|
|
458
|
+
export function openZip(bytes) {
|
|
459
|
+
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
460
|
+
let eocd = -1;
|
|
461
|
+
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 22 - 65535); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
|
|
462
|
+
if (eocd < 0) throw new Error("not a ZIP file (no end-of-archive record)");
|
|
463
|
+
const count = dv.getUint16(eocd + 10, true);
|
|
464
|
+
let at = dv.getUint32(eocd + 16, true);
|
|
465
|
+
if (count === 0xffff || at === 0xffffffff) throw new Error("ZIP64 archives are not read");
|
|
466
|
+
if (count > ZIP_LIMITS.maxEntries) throw new Error(`the archive has ${count} entries, over the limit of ${ZIP_LIMITS.maxEntries}`);
|
|
467
|
+
const entries = new Map();
|
|
468
|
+
for (let n = 0; n < count; n++) {
|
|
469
|
+
if (at + 46 > bytes.length || dv.getUint32(at, true) !== 0x02014b50) throw new Error("the archive's directory is damaged");
|
|
470
|
+
const nameLen = dv.getUint16(at + 28, true), extraLen = dv.getUint16(at + 30, true), commentLen = dv.getUint16(at + 32, true);
|
|
471
|
+
if (at + 46 + nameLen > bytes.length) throw new Error("the archive's directory is damaged");
|
|
472
|
+
const name = new TextDecoder().decode(bytes.subarray(at + 46, at + 46 + nameLen));
|
|
473
|
+
entries.set(name, { flags: dv.getUint16(at + 8, true), method: dv.getUint16(at + 10, true), size: dv.getUint32(at + 20, true), usize: dv.getUint32(at + 24, true), offset: dv.getUint32(at + 42, true) });
|
|
474
|
+
at += 46 + nameLen + extraLen + commentLen;
|
|
475
|
+
}
|
|
476
|
+
let total = 0;
|
|
477
|
+
return {
|
|
478
|
+
names: [...entries.keys()],
|
|
479
|
+
has: (name) => entries.has(name),
|
|
480
|
+
async read(name) {
|
|
481
|
+
const e = entries.get(name);
|
|
482
|
+
if (!e) throw new Error(`the archive has no ${name}`);
|
|
483
|
+
if (e.flags & 1) throw new Error("the archive is encrypted");
|
|
484
|
+
if (e.usize > ZIP_LIMITS.maxEntryBytes) throw new Error(`${name} is over the ${ZIP_LIMITS.maxEntryBytes} byte entry limit`);
|
|
485
|
+
total += e.usize;
|
|
486
|
+
if (total > ZIP_LIMITS.maxTotalBytes) throw new Error("the archive is over the total size limit");
|
|
487
|
+
if (e.offset + 30 > bytes.length || dv.getUint32(e.offset, true) !== 0x04034b50) throw new Error(`${name}: its local header is damaged`);
|
|
488
|
+
const start = e.offset + 30 + dv.getUint16(e.offset + 26, true) + dv.getUint16(e.offset + 28, true);
|
|
489
|
+
const raw = bytes.subarray(start, start + e.size);
|
|
490
|
+
if (raw.length !== e.size) throw new Error(`${name}: truncated`);
|
|
491
|
+
if (e.method === 0) return raw.slice();
|
|
492
|
+
if (e.method !== 8) throw new Error(`${name}: compression method ${e.method} is not read`);
|
|
493
|
+
return inflateRaw(raw, Math.min(ZIP_LIMITS.maxEntryBytes, e.usize + 1024));
|
|
494
|
+
},
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const utf8 = (b) => new TextDecoder("utf-8").decode(b).replace(/^/, "");
|
|
499
|
+
const attrOf = (tag, name) => { const m = new RegExp(`(?:^|\\s)${escapeRegExp(name)}\\s*=\\s*("([^"]*)"|'([^']*)')`).exec(tag); return m ? decodeEntities(m[2] ?? m[3]) : undefined; };
|
|
500
|
+
|
|
501
|
+
// The main part of a Word file; spelled with a template so the test that scans this module for the DOM's `document.` stays exact.
|
|
502
|
+
const DOCX_MAIN = `word/${"document"}.xml`;
|
|
503
|
+
|
|
504
|
+
/** A Word document (.docx): paragraphs of its main part, headings from the Title and Heading n styles. Text only: no images, comments, notes or tracked deletions. */
|
|
505
|
+
export async function extractDocx(bytes) {
|
|
506
|
+
let zip;
|
|
507
|
+
try { zip = openZip(bytes); } catch (e) { return { status: "unsupported", reason: `not a readable DOCX: ${e.message}` }; }
|
|
508
|
+
if (!zip.has(DOCX_MAIN)) return { status: "unsupported", reason: `not a Word document (no ${DOCX_MAIN})` };
|
|
509
|
+
if (zip.has("EncryptedPackage")) return { status: "encrypted", reason: "the document is password-protected: remove the password first" };
|
|
510
|
+
let xml;
|
|
511
|
+
try { xml = utf8(await zip.read(DOCX_MAIN)); } catch (e) { return { status: "unsupported", reason: `could not read the document: ${e.message}` }; }
|
|
512
|
+
let text = "";
|
|
513
|
+
const headings = [];
|
|
514
|
+
for (const pm of xml.matchAll(/<w:p(?:\s[^>]*)?>([\s\S]*?)<\/w:p>/g)) {
|
|
515
|
+
const body = pm[1];
|
|
516
|
+
let line = "";
|
|
517
|
+
for (const t of body.matchAll(/<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>|<w:tab\s*\/>|<w:(?:br|cr)\s*\/>/g)) line += t[1] !== undefined ? decodeEntities(t[1]) : t[0].startsWith("<w:tab") ? "\t" : "\n";
|
|
518
|
+
if (!line.trim()) continue;
|
|
519
|
+
const style = /<w:pStyle\s[^>]*w:val="([^"]*)"/.exec(body)?.[1] ?? "";
|
|
520
|
+
const level = /^title$/i.test(style) ? 1 : Number(/^heading\s*([1-6])$/i.exec(style)?.[1]) || 0;
|
|
521
|
+
if (text) text += "\n\n";
|
|
522
|
+
if (level) headings.push({ level, title: line.replace(/\s+/g, " ").trim(), start: text.length });
|
|
523
|
+
text += line.replace(/[ \t]+$/g, "");
|
|
524
|
+
}
|
|
525
|
+
const warnings = [];
|
|
526
|
+
if (zip.names.some((n) => /^word\/(footnotes|endnotes|comments)\.xml$/.test(n))) warnings.push("footnotes, endnotes and comments are not read");
|
|
527
|
+
return { text, headings, warnings };
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const dirOf = (path) => (path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "");
|
|
531
|
+
function resolvePath(base, href) {
|
|
532
|
+
const parts = (base + decodeURIComponent(href.split("#")[0])).split("/");
|
|
533
|
+
const out = [];
|
|
534
|
+
for (const p of parts) { if (p === "..") out.pop(); else if (p && p !== ".") out.push(p); }
|
|
535
|
+
return out.join("/");
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** An EPUB: the spine's XHTML files in reading order, each read as HTML; every chapter's headings are kept. */
|
|
539
|
+
export async function extractEpub(bytes) {
|
|
540
|
+
let zip;
|
|
541
|
+
try { zip = openZip(bytes); } catch (e) { return { status: "unsupported", reason: `not a readable EPUB: ${e.message}` }; }
|
|
542
|
+
try {
|
|
543
|
+
if (!zip.has("META-INF/container.xml")) return { status: "unsupported", reason: "not an EPUB (no META-INF/container.xml)" };
|
|
544
|
+
if (zip.has("META-INF/encryption.xml")) {
|
|
545
|
+
const algorithms = [...utf8(await zip.read("META-INF/encryption.xml")).matchAll(/Algorithm="([^"]*)"/g)].map((m) => m[1]);
|
|
546
|
+
if (algorithms.some((a) => a !== "http://www.idpf.org/2008/embedding" && a !== "http://ns.adobe.com/pdf/enc#RC")) return { status: "encrypted", reason: "the EPUB's content is protected (DRM): it is not read" };
|
|
547
|
+
}
|
|
548
|
+
const container = utf8(await zip.read("META-INF/container.xml"));
|
|
549
|
+
const rootTag = /<rootfile\b[^>]*>/.exec(container)?.[0];
|
|
550
|
+
const opfPath = rootTag && attrOf(rootTag, "full-path");
|
|
551
|
+
if (!opfPath || !zip.has(opfPath)) return { status: "unsupported", reason: "the EPUB names no package file" };
|
|
552
|
+
const opf = utf8(await zip.read(opfPath));
|
|
553
|
+
const base = dirOf(opfPath);
|
|
554
|
+
const manifest = new Map();
|
|
555
|
+
for (const m of opf.matchAll(/<item\b[^>]*>/g)) { const id = attrOf(m[0], "id"), href = attrOf(m[0], "href"); if (id && href) manifest.set(id, { href, type: attrOf(m[0], "media-type") ?? "" }); }
|
|
556
|
+
const spine = [...opf.matchAll(/<itemref\b[^>]*>/g)].map((m) => attrOf(m[0], "idref")).filter(Boolean);
|
|
557
|
+
if (!spine.length) return { status: "unsupported", reason: "the EPUB's spine is empty" };
|
|
558
|
+
let text = "";
|
|
559
|
+
const headings = [];
|
|
560
|
+
const warnings = [];
|
|
561
|
+
let missing = 0;
|
|
562
|
+
for (const id of spine.slice(0, 2000)) {
|
|
563
|
+
const item = manifest.get(id);
|
|
564
|
+
if (!item || !/html|xml/.test(item.type)) continue;
|
|
565
|
+
const path = resolvePath(base, item.href);
|
|
566
|
+
if (!zip.has(path)) { missing++; continue; }
|
|
567
|
+
const chapter = htmlToText(utf8(await zip.read(path)));
|
|
568
|
+
if (!chapter.text.trim()) continue;
|
|
569
|
+
if (text) text += "\n\n";
|
|
570
|
+
for (const h of chapter.headings) headings.push({ ...h, start: h.start + text.length });
|
|
571
|
+
text += chapter.text;
|
|
572
|
+
if (text.length > LIMITS.maxChars) { warnings.push("stopped at the character limit"); break; }
|
|
573
|
+
}
|
|
574
|
+
if (missing) warnings.push(`${missing} chapter file(s) listed in the spine are missing`);
|
|
575
|
+
return { text, headings, warnings };
|
|
576
|
+
} catch (e) {
|
|
577
|
+
return { status: "unsupported", reason: `could not read the EPUB: ${e.message}` };
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// ---- opt-in adapters: pdf.js and OCR ----
|
|
582
|
+
// Both are handed in by the caller (an import pane for pdf.js, a OCR library or service wrapped as a function), so
|
|
583
|
+
// this module imports nothing and makes no request itself; whatever they fetch goes through the canvas's network rules.
|
|
584
|
+
|
|
585
|
+
const IMAGE_TYPES = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", bmp: "image/bmp", tif: "image/tiff", tiff: "image/tiff" };
|
|
586
|
+
const ocrText = (r) => (typeof r === "string" ? r : r && typeof r.text === "string" ? r.text : "");
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* A PDF read by pdf.js (pass its module as `pdfjs`: `getDocument` is the only thing used): every page's text items in
|
|
590
|
+
* reading order, which reads object/xref streams, composite fonts and every standard filter. A page with no text is
|
|
591
|
+
* handed to `ocr` as a rendered PNG when both an `ocr` function and a canvas (OffscreenCanvas) exist, else the PDF is `scanned`.
|
|
592
|
+
*/
|
|
593
|
+
export async function extractPdfWithPdfjs(bytes, pdfjs, { ocr } = {}) {
|
|
594
|
+
if (!pdfjs || typeof pdfjs.getDocument !== "function") throw new Error("the pdfjs adapter needs getDocument (pass the pdfjs-dist module)");
|
|
595
|
+
let task;
|
|
596
|
+
let pdf;
|
|
597
|
+
try {
|
|
598
|
+
task = pdfjs.getDocument({ data: bytes.slice(), isEvalSupported: false, useSystemFonts: false, disableFontFace: true });
|
|
599
|
+
pdf = await (task.promise ?? task);
|
|
600
|
+
} catch (e) {
|
|
601
|
+
if (e?.name === "PasswordException" || /password/i.test(String(e?.message))) return { status: "encrypted", reason: "the PDF is password-protected: decrypt it first" };
|
|
602
|
+
return { status: "unsupported", reason: `pdf.js could not open it: ${e?.message ?? e}` };
|
|
603
|
+
}
|
|
604
|
+
try {
|
|
605
|
+
const pages = [];
|
|
606
|
+
const warnings = [];
|
|
607
|
+
let text = "";
|
|
608
|
+
let ocred = 0, blank = 0;
|
|
609
|
+
for (let p = 1; p <= Math.min(pdf.numPages, 2000); p++) {
|
|
610
|
+
const page = await pdf.getPage(p);
|
|
611
|
+
let pageText = "";
|
|
612
|
+
try {
|
|
613
|
+
const content = await page.getTextContent();
|
|
614
|
+
let lastY = null;
|
|
615
|
+
for (const it of content.items) {
|
|
616
|
+
if (typeof it.str !== "string") continue;
|
|
617
|
+
const y = Array.isArray(it.transform) ? Math.round(it.transform[5]) : null;
|
|
618
|
+
if (pageText && lastY !== null && y !== null && Math.abs(y - lastY) > 2 && !pageText.endsWith("\n")) pageText += "\n";
|
|
619
|
+
pageText += it.str;
|
|
620
|
+
if (it.hasEOL) pageText += "\n";
|
|
621
|
+
if (y !== null && it.str) lastY = y;
|
|
622
|
+
}
|
|
623
|
+
pageText = pageText.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
624
|
+
if (!pageText && typeof ocr === "function") {
|
|
625
|
+
const png = await renderPagePng(page);
|
|
626
|
+
if (png) { pageText = ocrText(await ocr({ name: `page ${p}`, type: "image/png", bytes: png, page: p })).trim(); if (pageText) ocred++; }
|
|
627
|
+
}
|
|
628
|
+
} finally { page.cleanup?.(); }
|
|
629
|
+
if (!pageText) blank++;
|
|
630
|
+
if (text) text += "\n\n";
|
|
631
|
+
const start = text.length;
|
|
632
|
+
text += pageText;
|
|
633
|
+
pages.push({ page: p, start, end: text.length });
|
|
634
|
+
if (text.length > LIMITS.maxChars) { warnings.push(`stopped at page ${p}: the character limit`); break; }
|
|
635
|
+
}
|
|
636
|
+
if (!text.trim()) return { status: "scanned", reason: typeof ocr === "function" ? "no text was found, and the pages could not be rendered or read for OCR" : "the pages hold no text (a scan): pass an ocr adapter" };
|
|
637
|
+
if (ocred) warnings.push(`${ocred} page(s) were read with OCR`);
|
|
638
|
+
return { text, headings: [], pages, warnings, ...(blank ? { status: "partial", reason: `${blank} page(s) had no text` } : {}) };
|
|
639
|
+
} finally {
|
|
640
|
+
try { await (pdf.destroy?.() ?? task?.destroy?.()); } catch { /* the document is already gone */ }
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
async function renderPagePng(page) {
|
|
645
|
+
if (typeof OffscreenCanvas !== "function" || typeof page.getViewport !== "function" || typeof page.render !== "function") return null;
|
|
646
|
+
const viewport = page.getViewport({ scale: 2 });
|
|
647
|
+
const canvas = new OffscreenCanvas(Math.ceil(viewport.width), Math.ceil(viewport.height));
|
|
648
|
+
const ctx = canvas.getContext("2d");
|
|
649
|
+
if (!ctx) return null;
|
|
650
|
+
const job = page.render({ canvasContext: ctx, viewport });
|
|
651
|
+
await (job.promise ?? job);
|
|
652
|
+
return new Uint8Array(await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer());
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async function extractImage(src, ocr) {
|
|
656
|
+
const out = ocrText(await ocr({ name: src.name, type: src.type || IMAGE_TYPES[/\.([A-Za-z0-9]+)$/.exec(src.name)?.[1]?.toLowerCase()] || "image/png", bytes: src.bytes }));
|
|
657
|
+
return { text: normalizeText(out).trim(), headings: [], warnings: ["read with OCR: expect recognition mistakes"] };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// ---- chunking ----
|
|
661
|
+
|
|
662
|
+
/** Chunk size/overlap are in characters. */
|
|
663
|
+
export function normalizeChunkOptions({ size = 800, overlap = 100 } = {}) {
|
|
664
|
+
const s = Math.max(50, Math.min(20000, Math.floor(Number(size)) || 800));
|
|
665
|
+
const o = Math.max(0, Math.min(Math.floor(s / 2), Math.floor(Number(overlap)) || 0));
|
|
666
|
+
return { size: s, overlap: o };
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** The heading titles in effect at a position (the nearest of each level above it). */
|
|
670
|
+
export function headingPath(headings, pos) {
|
|
671
|
+
const path = [];
|
|
672
|
+
for (const h of headings) {
|
|
673
|
+
if (h.start > pos) break;
|
|
674
|
+
path.length = Math.min(path.length, h.level - 1);
|
|
675
|
+
while (path.length < h.level - 1) path.push(null);
|
|
676
|
+
path[h.level - 1] = h.title;
|
|
677
|
+
}
|
|
678
|
+
return path.filter((x) => x !== null);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function pageAt(pages, pos) {
|
|
682
|
+
if (!pages) return undefined;
|
|
683
|
+
let last = pages[0]?.page;
|
|
684
|
+
for (const p of pages) { if (p.start > pos) break; last = p.page; }
|
|
685
|
+
return last;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function unitsOf(text, headings, size) {
|
|
689
|
+
const cuts = new Set([0, text.length]);
|
|
690
|
+
const headingStarts = new Set(headings.map((h) => h.start));
|
|
691
|
+
for (const h of headingStarts) cuts.add(h);
|
|
692
|
+
for (const m of text.matchAll(/\n[ \t]*\n\s*/g)) cuts.add(m.index + m[0].length);
|
|
693
|
+
const sorted = [...cuts].filter((c) => c >= 0 && c <= text.length).sort((a, b) => a - b);
|
|
694
|
+
const units = [];
|
|
695
|
+
const push = (s, e, heading) => {
|
|
696
|
+
while (s < e && /\s/.test(text[s])) s++;
|
|
697
|
+
while (e > s && /\s/.test(text[e - 1])) e--;
|
|
698
|
+
if (e > s) units.push({ s, e, heading });
|
|
699
|
+
};
|
|
700
|
+
// cut a stretch that is longer than a chunk at spaces (or exactly, with no space)
|
|
701
|
+
const wrap = (s, e, heading) => {
|
|
702
|
+
let a = s, first = true;
|
|
703
|
+
while (e - a > size) {
|
|
704
|
+
let cut = text.lastIndexOf(" ", a + size);
|
|
705
|
+
if (cut <= a) cut = a + size;
|
|
706
|
+
push(a, cut, heading && first);
|
|
707
|
+
first = false;
|
|
708
|
+
a = cut;
|
|
709
|
+
}
|
|
710
|
+
push(a, e, heading && first);
|
|
711
|
+
};
|
|
712
|
+
for (let k = 0; k + 1 < sorted.length; k++) {
|
|
713
|
+
const s = sorted[k], e = sorted[k + 1];
|
|
714
|
+
const heading = headingStarts.has(s);
|
|
715
|
+
if (e - s <= size) { push(s, e, heading); continue; }
|
|
716
|
+
// a long paragraph: its sentences are the units
|
|
717
|
+
const ends = [s];
|
|
718
|
+
for (const m of text.slice(s, e).matchAll(/[.!?]+["')\]]*\s+/g)) ends.push(s + m.index + m[0].length);
|
|
719
|
+
ends.push(e);
|
|
720
|
+
let first = true;
|
|
721
|
+
for (let q = 0; q + 1 < ends.length; q++) {
|
|
722
|
+
if (ends[q + 1] <= ends[q]) continue;
|
|
723
|
+
if (ends[q + 1] - ends[q] > size) wrap(ends[q], ends[q + 1], heading && first);
|
|
724
|
+
else push(ends[q], ends[q + 1], heading && first);
|
|
725
|
+
first = false;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return units;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Chunks of one extracted document: `{ id, doc, index, start, end, text, headings, page?, pageEnd? }`.
|
|
733
|
+
* Sentence- and paragraph-aligned, never across a heading, up to `size` characters, the last sentences
|
|
734
|
+
* repeated at the start of the next chunk up to `overlap`. `id` depends only on the document name and the
|
|
735
|
+
* chunk's text (and, for a repeated text, its order), not on its position: the same on every run, unchanged when other documents
|
|
736
|
+
* change, and unchanged for chunks after an edit that moves them.
|
|
737
|
+
*/
|
|
738
|
+
export function chunkDocument(doc, options = {}) {
|
|
739
|
+
const { size, overlap } = normalizeChunkOptions(options);
|
|
740
|
+
const units = unitsOf(doc.text, doc.headings ?? [], size);
|
|
741
|
+
const chunks = [];
|
|
742
|
+
const seen = new Map();
|
|
743
|
+
let i = 0;
|
|
744
|
+
while (i < units.length) {
|
|
745
|
+
const start = units[i].s;
|
|
746
|
+
let j = i;
|
|
747
|
+
while (j + 1 < units.length && !units[j + 1].heading && units[j + 1].e - start <= size) j++;
|
|
748
|
+
const end = units[j].e;
|
|
749
|
+
const text = doc.text.slice(start, end);
|
|
750
|
+
const index = chunks.length;
|
|
751
|
+
const nth = seen.get(text) ?? 0; // the same text twice in a document is told apart by order
|
|
752
|
+
seen.set(text, nth + 1);
|
|
753
|
+
chunks.push({
|
|
754
|
+
id: `c_${hashOf(doc.name, text, String(nth)).slice(0, 12)}`,
|
|
755
|
+
doc: doc.name, index, start, end, text, headings: headingPath(doc.headings ?? [], start),
|
|
756
|
+
...(doc.pages ? { page: pageAt(doc.pages, start), pageEnd: pageAt(doc.pages, Math.max(start, end - 1)) } : {}),
|
|
757
|
+
});
|
|
758
|
+
if (j + 1 >= units.length) break;
|
|
759
|
+
let next = j + 1;
|
|
760
|
+
if (overlap > 0 && !units[j + 1].heading) {
|
|
761
|
+
for (let k = i + 1; k <= j; k++) {
|
|
762
|
+
if (units[j].e - units[k].s <= overlap && units[j + 1].e - units[k].s <= size) { next = k; break; }
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
i = next;
|
|
766
|
+
}
|
|
767
|
+
return chunks;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// ---- embedders ----
|
|
771
|
+
|
|
772
|
+
const STOP = new Set("a an and are as at be but by for from has have in is it its of on or that the this to was were will with not no do does did can could should would".split(" "));
|
|
773
|
+
|
|
774
|
+
export function tokens(text) {
|
|
775
|
+
const out = [];
|
|
776
|
+
for (const m of text.toLowerCase().normalize("NFKC").matchAll(/[\p{L}\p{N}]+/gu)) {
|
|
777
|
+
let t = m[0];
|
|
778
|
+
if (STOP.has(t)) continue;
|
|
779
|
+
if (t.length > 4 && t.endsWith("ies")) t = `${t.slice(0, -3)}y`;
|
|
780
|
+
else if (t.length > 3 && t.endsWith("s") && !t.endsWith("ss")) t = t.slice(0, -1);
|
|
781
|
+
out.push(t);
|
|
782
|
+
}
|
|
783
|
+
return out;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function fnv(token, seed) {
|
|
787
|
+
let h = seed >>> 0;
|
|
788
|
+
for (let i = 0; i < token.length; i++) { h ^= token.charCodeAt(i); h = Math.imul(h, 16777619); }
|
|
789
|
+
return h >>> 0;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const round = (x) => Math.round(x * 1e4) / 1e4;
|
|
793
|
+
|
|
794
|
+
/** The embedding of one text with the hashing trick: signed, log-scaled term counts in `dim` buckets, unit length. Deterministic everywhere. */
|
|
795
|
+
export function hashEmbed(text, dim) {
|
|
796
|
+
const v = new Array(dim).fill(0);
|
|
797
|
+
const counts = new Map();
|
|
798
|
+
for (const t of tokens(text)) counts.set(t, (counts.get(t) ?? 0) + 1);
|
|
799
|
+
for (const [t, c] of counts) v[fnv(t, 2166136261) % dim] += (fnv(t, 97) & 1 ? 1 : -1) * (1 + Math.log(c));
|
|
800
|
+
const norm = Math.sqrt(v.reduce((a, x) => a + x * x, 0)) || 1;
|
|
801
|
+
return v.map((x) => round(x / norm));
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* The embedder contract: `{ id, dim, embed(texts: string[]) => number[][] | Promise<number[][]> }`. `id` names the model
|
|
806
|
+
* and settings, so an index built with one is never searched with another. The default is local and deterministic.
|
|
807
|
+
*/
|
|
808
|
+
export function hashedEmbedder({ dim = 512 } = {}) {
|
|
809
|
+
const d = Math.max(16, Math.min(LIMITS.maxDim, Math.floor(Number(dim)) || 512));
|
|
810
|
+
return { id: `hashed-bow-${d}`, dim: d, embed: (texts) => texts.map((t) => hashEmbed(t, d)) };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Opt-in on-device AI (Chrome's built-in Prompt API, through mallory's bridge and its consent prompt): the model lists
|
|
815
|
+
* keywords and close synonyms for each text, and the local hashed embedder reads the text plus those. Chrome exposes no
|
|
816
|
+
* embedding model, so this widens what a query can match; it is not a vector model. Nothing leaves the device. It
|
|
817
|
+
* needs `LanguageModel` (pane code has it; the first use asks the person) and refuses more than `limit` texts.
|
|
818
|
+
*/
|
|
819
|
+
export function onDeviceEmbedder({ languageModel, dim = 512, limit = 200 } = {}) {
|
|
820
|
+
const base = hashedEmbedder({ dim });
|
|
821
|
+
return {
|
|
822
|
+
id: `on-device-keywords+${base.id}`,
|
|
823
|
+
dim: base.dim,
|
|
824
|
+
async embed(texts) {
|
|
825
|
+
if (!languageModel || typeof languageModel.create !== "function") throw new Error("on-device AI is not available in this browser (no LanguageModel); use the local embedder");
|
|
826
|
+
if (texts.length > limit) throw new Error(`${texts.length} texts is over the on-device limit of ${limit}: use the local embedder or a smaller corpus`);
|
|
827
|
+
const out = [];
|
|
828
|
+
for (const t of texts) {
|
|
829
|
+
const session = await languageModel.create({ initialPrompts: [{ role: "system", content: "Reply with up to 12 comma-separated keywords and close synonyms for the user's text. Nothing else." }] });
|
|
830
|
+
try {
|
|
831
|
+
const words = String(await session.prompt(t.slice(0, 2000))).slice(0, 400);
|
|
832
|
+
out.push(hashEmbed(`${t}\n${words}`, base.dim));
|
|
833
|
+
} finally {
|
|
834
|
+
session.destroy?.();
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return out;
|
|
838
|
+
},
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
export function embedderFor(id, { languageModel } = {}) {
|
|
843
|
+
const m = /^hashed-bow-(\d+)$/.exec(id ?? "");
|
|
844
|
+
if (m) return hashedEmbedder({ dim: Number(m[1]) });
|
|
845
|
+
const o = /^on-device-keywords\+hashed-bow-(\d+)$/.exec(id ?? "");
|
|
846
|
+
if (o) return onDeviceEmbedder({ languageModel, dim: Number(o[1]) });
|
|
847
|
+
throw new Error(`unknown embedder "${id}": pass its adapter`);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* A real embedding model behind an HTTP endpoint with the OpenAI-style request (`POST { model, input: [texts] }` answered with
|
|
852
|
+
* `{ data: [{ index, embedding }] }`; `{ embeddings: [[...]] }` is read too, as Ollama and others send it). Pass the pane's
|
|
853
|
+
* own `fetch` as `http`, so this module makes no request of its own: the request then goes through the canvas's network rules (the host is asked about first) and `auth: "NAME"`
|
|
854
|
+
* adds a stored API key on the page, so this module never sees a secret and makes no request of its own. **The text of
|
|
855
|
+
* every chunk leaves this device**, to that host; `maxTexts` (default 2000) refuses a corpus that would send more.
|
|
856
|
+
* The embedder's id names the host, model and size, so an index made with it is searched with the same one.
|
|
857
|
+
*/
|
|
858
|
+
export function endpointEmbedder({ http: send, url, model, dim, auth, headers, dimensions, batch = 32, maxTexts = 2000 } = {}) {
|
|
859
|
+
if (typeof send !== "function") throw new Error("an endpoint embedder needs `http`: the pane's request function, so that the network rules apply");
|
|
860
|
+
let host;
|
|
861
|
+
try { const u = new URL(String(url)); if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("scheme"); host = u.host; } catch { throw new Error("an endpoint embedder needs an http(s) url"); }
|
|
862
|
+
if (!model || typeof model !== "string") throw new Error("an endpoint embedder needs the model name");
|
|
863
|
+
const d = Math.floor(Number(dim));
|
|
864
|
+
if (!(d >= 1 && d <= LIMITS.maxDim)) throw new Error(`dim must be a whole number from 1 to ${LIMITS.maxDim}: the vector size of ${model}${Number(dim) > LIMITS.maxDim ? " (ask the model for fewer dimensions with `dimensions`)" : ""}`);
|
|
865
|
+
const size = Math.max(1, Math.min(256, Math.floor(Number(batch)) || 32));
|
|
866
|
+
const cap = Math.max(1, Math.floor(Number(maxTexts)) || 2000);
|
|
867
|
+
const id = `endpoint:${host}/${model}:${d}`;
|
|
868
|
+
return {
|
|
869
|
+
id, dim: d,
|
|
870
|
+
async embed(texts) {
|
|
871
|
+
if (texts.length > cap) throw new Error(`${texts.length} texts is over the endpoint limit of ${cap} (each is sent to ${host}): raise maxTexts, or use the local embedder or a smaller corpus`);
|
|
872
|
+
const out = [];
|
|
873
|
+
for (let from = 0; from < texts.length; from += size) {
|
|
874
|
+
const input = texts.slice(from, from + size);
|
|
875
|
+
const res = await send(String(url), { method: "POST", headers: { "content-type": "application/json", ...(headers ?? {}) }, body: JSON.stringify({ model, input, ...(dimensions ? { dimensions: Number(dimensions) } : {}) }), ...(auth ? { auth: String(auth) } : {}) });
|
|
876
|
+
let body;
|
|
877
|
+
try { body = await res.json(); } catch { body = null; }
|
|
878
|
+
if (!res.ok) throw new Error(`${host} answered ${res.status}${body?.error?.message ? `: ${String(body.error.message).slice(0, 200)}` : ""}`);
|
|
879
|
+
const rows = Array.isArray(body?.data) ? [...body.data].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((r) => r?.embedding) : Array.isArray(body?.embeddings) ? body.embeddings : null;
|
|
880
|
+
if (!rows || rows.length !== input.length) throw new Error(`${host} returned ${rows ? rows.length : "no"} embeddings for ${input.length} texts`);
|
|
881
|
+
for (const v of rows) {
|
|
882
|
+
if (!Array.isArray(v) || v.length !== d) throw new Error(`${model} returned vectors of ${Array.isArray(v) ? v.length : "no"} numbers, not ${d}: set dim to its vector size`);
|
|
883
|
+
out.push(v);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
return out;
|
|
887
|
+
},
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// ---- the index ----
|
|
892
|
+
|
|
893
|
+
const sameChunkOptions = (a, b) => a?.size === b.size && a?.overlap === b.overlap;
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* Build or update an index. `sources` are the inputs (strings, { name, text | file }); `previous` is an earlier index
|
|
897
|
+
* (or null): a document whose content, type and settings are unchanged keeps its chunks and vectors, only the others
|
|
898
|
+
* are extracted, chunked and embedded again. `adapters` are `{ pdfjs, ocr }`, see `extractDocument`. Returns `{ index, report }`; `report` holds names, statuses and counts, no text.
|
|
899
|
+
*/
|
|
900
|
+
export async function buildIndex(sources, { size, overlap, embedder = hashedEmbedder(), previous = null, adapters = {} } = {}) {
|
|
901
|
+
const options = normalizeChunkOptions({ size, overlap });
|
|
902
|
+
const list = Array.isArray(sources) ? sources : sources == null ? [] : [sources];
|
|
903
|
+
const report = { reused: [], rebuilt: [], removed: [], skipped: [], truncated: false, warnings: [] };
|
|
904
|
+
if (list.length > LIMITS.maxDocs) { report.truncated = true; report.warnings.push(`only the first ${LIMITS.maxDocs} of ${list.length} documents are read`); }
|
|
905
|
+
const usable = previous && previous.format === FORMAT && previous.embedder?.id === embedder.id && sameChunkOptions(previous.options, options) ? previous : null;
|
|
906
|
+
const old = new Map((usable?.documents ?? []).map((d) => [d.name, d]));
|
|
907
|
+
const documents = [];
|
|
908
|
+
const chunks = [];
|
|
909
|
+
const seen = new Set();
|
|
910
|
+
for (let n = 0; n < Math.min(list.length, LIMITS.maxDocs); n++) {
|
|
911
|
+
const src = await readSource(list[n], n);
|
|
912
|
+
if (seen.has(src.name)) { report.skipped.push({ name: src.name, status: "unsupported", reason: "a second document with this name: names must be unique, they are the citations" }); continue; }
|
|
913
|
+
seen.add(src.name);
|
|
914
|
+
if (!src.problem) src.kind = decideKind(src);
|
|
915
|
+
// a document read with an adapter is a different read: switching one on or off rebuilds it
|
|
916
|
+
const tag = [adapters?.pdfjs ? "pdfjs" : "", adapters?.ocr ? "ocr" : ""].filter(Boolean).join("+");
|
|
917
|
+
const source = src.problem ? hashOf(src.name, src.problem.status) : tag ? hashOf(sourceHash(src), tag) : sourceHash(src);
|
|
918
|
+
const was = old.get(src.name);
|
|
919
|
+
if (was && was.source === source && was.status !== "unsupported") {
|
|
920
|
+
const own = usable.chunks.filter((c) => c.doc === src.name);
|
|
921
|
+
documents.push({ ...was });
|
|
922
|
+
chunks.push(...own);
|
|
923
|
+
report.reused.push(src.name);
|
|
924
|
+
if (was.status !== "ok") report.skipped.push({ name: src.name, status: was.status, reason: was.reason });
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
const doc = await extractDocument(src, adapters);
|
|
928
|
+
const entry = { name: doc.name, kind: doc.kind, status: doc.status, ...(doc.reason ? { reason: doc.reason } : {}), source, fingerprint: doc.fingerprint, chars: doc.text.length, ...(doc.pages ? { pages: doc.pages.length } : {}), chunks: 0 };
|
|
929
|
+
if (doc.status !== "ok" && doc.status !== "partial") {
|
|
930
|
+
documents.push(entry);
|
|
931
|
+
report.skipped.push({ name: doc.name, status: doc.status, reason: doc.reason });
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
let made = chunkDocument(doc, options);
|
|
935
|
+
if (chunks.length + made.length > LIMITS.maxChunks) { made = made.slice(0, Math.max(0, LIMITS.maxChunks - chunks.length)); report.truncated = true; report.warnings.push(`${doc.name}: stopped at the ${LIMITS.maxChunks} chunk limit`); }
|
|
936
|
+
const vectors = await embedder.embed(made.map((c) => c.text));
|
|
937
|
+
if (!Array.isArray(vectors) || vectors.length !== made.length || vectors.some((v) => !Array.isArray(v) || v.length !== embedder.dim || v.some((x) => !Number.isFinite(x)))) throw new Error(`embedder ${embedder.id} returned vectors that are not ${embedder.dim} finite numbers each, one per chunk`);
|
|
938
|
+
made.forEach((c, k) => chunks.push({ ...c, v: vectors[k].map(round) }));
|
|
939
|
+
entry.chunks = made.length;
|
|
940
|
+
documents.push(entry);
|
|
941
|
+
report.rebuilt.push(doc.name);
|
|
942
|
+
if (doc.status === "partial") report.skipped.push({ name: doc.name, status: "partial", reason: doc.reason });
|
|
943
|
+
for (const w of doc.warnings) report.warnings.push(`${doc.name}: ${w}`);
|
|
944
|
+
}
|
|
945
|
+
for (const name of old.keys()) if (!seen.has(name)) report.removed.push(name);
|
|
946
|
+
documents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
947
|
+
const index = { format: FORMAT, version: 1, embedder: { id: embedder.id, dim: embedder.dim }, options, documents, chunks };
|
|
948
|
+
index.fingerprint = corpusFingerprint(index);
|
|
949
|
+
report.fingerprint = index.fingerprint;
|
|
950
|
+
report.documents = documents.length;
|
|
951
|
+
report.chunks = chunks.length;
|
|
952
|
+
return { index, report };
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/** One fingerprint for the whole corpus: its documents' sources, the chunk settings and the embedder. */
|
|
956
|
+
export function corpusFingerprint(index) {
|
|
957
|
+
return hashOf(index.embedder.id, String(index.options.size), String(index.options.overlap), ...[...index.documents].sort((a, b) => (a.name < b.name ? -1 : 1)).flatMap((d) => [d.name, d.source, d.status]));
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** A readable citation for a chunk or result: `guide.pdf p.3-4 § Setup > Install [120-340]`. */
|
|
961
|
+
export function cite(c) {
|
|
962
|
+
const page = c.page === undefined ? "" : c.pageEnd !== undefined && c.pageEnd !== c.page ? ` p.${c.page}-${c.pageEnd}` : ` p.${c.page}`;
|
|
963
|
+
const path = c.headings?.length ? ` § ${c.headings.join(" > ")}` : "";
|
|
964
|
+
return `${c.doc}${page}${path} [${c.start}-${c.end}]`;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// ---- lexical scoring (BM25) and an approximate nearest-neighbour list index ----
|
|
968
|
+
|
|
969
|
+
const lexicons = new WeakMap(); // index -> its term statistics, made once per index (chunks never change after a build)
|
|
970
|
+
function lexiconOf(index) {
|
|
971
|
+
let lex = lexicons.get(index);
|
|
972
|
+
if (lex && lex.n === index.chunks.length) return lex;
|
|
973
|
+
const df = new Map();
|
|
974
|
+
const docs = index.chunks.map((c) => {
|
|
975
|
+
const tf = new Map();
|
|
976
|
+
for (const t of tokens(c.text)) tf.set(t, (tf.get(t) ?? 0) + 1);
|
|
977
|
+
for (const t of tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);
|
|
978
|
+
let len = 0;
|
|
979
|
+
for (const n of tf.values()) len += n;
|
|
980
|
+
return { tf, len };
|
|
981
|
+
});
|
|
982
|
+
lex = { n: index.chunks.length, docs, df, avg: docs.reduce((a, d) => a + d.len, 0) / (docs.length || 1) || 1 };
|
|
983
|
+
lexicons.set(index, lex);
|
|
984
|
+
return lex;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/** BM25 of every chunk for a query (`k1` 1.2, `b` 0.75): one number per chunk, 0 for no shared word. Words, not meaning: the same tokens as the local embedder. */
|
|
988
|
+
export function bm25Scores(index, query, { k1 = 1.2, b = 0.75 } = {}) {
|
|
989
|
+
const lex = lexiconOf(index);
|
|
990
|
+
const terms = [...new Set(tokens(String(query ?? "")))];
|
|
991
|
+
const idf = terms.map((t) => { const n = lex.df.get(t) ?? 0; return Math.log(1 + (lex.n - n + 0.5) / (n + 0.5)); });
|
|
992
|
+
return lex.docs.map((d) => {
|
|
993
|
+
let score = 0;
|
|
994
|
+
for (let i = 0; i < terms.length; i++) {
|
|
995
|
+
const f = d.tf.get(terms[i]);
|
|
996
|
+
if (f) score += idf[i] * ((f * (k1 + 1)) / (f + k1 * (1 - b + (b * d.len) / lex.avg)));
|
|
997
|
+
}
|
|
998
|
+
return score;
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const unit = (v) => { let n = 0; for (let i = 0; i < v.length; i++) n += v[i] * v[i]; n = Math.sqrt(n) || 1; return v.map((x) => x / n); };
|
|
1003
|
+
const dotOf = (a, b) => { let d = 0; for (let i = 0; i < a.length; i++) d += a[i] * b[i]; return d; };
|
|
1004
|
+
const annCache = new WeakMap(); // index -> Map("lists" -> lists)
|
|
1005
|
+
|
|
1006
|
+
/**
|
|
1007
|
+
* A coarse list index (inverted file) for big corpora: the chunks are grouped around `lists` centroids (spherical k-means,
|
|
1008
|
+
* started from evenly spaced chunks, six passes, so the same corpus always gives the same lists). A search then scores only
|
|
1009
|
+
* the chunks of the `nprobe` nearest lists. It is approximate: a chunk in a list that is not probed is missed; more
|
|
1010
|
+
* `nprobe` is slower and closer to exact. The default `lists` is about the square root of the chunk count (at most 256).
|
|
1011
|
+
*/
|
|
1012
|
+
export function buildAnn(index, { lists } = {}) {
|
|
1013
|
+
const n = index.chunks.length;
|
|
1014
|
+
const count = Math.max(1, Math.min(256, n, Math.floor(Number(lists)) || Math.round(Math.sqrt(n))));
|
|
1015
|
+
const cache = annCache.get(index) ?? new Map();
|
|
1016
|
+
annCache.set(index, cache);
|
|
1017
|
+
if (cache.has(count)) return cache.get(count);
|
|
1018
|
+
const vecs = index.chunks.map((c) => unit(c.v));
|
|
1019
|
+
let centroids = Array.from({ length: count }, (_, i) => vecs[Math.floor((i * n) / count)].slice());
|
|
1020
|
+
let members = [];
|
|
1021
|
+
for (let pass = 0; pass < 6; pass++) {
|
|
1022
|
+
members = Array.from({ length: count }, () => []);
|
|
1023
|
+
for (let i = 0; i < n; i++) {
|
|
1024
|
+
let best = 0, bs = -Infinity;
|
|
1025
|
+
for (let c = 0; c < count; c++) { const d = dotOf(vecs[i], centroids[c]); if (d > bs) { bs = d; best = c; } }
|
|
1026
|
+
members[best].push(i);
|
|
1027
|
+
}
|
|
1028
|
+
centroids = centroids.map((old, c) => {
|
|
1029
|
+
if (!members[c].length) return old;
|
|
1030
|
+
const sum = new Array(old.length).fill(0);
|
|
1031
|
+
for (const i of members[c]) for (let k = 0; k < sum.length; k++) sum[k] += vecs[i][k];
|
|
1032
|
+
return unit(sum);
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
const ann = { lists: count, centroids, members, vecs };
|
|
1036
|
+
cache.set(count, ann);
|
|
1037
|
+
return ann;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* The top `k` chunks for a query, best first: score descending, ties by document name then position, so the same index
|
|
1042
|
+
* and query always give the same list. `k` is clamped to 1..50. Each result carries its provenance.
|
|
1043
|
+
*
|
|
1044
|
+
* `mode` is `vector` (the default: cosine similarity of the embeddings), `bm25` (word statistics only: no embedder is
|
|
1045
|
+
* called, so nothing is sent anywhere) or `hybrid` (`alpha` of the cosine score plus `1 - alpha` of the BM25 score scaled
|
|
1046
|
+
* to the best match, `alpha` 0.5 by default). In the other two modes a result also has `scores: { vector, bm25 }`.
|
|
1047
|
+
* `ann: true | { lists, nprobe }` scores only the nearest lists of a list index instead of every chunk (approximate).
|
|
1048
|
+
*/
|
|
1049
|
+
export async function search(index, query, { k = 5, minScore = 0, embedder, mode = "vector", alpha = 0.5, ann = false } = {}) {
|
|
1050
|
+
if (!index || index.format !== FORMAT) throw new Error("search needs an index made by Build document index (or Import corpus)");
|
|
1051
|
+
if (!["vector", "bm25", "hybrid"].includes(mode)) throw new Error(`unknown search mode "${mode}": use vector, bm25 or hybrid`);
|
|
1052
|
+
const a = Math.max(0, Math.min(1, Number.isFinite(Number(alpha)) ? Number(alpha) : 0.5));
|
|
1053
|
+
const limit = Math.max(1, Math.min(LIMITS.maxK, Math.floor(Number(k)) || 5));
|
|
1054
|
+
const docs = new Map(index.documents.map((d) => [d.name, d]));
|
|
1055
|
+
const text = String(query ?? "");
|
|
1056
|
+
const n = index.chunks.length;
|
|
1057
|
+
const cos = new Float64Array(n);
|
|
1058
|
+
let cand = null; // null: every chunk
|
|
1059
|
+
let scoreOf = null;
|
|
1060
|
+
if (mode !== "bm25") {
|
|
1061
|
+
const emb = embedder ?? embedderFor(index.embedder.id);
|
|
1062
|
+
if (emb.id !== index.embedder.id || emb.dim !== index.embedder.dim) throw new Error(`the index was built with ${index.embedder.id}; the query embedder is ${emb.id}`);
|
|
1063
|
+
const q = (await emb.embed([text]))[0];
|
|
1064
|
+
const qn = Math.sqrt(q.reduce((s, x) => s + x * x, 0));
|
|
1065
|
+
if (qn > 0) {
|
|
1066
|
+
scoreOf = (i) => {
|
|
1067
|
+
const c = index.chunks[i];
|
|
1068
|
+
let dot = 0, cn = 0;
|
|
1069
|
+
for (let j = 0; j < q.length; j++) { dot += q[j] * c.v[j]; cn += c.v[j] * c.v[j]; }
|
|
1070
|
+
cos[i] = cn > 0 ? Math.max(0, dot / (qn * Math.sqrt(cn))) : 0;
|
|
1071
|
+
};
|
|
1072
|
+
if (ann && n > 0) {
|
|
1073
|
+
const o = typeof ann === "object" ? ann : {};
|
|
1074
|
+
const list = buildAnn(index, { lists: o.lists });
|
|
1075
|
+
const probe = Math.max(1, Math.min(list.lists, Math.floor(Number(o.nprobe)) || Math.ceil(list.lists / 4)));
|
|
1076
|
+
const qu = unit(q);
|
|
1077
|
+
const near = list.centroids.map((c, i) => [dotOf(qu, c), i]).sort((x, y) => y[0] - x[0] || x[1] - y[1]).slice(0, probe);
|
|
1078
|
+
cand = new Set(near.flatMap(([, i]) => list.members[i]));
|
|
1079
|
+
for (const i of cand) scoreOf(i);
|
|
1080
|
+
} else for (let i = 0; i < n; i++) scoreOf(i);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
let lexical = null;
|
|
1084
|
+
if (mode !== "vector") {
|
|
1085
|
+
lexical = bm25Scores(index, text);
|
|
1086
|
+
// a word match is always scored by cosine too, even outside the lists that were probed
|
|
1087
|
+
if (cand && scoreOf) for (let i = 0; i < n; i++) if (lexical[i] > 0 && !cand.has(i)) { cand.add(i); scoreOf(i); }
|
|
1088
|
+
}
|
|
1089
|
+
let top = 0;
|
|
1090
|
+
if (lexical) for (const x of lexical) if (x > top) top = x;
|
|
1091
|
+
const scored = [];
|
|
1092
|
+
for (let i = 0; i < n; i++) {
|
|
1093
|
+
if (cand && !cand.has(i)) continue;
|
|
1094
|
+
const l = lexical && top > 0 ? lexical[i] / top : 0;
|
|
1095
|
+
const score = mode === "vector" ? cos[i] : mode === "bm25" ? l : a * cos[i] + (1 - a) * l;
|
|
1096
|
+
if (score > 0 && score >= minScore) scored.push({ c: index.chunks[i], score, parts: { vector: cos[i], bm25: lexical ? lexical[i] : 0 } });
|
|
1097
|
+
}
|
|
1098
|
+
scored.sort((x, y) => y.score - x.score || (x.c.doc < y.c.doc ? -1 : x.c.doc > y.c.doc ? 1 : 0) || x.c.start - y.c.start);
|
|
1099
|
+
return scored.slice(0, limit).map(({ c, score, parts }, i) => {
|
|
1100
|
+
const prov = { doc: c.doc, start: c.start, end: c.end, headings: c.headings, ...(c.page !== undefined ? { page: c.page, pageEnd: c.pageEnd } : {}), fingerprint: docs.get(c.doc)?.fingerprint };
|
|
1101
|
+
return { rank: i + 1, score: Math.round(score * 1e4) / 1e4, id: c.id, text: c.text, provenance: prov, citation: cite(c), ...(mode === "vector" ? {} : { scores: { vector: Math.round(parts.vector * 1e4) / 1e4, bm25: Math.round(parts.bm25 * 1e4) / 1e4 } }) };
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/** Results as one text block an agent can read, each passage marked [n] with its citation. */
|
|
1106
|
+
export function contextOf(results) {
|
|
1107
|
+
return results.map((r) => `[${r.rank}] ${r.citation}\n${r.text}`).join("\n\n");
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// ---- the portable corpus file ----
|
|
1111
|
+
|
|
1112
|
+
const b64 = (bytes) => { let s = ""; for (let i = 0; i < bytes.length; i += 8192) s += String.fromCharCode(...bytes.subarray(i, i + 8192)); return btoa(s); };
|
|
1113
|
+
const unb64 = (text) => { const s = atob(text); const out = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i); return out; };
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* A vector as 8-bit integers: `{ s, q, i? }`. `s` is the largest magnitude, `q` the base64 of one signed byte per number
|
|
1117
|
+
* (x / s * 127), and, when under a third of the numbers are not zero (the local embedder's vectors mostly are), `i` lists
|
|
1118
|
+
* the positions of the non-zero ones and `q` holds only those. About a quarter of the size, within 1% of the original.
|
|
1119
|
+
*/
|
|
1120
|
+
export function quantizeVector(v) {
|
|
1121
|
+
let s = 0;
|
|
1122
|
+
for (const x of v) s = Math.max(s, Math.abs(x));
|
|
1123
|
+
s = Math.round(s * 1e6) / 1e6; // so that packing what was unpacked gives the same pack again
|
|
1124
|
+
const byte = (x) => (s ? Math.max(-127, Math.min(127, Math.round((x / s) * 127))) : 0);
|
|
1125
|
+
const nz = [];
|
|
1126
|
+
v.forEach((x, k) => { if (byte(x) !== 0) nz.push(k); });
|
|
1127
|
+
const sparse = nz.length * 3 < v.length;
|
|
1128
|
+
const q = new Int8Array(sparse ? nz.length : v.length);
|
|
1129
|
+
if (sparse) nz.forEach((k, j) => { q[j] = byte(v[k]); }); else v.forEach((x, k) => { q[k] = byte(x); });
|
|
1130
|
+
return { s, q: b64(new Uint8Array(q.buffer)), ...(sparse ? { i: nz } : {}) };
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/** The numbers back from `quantizeVector`'s `{ s, q, i? }` (checked: a wrong length, an index out of order or a bad scale throws). */
|
|
1134
|
+
export function dequantizeVector(packed, dim, what = "vector") {
|
|
1135
|
+
const { s, q, i } = packed ?? {};
|
|
1136
|
+
if (typeof s !== "number" || !Number.isFinite(s) || s < 0 || typeof q !== "string") throw new Error(`${what}: not a packed vector (s and q)`);
|
|
1137
|
+
let bytes;
|
|
1138
|
+
try { bytes = unb64(q); } catch { throw new Error(`${what}: q is not base64`); }
|
|
1139
|
+
const out = new Array(dim).fill(0);
|
|
1140
|
+
const put = (k, byte) => { const x = byte > 127 ? byte - 256 : byte; out[k] = Math.round((x / 127) * s * 1e6) / 1e6; };
|
|
1141
|
+
if (i === undefined) {
|
|
1142
|
+
if (bytes.length !== dim) throw new Error(`${what}: ${bytes.length} packed numbers, not ${dim}`);
|
|
1143
|
+
for (let k = 0; k < dim; k++) put(k, bytes[k]);
|
|
1144
|
+
} else {
|
|
1145
|
+
if (!Array.isArray(i) || i.length !== bytes.length) throw new Error(`${what}: the positions and the packed numbers differ in count`);
|
|
1146
|
+
let last = -1;
|
|
1147
|
+
i.forEach((k, j) => {
|
|
1148
|
+
if (!Number.isInteger(k) || k <= last || k >= dim) throw new Error(`${what}: the positions must increase and stay under ${dim}`);
|
|
1149
|
+
last = k;
|
|
1150
|
+
put(k, bytes[j]);
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
return out;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
const SECRET_KEY = /(api[-_]?key|secret|token|passw|authorization|credential|bearer)/i;
|
|
1157
|
+
function scanKeys(value, path, depth = 0) {
|
|
1158
|
+
if (!value || typeof value !== "object" || depth > 8) return null;
|
|
1159
|
+
for (const [k, v] of Array.isArray(value) ? [] : Object.entries(value)) {
|
|
1160
|
+
if (SECRET_KEY.test(k)) return `${path}.${k}`;
|
|
1161
|
+
const hit = scanKeys(v, `${path}.${k}`, depth + 1);
|
|
1162
|
+
if (hit) return hit;
|
|
1163
|
+
}
|
|
1164
|
+
if (Array.isArray(value)) for (let i = 0; i < Math.min(value.length, 50); i++) { const hit = scanKeys(value[i], `${path}[${i}]`, depth + 1); if (hit) return hit; }
|
|
1165
|
+
return null;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/**
|
|
1169
|
+
* The corpus as portable JSON text: documents (name, kind, status, fingerprints, sizes) and chunks (text, spans, headings,
|
|
1170
|
+
* vectors). Only these fields are written, by name: no provider configuration, keys, permissions or storage state.
|
|
1171
|
+
* `compact` writes the vectors as 8-bit integers (version 2, see `quantizeVector`): roughly a third of the size, scores within about 1%.
|
|
1172
|
+
* A plain file (version 1) stays readable by older versions of mallory.
|
|
1173
|
+
*/
|
|
1174
|
+
export function exportCorpus(index, { compact = false } = {}) {
|
|
1175
|
+
if (!index || index.format !== FORMAT) throw new Error("nothing to export: wire a document index");
|
|
1176
|
+
const out = {
|
|
1177
|
+
format: FORMAT, version: compact ? 2 : 1, fingerprint: index.fingerprint, embedder: { id: index.embedder.id, dim: index.embedder.dim }, options: { size: index.options.size, overlap: index.options.overlap },
|
|
1178
|
+
documents: index.documents.map((d) => ({ name: d.name, kind: d.kind, status: d.status, ...(d.reason ? { reason: d.reason } : {}), source: d.source, fingerprint: d.fingerprint, chars: d.chars, ...(d.pages ? { pages: d.pages } : {}), chunks: d.chunks })),
|
|
1179
|
+
chunks: index.chunks.map((c) => ({ id: c.id, doc: c.doc, index: c.index, start: c.start, end: c.end, text: c.text, headings: c.headings, ...(c.page !== undefined ? { page: c.page, pageEnd: c.pageEnd } : {}), ...(compact ? quantizeVector(c.v) : { v: c.v }) })),
|
|
1180
|
+
};
|
|
1181
|
+
return JSON.stringify(out);
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/** Read a corpus file (text or object) back into an index, checking everything; throws a precise message when it is not one. */
|
|
1185
|
+
export function importCorpus(input) {
|
|
1186
|
+
if (typeof input === "string" && input.length > LIMITS.maxImportChars) throw new Error("the corpus file is too large");
|
|
1187
|
+
let raw = input;
|
|
1188
|
+
if (typeof input === "string") { try { raw = JSON.parse(input); } catch { throw new Error("not a corpus file: invalid JSON"); } }
|
|
1189
|
+
if (!raw || (raw.format !== FORMAT && raw.format !== "viaframe-doc-index")) throw new Error(`not a corpus file: format is not ${FORMAT}`);
|
|
1190
|
+
if (raw.version !== 1 && raw.version !== 2) throw new Error(`corpus version ${raw.version} is not supported (this reads 1 and 2)`);
|
|
1191
|
+
const secret = scanKeys(raw, "corpus");
|
|
1192
|
+
if (secret) throw new Error(`refused: ${secret} looks like a credential; a corpus file never carries provider secrets`);
|
|
1193
|
+
const dim = raw.embedder?.dim;
|
|
1194
|
+
if (typeof raw.embedder?.id !== "string" || !Number.isInteger(dim) || dim < 1 || dim > LIMITS.maxDim) throw new Error("the corpus names no valid embedder (id and dim)");
|
|
1195
|
+
const options = normalizeChunkOptions(raw.options ?? {});
|
|
1196
|
+
if (!Array.isArray(raw.documents) || !Array.isArray(raw.chunks)) throw new Error("the corpus has no documents or chunks list");
|
|
1197
|
+
if (raw.chunks.length > LIMITS.maxChunks || raw.documents.length > LIMITS.maxDocs) throw new Error("the corpus is over the document or chunk limit");
|
|
1198
|
+
const str = (x, what) => { if (typeof x !== "string") throw new Error(`${what} must be text`); return x; };
|
|
1199
|
+
const int = (x, what) => { if (!Number.isInteger(x) || x < 0) throw new Error(`${what} must be a whole number`); return x; };
|
|
1200
|
+
const documents = raw.documents.map((d, i) => ({
|
|
1201
|
+
name: str(d?.name, `documents[${i}].name`), kind: str(d.kind, `documents[${i}].kind`), status: str(d.status, `documents[${i}].status`), ...(d.reason ? { reason: str(d.reason, "reason") } : {}),
|
|
1202
|
+
source: str(d.source, `documents[${i}].source`), fingerprint: str(d.fingerprint, `documents[${i}].fingerprint`), chars: int(d.chars, "chars"), ...(d.pages !== undefined ? { pages: int(d.pages, "pages") } : {}), chunks: int(d.chunks, "chunks"),
|
|
1203
|
+
}));
|
|
1204
|
+
const names = new Set(documents.map((d) => d.name));
|
|
1205
|
+
if (names.size !== documents.length) throw new Error("two documents share a name");
|
|
1206
|
+
const ids = new Set();
|
|
1207
|
+
const chunks = raw.chunks.map((c, i) => {
|
|
1208
|
+
const id = str(c?.id, `chunks[${i}].id`);
|
|
1209
|
+
if (ids.has(id)) throw new Error(`chunk id ${id} appears twice`);
|
|
1210
|
+
ids.add(id);
|
|
1211
|
+
const doc = str(c.doc, `chunks[${i}].doc`);
|
|
1212
|
+
if (!names.has(doc)) throw new Error(`chunk ${id} cites a document that is not in the corpus: ${doc}`);
|
|
1213
|
+
const start = int(c.start, "start"), end = int(c.end, "end");
|
|
1214
|
+
if (end <= start) throw new Error(`chunk ${id} has an empty span`);
|
|
1215
|
+
const v = raw.version === 2 ? dequantizeVector(c, dim, `chunk ${id}`) : c.v;
|
|
1216
|
+
if (!Array.isArray(v) || v.length !== dim || v.some((x) => typeof x !== "number" || !Number.isFinite(x))) throw new Error(`chunk ${id}: its vector is not ${dim} finite numbers`);
|
|
1217
|
+
if (!Array.isArray(c.headings) || c.headings.some((h) => typeof h !== "string")) throw new Error(`chunk ${id}: headings must be a list of text`);
|
|
1218
|
+
return { id, doc, index: int(c.index, "index"), start, end, text: str(c.text, `chunks[${i}].text`), headings: c.headings, ...(c.page !== undefined ? { page: int(c.page, "page"), pageEnd: int(c.pageEnd ?? c.page, "pageEnd") } : {}), v };
|
|
1219
|
+
});
|
|
1220
|
+
const index = { format: FORMAT, version: 1, embedder: { id: raw.embedder.id, dim }, options, documents, chunks };
|
|
1221
|
+
index.fingerprint = corpusFingerprint(index);
|
|
1222
|
+
if (raw.fingerprint !== index.fingerprint) throw new Error("the corpus fingerprint does not match its documents: the file was changed or is damaged");
|
|
1223
|
+
return index;
|
|
1224
|
+
}
|