aws-runtime-bridge 1.9.175 → 1.9.179
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +188 -0
- package/README.md +61 -2
- package/dist/adapter/AcodeSdkAdapter.d.ts +369 -0
- package/dist/adapter/AcodeSdkAdapter.js +2 -2
- package/dist/adapter/AdapterRegistry.d.ts +28 -0
- package/dist/adapter/ClaudeSdkAdapter.d.ts +71 -0
- package/dist/adapter/CodexSdkAdapter.d.ts +14 -0
- package/dist/adapter/OpencodeSdkAdapter.d.ts +44 -0
- package/dist/adapter/acode-tool-names.d.ts +9 -0
- package/dist/adapter/idle-poll-loop.d.ts +20 -0
- package/dist/adapter/index.d.ts +3 -0
- package/dist/adapter/instance-ai-config-resolver.d.ts +20 -0
- package/dist/adapter/prompts.d.ts +12 -0
- package/dist/adapter/types.d.ts +182 -0
- package/dist/browser/browser-bootstrap.d.ts +15 -0
- package/dist/browser/browser-connect-token.d.ts +11 -0
- package/dist/browser/browser-frame-encode.d.ts +32 -0
- package/dist/browser/browser-pool.d.ts +129 -0
- package/dist/browser/browser-profile-store.d.ts +41 -0
- package/dist/browser/browser-ws-bridge.d.ts +20 -0
- package/dist/browser/built-in-browser-tools.d.ts +44 -0
- package/dist/browser/element-locator.d.ts +25 -0
- package/dist/browser/element-picker.d.ts +30 -0
- package/dist/browser/frame-encode.d.ts +19 -0
- package/dist/browser/input-dispatcher.d.ts +35 -0
- package/dist/browser/listener-store.d.ts +44 -0
- package/dist/browser/page-listener-manager.d.ts +88 -0
- package/dist/browser/page-listener-types.d.ts +38 -0
- package/dist/browser/screencast-differ.d.ts +10 -0
- package/dist/browser/screencast-manager.d.ts +94 -0
- package/dist/browser/snapshot-serializer.d.ts +56 -0
- package/dist/browser/ssrf-guard.d.ts +44 -0
- package/dist/browser/stealth.d.ts +21 -0
- package/dist/browser/step-archive.d.ts +13 -0
- package/dist/browser/types.d.ts +100 -0
- package/dist/browser/ws-server.d.ts +54 -0
- package/dist/config.d.ts +138 -2
- package/dist/config.js +2 -2
- package/dist/desktop/built-in-desktop-tools.d.ts +68 -0
- package/dist/desktop/built-in-desktop-tools.js +2 -1
- package/dist/desktop/desktop-control.d.ts +142 -0
- package/dist/desktop/desktop-control.js +2 -0
- package/dist/desktop/desktop-mcp-client.d.ts +28 -0
- package/dist/desktop/desktop-staleness.d.ts +66 -0
- package/dist/desktop/desktop-staleness.js +2 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -1
- package/dist/middleware/auth.d.ts +26 -0
- package/dist/middleware/auth.js +1 -1
- package/dist/remote-desktop/computer-control.d.ts +3 -0
- package/dist/remote-desktop/coords.d.ts +6 -0
- package/dist/remote-desktop/frame-backpressure.d.ts +10 -0
- package/dist/remote-desktop/frame-encode.d.ts +3 -0
- package/dist/remote-desktop/index.js +2 -2
- package/dist/remote-desktop/input-dispatcher.d.ts +4 -0
- package/dist/remote-desktop/permission-manager.d.ts +3 -0
- package/dist/remote-desktop/screen-capture.d.ts +91 -0
- package/dist/remote-desktop/session-manager.d.ts +47 -0
- package/dist/remote-desktop/session-manager.js +1 -1
- package/dist/remote-desktop/system-backend.d.ts +64 -0
- package/dist/remote-desktop/types.d.ts +25 -0
- package/dist/remote-desktop/ui-automation.d.ts +11 -0
- package/dist/remote-desktop/win32-api.d.ts +10 -0
- package/dist/routes/acode-todos.d.ts +13 -0
- package/dist/routes/agent-state.d.ts +15 -0
- package/dist/routes/ai-sources.js +1 -1
- package/dist/routes/background-tasks.d.ts +18 -0
- package/dist/routes/background-tasks.js +2 -2
- package/dist/routes/browser-listeners.d.ts +17 -0
- package/dist/routes/browser-sessions.d.ts +10 -0
- package/dist/routes/capabilities.js +1 -1
- package/dist/routes/dashboard-icon.d.ts +9 -0
- package/dist/routes/dashboard-icon.js +2 -0
- package/dist/routes/dashboard-theme.d.ts +24 -0
- package/dist/routes/dashboard-theme.js +157 -0
- package/dist/routes/dashboard.d.ts +9 -0
- package/dist/routes/dashboard.js +1988 -625
- package/dist/routes/debug-mount.d.ts +16 -0
- package/dist/routes/desktop-control.d.ts +15 -0
- package/dist/routes/desktop-control.js +2 -0
- package/dist/routes/events.d.ts +4 -0
- package/dist/routes/file-browser.d.ts +11 -0
- package/dist/routes/file-change-diff.d.ts +25 -0
- package/dist/routes/file-diff-rollback.d.ts +28 -0
- package/dist/routes/file-snapshot.d.ts +7 -0
- package/dist/routes/git.d.ts +143 -0
- package/dist/routes/instance-tool-status.d.ts +5 -0
- package/dist/routes/instance.d.ts +8 -0
- package/dist/routes/instance.js +1 -1
- package/dist/routes/jdks.d.ts +4 -0
- package/dist/routes/launch.d.ts +5 -0
- package/dist/routes/lsp-providers.d.ts +11 -0
- package/dist/routes/lsp-providers.js +2 -0
- package/dist/routes/lsp.d.ts +41 -0
- package/dist/routes/lsp.js +4 -2
- package/dist/routes/mcp-extra.d.ts +15 -0
- package/dist/routes/mcp.d.ts +16 -0
- package/dist/routes/mcp.js +1 -1
- package/dist/routes/plugins.d.ts +19 -0
- package/dist/routes/plugins.js +1 -1
- package/dist/routes/processes.d.ts +4 -0
- package/dist/routes/properties.d.ts +4 -0
- package/dist/routes/pty.d.ts +29 -0
- package/dist/routes/runtime-binding.d.ts +3 -0
- package/dist/routes/sessions.d.ts +22 -0
- package/dist/routes/skills.d.ts +15 -0
- package/dist/routes/skills.js +1 -1
- package/dist/routes/sub-agents.d.ts +11 -0
- package/dist/routes/sub-agents.js +1 -1
- package/dist/routes/task-context.d.ts +5 -0
- package/dist/routes/tech-stack.d.ts +4 -0
- package/dist/routes/terminal.d.ts +122 -0
- package/dist/routes/terminal.js +16 -16
- package/dist/routes/workspace-index.d.ts +12 -0
- package/dist/routes/workspace-index.js +2 -0
- package/dist/routes/yml.d.ts +4 -0
- package/dist/scripts/migrate-user-scopes.d.ts +26 -0
- package/dist/scripts/migrate-user-scopes.js +2 -0
- package/dist/services/access-control.d.ts +21 -0
- package/dist/services/acode-bg-manager.d.ts +21 -0
- package/dist/services/acode-package.d.ts +10 -0
- package/dist/services/acode-package.js +1 -1
- package/dist/services/agent-capability-sync.d.ts +26 -0
- package/dist/services/agent-capability-sync.js +1 -1
- package/dist/services/agent-event-store.d.ts +20 -0
- package/dist/services/agent-ownership.d.ts +58 -0
- package/dist/services/agent-ownership.js +3 -0
- package/dist/services/agent-process-manager.d.ts +154 -0
- package/dist/services/agent-pty-manager.d.ts +37 -0
- package/dist/services/agent-startup-memory.d.ts +34 -0
- package/dist/services/agent-startup-memory.js +1 -1
- package/dist/services/ai-config-service.d.ts +26 -52
- package/dist/services/ai-config-service.js +1 -3
- package/dist/services/ai-source-apply.d.ts +7 -15
- package/dist/services/ai-source-apply.js +1 -1
- package/dist/services/auto-register.d.ts +165 -1
- package/dist/services/auto-register.js +1 -1
- package/dist/services/aws-client-agent-mcp.d.ts +14 -0
- package/dist/services/aws-client-agent-mcp.js +2 -2
- package/dist/services/bridge-package-publish-hooks.d.ts +14 -0
- package/dist/services/bridge-pairing.d.ts +82 -0
- package/dist/services/bridge-pairing.js +2 -0
- package/dist/services/bridge-temp-files.d.ts +29 -0
- package/dist/services/browser-session-manager.d.ts +71 -0
- package/dist/services/capability-config.d.ts +60 -15
- package/dist/services/capability-config.js +2 -2
- package/dist/services/change-cache-retention.d.ts +9 -0
- package/dist/services/changelog.d.ts +9 -0
- package/dist/services/cli-commands.d.ts +82 -0
- package/dist/services/cli-commands.js +6 -6
- package/dist/services/connection-key-rotation.d.ts +27 -0
- package/dist/services/connection-key-rotation.js +2 -0
- package/dist/services/debug-mount.d.ts +49 -0
- package/dist/services/desktop-mcp-manager.d.ts +103 -1
- package/dist/services/desktop-mcp-manager.js +1 -1
- package/dist/services/event-delta-pusher.d.ts +15 -0
- package/dist/services/fileSnapshotStore.d.ts +33 -0
- package/dist/services/gitignore.d.ts +9 -0
- package/dist/services/instance-ai-config-service.d.ts +9 -0
- package/dist/services/instance-ai-config-service.js +1 -1
- package/dist/services/instance-features.d.ts +127 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/instance-init-service.d.ts +3 -0
- package/dist/services/instance-init-service.js +1 -1
- package/dist/services/instance-state.d.ts +23 -0
- package/dist/services/jdk-scanner.d.ts +15 -0
- package/dist/services/launch-manager.d.ts +138 -0
- package/dist/services/launch-metrics.d.ts +42 -0
- package/dist/services/launch-streams.d.ts +19 -0
- package/dist/services/lifecycle-state.d.ts +5 -0
- package/dist/services/log-retention.d.ts +38 -0
- package/dist/services/lsp/install-manager.d.ts +55 -0
- package/dist/services/lsp/install-manager.js +2 -0
- package/dist/services/lsp/provider-registry.d.ts +108 -0
- package/dist/services/lsp/provider-registry.js +2 -0
- package/dist/services/lsp/uri-rewrite.d.ts +44 -0
- package/dist/services/lsp/uri-rewrite.js +2 -0
- package/dist/services/lsp-stdio-bridge.d.ts +41 -4
- package/dist/services/lsp-stdio-bridge.js +3 -3
- package/dist/services/mcp-deploy.d.ts +45 -4
- package/dist/services/mcp-deploy.js +4 -4
- package/dist/services/mcp-env-injector.d.ts +52 -0
- package/dist/services/mcp-launch-binding-queue.d.ts +12 -0
- package/dist/services/mcp-package.d.ts +22 -0
- package/dist/services/mcp-package.js +1 -1
- package/dist/services/mcp-probe-client.d.ts +19 -0
- package/dist/services/mcp-probe-client.js +1 -1
- package/dist/services/open-doc-events.d.ts +22 -0
- package/dist/services/open-doc-registry.d.ts +35 -0
- package/dist/services/orphan-monitor.d.ts +43 -0
- package/dist/services/panel-auth.d.ts +24 -0
- package/dist/services/panel-env.d.ts +28 -0
- package/dist/services/plugin-deployment.d.ts +34 -1
- package/dist/services/plugin-deployment.js +2 -2
- package/dist/services/plugin-event-buffer.d.ts +21 -0
- package/dist/services/plugin-fs.d.ts +11 -0
- package/dist/services/plugin-handler-adapter.d.ts +13 -0
- package/dist/services/plugin-listener-runner.d.ts +10 -0
- package/dist/services/plugin-loader.d.ts +15 -0
- package/dist/services/plugin-manager.d.ts +95 -9
- package/dist/services/plugin-manager.js +4 -4
- package/dist/services/plugin-manifest.d.ts +14 -0
- package/dist/services/plugin-package.d.ts +13 -0
- package/dist/services/plugin-runtime.d.ts +15 -0
- package/dist/services/port-detector.d.ts +15 -0
- package/dist/services/process-detail.d.ts +3 -0
- package/dist/services/process-detector.d.ts +132 -0
- package/dist/services/process-registry.d.ts +120 -0
- package/dist/services/process-top.d.ts +6 -0
- package/dist/services/request-identity.d.ts +77 -0
- package/dist/services/request-identity.js +2 -0
- package/dist/services/request-invalid-dump.d.ts +4 -0
- package/dist/services/ring-buffer.d.ts +33 -0
- package/dist/services/runtime-binding.d.ts +56 -4
- package/dist/services/runtime-binding.js +4 -4
- package/dist/services/runtime-lifecycle-policy.d.ts +17 -0
- package/dist/services/runtime-resources-snapshot.d.ts +26 -0
- package/dist/services/sdk-tool-file-change-recorder.d.ts +9 -0
- package/dist/services/session-output.d.ts +63 -0
- package/dist/services/session-output.js +3 -3
- package/dist/services/skill-manager.d.ts +42 -5
- package/dist/services/skill-manager.js +3 -3
- package/dist/services/snapshot-retention.d.ts +23 -0
- package/dist/services/startup-config-wizard.d.ts +7 -1
- package/dist/services/startup-config-wizard.js +10 -10
- package/dist/services/system-metrics.d.ts +3 -0
- package/dist/services/tech-stack-scanner.d.ts +12 -0
- package/dist/services/terminal-persistence.d.ts +43 -0
- package/dist/services/tool-installer.d.ts +12 -0
- package/dist/services/tunnel-client.d.ts +57 -2
- package/dist/services/tunnel-client.js +1 -1
- package/dist/services/update-log.d.ts +6 -0
- package/dist/services/update-notifier.d.ts +17 -0
- package/dist/services/update-notifier.js +2 -2
- package/dist/services/user-scope.d.ts +115 -0
- package/dist/services/user-scope.js +2 -0
- package/dist/services/windows-service-manager.d.ts +12 -0
- package/dist/services/workspace-files.d.ts +64 -0
- package/dist/services/workspace-index/index-manager.d.ts +46 -0
- package/dist/services/workspace-index/index-manager.js +2 -0
- package/dist/services/workspace-index/indexer.d.ts +15 -0
- package/dist/services/workspace-index/indexer.js +2 -0
- package/dist/services/workspace-index/query.d.ts +74 -0
- package/dist/services/workspace-index/query.js +5 -0
- package/dist/services/workspace-index/resolver.d.ts +26 -0
- package/dist/services/workspace-index/resolver.js +2 -0
- package/dist/services/workspace-index/types.d.ts +89 -0
- package/dist/services/workspace-index/types.js +2 -0
- package/dist/services/workspace-watch.d.ts +4 -0
- package/dist/services/workspaceTaskChangeWatcher.d.ts +49 -0
- package/dist/services/workspaceTaskChangeWatcher.js +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/utils/config-write-queue.d.ts +11 -0
- package/dist/utils/env-safety.d.ts +21 -0
- package/dist/utils/file-utils.d.ts +15 -0
- package/dist/utils/instance-ai-config-debug-logger.d.ts +15 -0
- package/dist/utils/lifecycle-log.d.ts +5 -0
- package/dist/utils/logger.d.ts +13 -0
- package/dist/utils/logger.js +2 -1
- package/dist/utils/npm-version.d.ts +10 -0
- package/dist/utils/path-utils.d.ts +12 -0
- package/dist/utils/scheduler-url.d.ts +18 -0
- package/dist/utils/scheduler-url.js +2 -0
- package/dist/utils/sdk-package-loader.d.ts +13 -0
- package/dist/utils/sdk-package-loader.js +1 -1
- package/dist/utils/target-identity.d.ts +31 -0
- package/dist/utils/target-identity.js +2 -0
- package/dist/utils/validation.d.ts +17 -0
- package/dist/utils/yaml-utils.d.ts +48 -0
- package/package/acode/dist/__tests__/summary-request-helper.d.ts +10 -0
- package/package/acode/dist/ask-user-question-tool.d.ts +17 -0
- package/package/acode/dist/await-complete-tool.d.ts +12 -0
- package/package/acode/dist/background-command-manager.d.ts +105 -0
- package/package/acode/dist/background-command-store.d.ts +27 -0
- package/package/acode/dist/background-command-tools.d.ts +8 -0
- package/package/acode/dist/background-output-ringbuffer.d.ts +15 -0
- package/package/acode/dist/built-in-file-tools.d.ts +65 -0
- package/package/acode/dist/built-in-symbols-tool.d.ts +3 -0
- package/package/acode/dist/builtins/commandArtifacts.d.ts +3 -0
- package/package/acode/dist/builtins/shellCommandPreparation.d.ts +17 -0
- package/package/acode/dist/builtins/shellCommandRunner.d.ts +4 -0
- package/package/acode/dist/builtins/shellOutputDecoder.d.ts +15 -0
- package/package/acode/dist/cache-control.d.ts +45 -0
- package/package/acode/dist/commands/commandLoader.d.ts +3 -0
- package/package/acode/dist/commands/commandParser.d.ts +3 -0
- package/package/acode/dist/commands/commandRegistry.d.ts +3 -0
- package/package/acode/dist/compaction.d.ts +354 -0
- package/package/acode/dist/config.d.ts +3 -0
- package/package/acode/dist/context-overflow.d.ts +32 -0
- package/package/acode/dist/fs-utils.d.ts +18 -0
- package/package/acode/dist/hooks/hookBus.d.ts +3 -0
- package/package/acode/dist/image-utils.d.ts +35 -0
- package/package/acode/dist/index.d.ts +1 -0
- package/package/acode/dist/index.js +1 -1
- package/package/acode/dist/mcpToolNames.d.ts +32 -0
- package/package/acode/dist/microcompact.d.ts +53 -0
- package/package/acode/dist/parsers/ast-cache.d.ts +41 -0
- package/package/acode/dist/parsers/file-index.d.ts +83 -0
- package/package/acode/dist/parsers/file-index.js +4 -0
- package/package/acode/dist/parsers/language-detector.d.ts +4 -0
- package/package/acode/dist/parsers/tree-sitter-loader.d.ts +12 -0
- package/package/acode/dist/parsers/types.d.ts +11 -0
- package/package/acode/dist/paths.d.ts +14 -0
- package/package/acode/dist/plugin-types.d.ts +34 -0
- package/package/acode/dist/read-file-state.d.ts +15 -0
- package/package/acode/dist/runtime-environment.d.ts +16 -0
- package/package/acode/dist/runtime.d.ts +824 -9
- package/package/acode/dist/runtime.js +21 -21
- package/package/acode/dist/skill-tool.d.ts +20 -0
- package/package/acode/dist/sub-agent-manager.d.ts +169 -0
- package/package/acode/dist/sub-agent-manager.js +1 -1
- package/package/acode/dist/sub-agent-store.d.ts +50 -0
- package/package/acode/dist/sub-agent-tools.d.ts +15 -0
- package/package/acode/dist/sub-agent-types.d.ts +13 -0
- package/package/acode/dist/terminal-tool.d.ts +15 -0
- package/package/acode/dist/terminal-types.d.ts +10 -0
- package/package/acode/dist/todo-store.d.ts +15 -0
- package/package/acode/dist/token-estimator.d.ts +17 -0
- package/package/acode/dist/tool-allocation.d.ts +113 -0
- package/package/acode/dist/tool-concurrency/index.d.ts +8 -0
- package/package/acode/dist/tool-concurrency/observability.d.ts +32 -0
- package/package/acode/dist/tool-concurrency/resource-lock.d.ts +30 -0
- package/package/acode/dist/tool-concurrency/scheduler.d.ts +19 -0
- package/package/acode/dist/tool-concurrency/types.d.ts +57 -0
- package/package/acode/dist/tool-group-manager.d.ts +195 -0
- package/package/acode/dist/tool-group-manager.js +4 -4
- package/package/acode/dist/types.d.ts +179 -0
- package/package/aws-client-agent-mcp/README.md +130 -215
- package/package/aws-client-agent-mcp/dist/ability-market-tools.d.ts +57 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +277 -3
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/config.d.ts +18 -0
- package/package/aws-client-agent-mcp/dist/constants.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/context-manager.d.ts +70 -0
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +61 -0
- package/package/aws-client-agent-mcp/dist/index.d.ts +10 -0
- package/package/aws-client-agent-mcp/dist/logger.d.ts +24 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +606 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.js +4 -4
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +158 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +38 -22
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +81 -0
- package/package/aws-client-agent-mcp/dist/memory-tools.d.ts +18 -0
- package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +86 -0
- package/package/aws-client-agent-mcp/dist/messageContent.d.ts +24 -0
- package/package/aws-client-agent-mcp/dist/office/office-equation.d.ts +19 -0
- package/package/aws-client-agent-mcp/dist/office/office-image.d.ts +18 -0
- package/package/aws-client-agent-mcp/dist/office/office-workspace.d.ts +29 -0
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.d.ts +18 -0
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.d.ts +6 -0
- package/package/aws-client-agent-mcp/dist/server-memory-store.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/status-reporter.d.ts +41 -0
- package/package/aws-client-agent-mcp/dist/tool-groups.d.ts +136 -0
- package/package/aws-client-agent-mcp/dist/types.d.ts +123 -0
- package/package/aws-client-agent-mcp/dist/watchdog.d.ts +7 -0
- package/package/aws-client-agent-mcp/dist/websocket-client.d.ts +108 -0
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import O,{AxiosError as x}from"axios";import g from"ws";import{getActiveBridgeHttpPort as R}from"../config.js";import{logger as s}from"../utils/logger.js";import{loadConfigs as L,loadPrimaryLifecycleConfig as P}from"./auto-register.js";import{getRuntimeAccessToken as W,normalizeSchedulerBaseUrl as C}from"./runtime-binding.js";const $=15e3,G=5e3,H=3e4,A=.2,J=200,K=1*1024*1024,X=4001,Y=768*1024,j=384*1024,z=5*6e4,p=new Map;function F(e){const n=e.serverUrl,r=e.instanceId;if(!n||!r)return null;try{const t=new URL(n),o=t.protocol==="https:"?"wss:":"ws:",u=W(n),l=L().find(h=>C(h.serverUrl)===n)||P(),i=u||l.userKey;if(u?s.debug("[TunnelClient] \u4F7F\u7528 runtime access token \u8FDE\u63A5\u96A7\u9053"):l.userKey&&s.warn("[TunnelClient] getRuntimeAccessToken \u8FD4\u56DE\u7A7A\uFF0C\u56DE\u9000\u5230 userKey\uFF08\u975E runtime token\uFF0C\u9274\u6743\u53EF\u80FD\u5931\u8D25\uFF09: targetUrl=",n),!i)return s.warn("[TunnelClient] \u7F3A\u5C11 runtime token\uFF0C\u65E0\u6CD5\u5EFA\u7ACB\u96A7\u9053: targetUrl=",n),null;const f=new URLSearchParams({instanceId:r});return{url:`${o}//${t.host}/ws/bridge-tunnel?${f.toString()}`,token:i}}catch(t){return s.warn("[TunnelClient] \u65E0\u6CD5\u89E3\u6790 serverUrl:",String(t)),null}}function le(e,n){const r=C(e);if(!r){s.warn("[TunnelClient] serverUrl \u65E0\u6548\uFF0C\u65E0\u6CD5\u542F\u52A8\u96A7\u9053:",e);return}const t=p.get(r);t&&(t.shuttingDown=!0,S(t),p.delete(r));const o={serverUrl:r,instanceId:n,streams:new Map,pendingReqChunks:new Map,shuttingDown:!1};p.set(r,o),B(o)}function de(){for(const e of p.values())e.shuttingDown=!0,S(e);p.clear()}function fe(e){const n=C(e);if(!n)return;const r=p.get(n);r&&(r.shuttingDown=!0,S(r),p.delete(n),s.info(`[TunnelClient] tunnel stopped: ${n}`))}function ae(e){const n=new Set(e.map(r=>C(r)).filter(r=>!!r));for(const[r,t]of p.entries())n.has(r)||(s.info(`[TunnelClient] serverUrl \u5DF2\u4E0D\u5728\u914D\u7F6E\u4E2D\uFF0C\u505C\u6B62\u65E7\u96A7\u9053: ${r}`),t.shuttingDown=!0,S(t),p.delete(r))}function S(e){e.timer&&(clearInterval(e.timer),e.timer=void 0),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);for(const[n,r]of e.streams.entries()){try{r.ws.close(1e3,"tunnel client stopped")}catch{}e.streams.delete(n)}if(e.ws){e.ws.removeAllListeners();try{e.ws.close(1e3,"tunnel client stopped")}catch{}e.ws=void 0}}function B(e){if(e.shuttingDown)return;const n=e.instanceId;if(!n)return;const r=F(e);if(!r){b(e);return}s.info("[TunnelClient] \u8FDE\u63A5\u96A7\u9053\u670D\u52A1\u7AEF:",r.url);const t=new g(r.url,{handshakeTimeout:15e3,headers:{"X-Runtime-Token":r.token}});e.ws=t,t.on("open",()=>{s.info("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5DF2\u5EFA\u7ACB: server=",e.serverUrl,"instanceId=",n),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0,e.reconnectAttempts=0,e.timer=setInterval(()=>{t.readyState===g.OPEN&&t.send(JSON.stringify({t:"ping"}))},$)}),t.on("unexpected-response",(o,u)=>{s.error("[TunnelClient] \u670D\u52A1\u7AEF\u62D2\u7EDD\u8FDE\u63A5\uFF08\u975E 101 \u54CD\u5E94\uFF09: server=",e.serverUrl,"statusCode=",u.statusCode,"statusMessage=",u.statusMessage)}),t.on("upgrade",o=>{s.debug("[TunnelClient] \u6536\u5230\u5347\u7EA7\u54CD\u5E94: statusCode=",o.statusCode)}),t.on("message",o=>{let u;typeof o=="string"?u=o:Buffer.isBuffer(o)?u=o.toString("utf-8"):u=Buffer.from(o).toString("utf-8");try{const l=JSON.parse(u);M(e,l)}catch(l){s.warn("[TunnelClient] \u89E3\u6790\u96A7\u9053\u6D88\u606F\u5931\u8D25:",String(l))}}),t.on("close",(o,u)=>{if(s.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5173\u95ED: server=",e.serverUrl,"code=",o,"reason=",String(u)),k(e),o===X){s.warn("[TunnelClient] \u9274\u6743\u5931\u8D25\uFF084001\uFF09\uFF0C\u505C\u6B62\u81EA\u52A8\u91CD\u8FDE\uFF1B\u5F85\u91CD\u65B0\u6CE8\u518C\u540E\u518D\u542F\u52A8\u96A7\u9053: server=",e.serverUrl);return}b(e)}),t.on("error",o=>{s.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u9519\u8BEF: server=",e.serverUrl,"err=",o.message,"code=",o.code),k(e),b(e)})}function k(e){e.timer&&(clearInterval(e.timer),e.timer=void 0);for(const[n,r]of e.streams.entries()){try{r.ws.close(1011,"tunnel disconnected")}catch{}e.streams.delete(n)}for(const n of Array.from(e.pendingReqChunks.keys()))E(e,n);e.ws=void 0}function b(e){if(e.shuttingDown||e.reconnectTimer)return;const n=(e.reconnectAttempts??0)+1;e.reconnectAttempts=n;const r=Math.min(G*Math.pow(2,n-1),H),t=1-A+Math.random()*A*2,o=Math.round(r*t);s.debug("[TunnelClient] \u8BA1\u5212\u91CD\u8FDE: server=",e.serverUrl,"attempt=",n,"delayMs=",o),e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,B(e)},o)}function M(e,n){switch(n.t){case"req":n.chunked?V(e,n):U(e,n);break;case"reqchunk":Q(e,n);break;case"reqend":Z(e,n);break;case"wsopen":ee(e,n);break;case"wsmsg":ne(e,n);break;case"wsclose":re(e,n);break;case"ping":d(e,{t:"pong"});break;case"pong":break;default:s.debug("[TunnelClient] \u672A\u77E5\u6D88\u606F\u7C7B\u578B: t=",n.t)}}function V(e,n){E(e,n.id);const r=setTimeout(()=>{s.warn("[TunnelClient] \u8BF7\u6C42\u4F53\u62C6\u5E27\u8D85\u65F6\uFF0C\u4E22\u5F03\u534A\u5305:",n.id),e.pendingReqChunks.delete(n.id)},z);r.unref?.(),e.pendingReqChunks.set(n.id,{method:n.method||"GET",path:n.path||"/",headers:n.headers,parts:[],timer:r})}function Q(e,n){const r=e.pendingReqChunks.get(n.id);if(!r){s.debug("[TunnelClient] \u6536\u5230\u65E0\u4E3B reqchunk\uFF0C\u5DF2\u5FFD\u7565:",n.id);return}n.d&&r.parts.push(Buffer.from(n.d,"base64"))}async function Z(e,n){const r=e.pendingReqChunks.get(n.id);if(!r){s.debug("[TunnelClient] \u6536\u5230\u65E0\u4E3B reqend\uFF0C\u5DF2\u5FFD\u7565:",n.id);return}E(e,n.id);const t=Buffer.concat(r.parts);await U(e,{t:"req",id:n.id,method:r.method,path:r.path,headers:r.headers,body:t.length>0?t.toString("base64"):null})}function E(e,n){const r=e.pendingReqChunks.get(n);r&&(clearTimeout(r.timer),e.pendingReqChunks.delete(n))}async function U(e,n){const r=n.id,t=n.method||"GET",o=n.path||"/",u=`http://127.0.0.1:${R()}${o}`;try{const l=n.body?Buffer.from(n.body,"base64"):void 0,i={};if(n.headers)for(const[a,c]of Object.entries(n.headers))c&&c.length>0&&(i[a]=c[0]);i["x-bridge-tunnel-source"]=e.serverUrl;const f=await O.request({url:u,method:t,headers:i,data:l,timeout:0,responseType:"stream",validateStatus:()=>!0}),h={};for(const[a,c]of Object.entries(f.headers))c!==void 0&&(h[a]=Array.isArray(c)?c:[String(c)]);const v=f.data,I=String(h["content-type"]?.[0]||"").toLowerCase().includes("text/event-stream"),m=[];let w=0,T=!1,y=!1;try{if(v)for await(const a of v){const c=Buffer.isBuffer(a)?a:Buffer.from(a);if(c.length!==0){if(T){if(!_(e,r,c))return}else if(I){if(T=!0,y=!0,!d(e,{t:"res",id:r,status:f.status,headers:h,body:null,chunked:!0})||!_(e,r,c))return}else if(m.push(c),w+=c.length,w>Y){if(T=!0,y=!0,!d(e,{t:"res",id:r,status:f.status,headers:h,body:null,chunked:!0}))return;for(const D of m)if(!_(e,r,D))return;m.length=0,w=0}}}}catch(a){const c=a instanceof Error?a.message:String(a);s.warn("[TunnelClient] \u672C\u5730\u6D41\u8BFB\u53D6\u4E2D\u65AD:",t,o,"->",c),y?d(e,{t:"resend",id:r,error:c}):d(e,{t:"res",id:r,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(c).toString("base64")});return}if(T){d(e,{t:"resend",id:r});return}const N=w>0?Buffer.concat(m).toString("base64"):"";d(e,{t:"res",id:r,status:f.status,headers:h,body:N||null})}catch(l){const i=l instanceof x?l.message:String(l);s.warn("[TunnelClient] \u672C\u5730\u8F6C\u53D1\u5931\u8D25:",t,o,"->",i),d(e,{t:"res",id:r,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(i).toString("base64")})}}function _(e,n,r){let t=0;for(;t<r.length;){const o=r.subarray(t,t+j);if(!d(e,{t:"reschunk",id:n,d:o.toString("base64")}))return!1;t+=o.length}return!0}function ee(e,n){const r=n.id,t=n.path||"/",o=`ws://127.0.0.1:${R()}${t}`;let u;try{u=new g(o,{handshakeTimeout:1e4})}catch(i){s.warn("[TunnelClient] \u672C\u5730 WS \u8FDE\u63A5\u5931\u8D25:",String(i)),d(e,{t:"wsclose",id:r,code:1011,reason:"local ws connect failed"});return}const l={ws:u,pending:[]};e.streams.set(r,l),u.on("open",()=>{for(const i of l.pending)q(l,i.data,i.bin);l.pending=[],d(e,{t:"wsopened",id:r})}),u.on("message",(i,f)=>{const h=Buffer.isBuffer(i)?i:Buffer.from(i);f&&e.ws&&e.ws.bufferedAmount>K||d(e,{t:"wsmsg",id:r,bin:f,d:h.toString("base64")})}),u.on("close",(i,f)=>{e.streams.delete(r),d(e,{t:"wsclose",id:r,code:i,reason:String(f)})}),u.on("error",i=>{s.warn("[TunnelClient] \u672C\u5730 WS \u9519\u8BEF: id=",r,"err=",i.message),e.streams.delete(r);try{u.close(1011,i.message)}catch{}d(e,{t:"wsclose",id:r,code:1011,reason:i.message})})}function q(e,n,r){r?e.ws.send(n):e.ws.send(n.toString("utf-8"))}function ne(e,n){const r=e.streams.get(n.id);if(!r)return;const t=n.d?Buffer.from(n.d,"base64"):Buffer.alloc(0);if(r.ws.readyState!==g.OPEN){r.pending.length>=J&&(r.pending.shift(),s.warn("[TunnelClient] \u672C\u5730 WS \u672A\u5C31\u7EEA\uFF0C\u6392\u961F\u6D88\u606F\u8D85\u4E0A\u9650\uFF0C\u4E22\u5F03\u6700\u65E7\u4E00\u6761: id=",n.id)),r.pending.push({data:t,bin:!!n.bin});return}q(r,t,!!n.bin)}function re(e,n){const r=e.streams.get(n.id);if(r){e.streams.delete(n.id);try{r.ws.close(n.code??1e3,n.reason||"")}catch{}}}function d(e,n){if(!e.ws||e.ws.readyState!==g.OPEN)return!1;try{return e.ws.send(JSON.stringify(n)),!0}catch(r){return s.warn("[TunnelClient] sendJson \u5931\u8D25:",String(r)),!1}}const he={createState(e="http://server.test",n="test-instance"){return{serverUrl:e,instanceId:n,streams:new Map,pendingReqChunks:new Map,shuttingDown:!1}},dispatch(e,n){M(e,n)},pendingChunkIds(e){return Array.from(e.pendingReqChunks.keys())},cleanup(e){k(e)}};export{he as __tunnelClientTestHooks,le as startTunnelClient,de as stopTunnelClient,fe as stopTunnelClientForServer,ae as stopTunnelClientsExcept};
|
|
1
|
+
import O,{AxiosError as L}from"axios";import m from"ws";import{getActiveBridgeHttpPort as v}from"../config.js";import{logger as i}from"../utils/logger.js";import{buildTargetKey as S}from"../utils/target-identity.js";import{getRuntimeAccessToken as W,normalizeSchedulerBaseUrl as A}from"./runtime-binding.js";const P=15e3,$=5e3,K=3e4,B=.2,G=200,H=1*1024*1024,J=4001,F=768*1024,X=384*1024,Y=5*6e4,f=new Map;function j(e){const n=e.serverUrl,t=e.instanceId;if(!n||!t)return null;try{const r=new URL(n),o=r.protocol==="https:"?"wss:":"ws:",s=W(n,e.userKey);if(!s)return i.warn("[TunnelClient] \u7F3A\u5C11\u8BE5\u76EE\u6807\u8EAB\u4EFD\u7684 runtime token\uFF0C\u65E0\u6CD5\u5EFA\u7ACB\u96A7\u9053\uFF08\u8BF7\u91CD\u65B0\u6CE8\u518C bridge\uFF09: targetUrl=",n),null;i.debug("[TunnelClient] \u4F7F\u7528 runtime access token \u8FDE\u63A5\u96A7\u9053");const c=new URLSearchParams({instanceId:t});return{url:`${o}//${r.host}/ws/bridge-tunnel?${c.toString()}`,token:s}}catch(r){return i.warn("[TunnelClient] \u65E0\u6CD5\u89E3\u6790 serverUrl:",String(r)),null}}function ce(e,n,t){const r=A(e);if(!r){i.warn("[TunnelClient] serverUrl \u65E0\u6548\uFF0C\u65E0\u6CD5\u542F\u52A8\u96A7\u9053:",e);return}const o=S(r,t),s=f.get(o);s&&(s.shuttingDown=!0,g(s),f.delete(o));const c={serverUrl:r,targetKey:o,userKey:String(t||"").trim()||void 0,instanceId:n,streams:new Map,pendingReqChunks:new Map,shuttingDown:!1};f.set(o,c),M(c)}function le(){for(const e of f.values())e.shuttingDown=!0,g(e);f.clear()}function de(e,n){const t=S(e,n),r=f.get(t);r&&(r.shuttingDown=!0,g(r),f.delete(t),i.info(`[TunnelClient] tunnel stopped: ${t}`))}function fe(e){const n=A(e);if(!n)return;const t=`${n}#`;for(const[r,o]of[...f.entries()])r!==n&&!r.startsWith(t)||(o.shuttingDown=!0,g(o),f.delete(r),i.info(`[TunnelClient] tunnel stopped: ${r}`))}function ae(e){const n=new Set(e.map(t=>String(t||"").trim()).filter(t=>!!t));for(const[t,r]of f.entries())n.has(t)||(i.info(`[TunnelClient] \u76EE\u6807\u5DF2\u4E0D\u5728\u914D\u7F6E\u4E2D\uFF0C\u505C\u6B62\u65E7\u96A7\u9053: ${t}`),r.shuttingDown=!0,g(r),f.delete(t))}function g(e){e.timer&&(clearInterval(e.timer),e.timer=void 0),e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0);for(const[n,t]of e.streams.entries()){try{t.ws.close(1e3,"tunnel client stopped")}catch{}e.streams.delete(n)}if(e.ws){const n=e.ws;e.ws=void 0,n.removeAllListeners(),n.on("error",()=>{});try{n.close(1e3,"tunnel client stopped")}catch{}}}function M(e){if(e.shuttingDown)return;const n=e.instanceId;if(!n)return;const t=j(e);if(!t){k(e);return}i.info("[TunnelClient] \u8FDE\u63A5\u96A7\u9053\u670D\u52A1\u7AEF:",t.url);const r=new m(t.url,{handshakeTimeout:15e3,headers:{"X-Runtime-Token":t.token}});e.ws=r,r.on("open",()=>{i.info("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5DF2\u5EFA\u7ACB: server=",e.serverUrl,"instanceId=",n),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0,e.reconnectAttempts=0,e.timer=setInterval(()=>{r.readyState===m.OPEN&&r.send(JSON.stringify({t:"ping"}))},P)}),r.on("unexpected-response",(o,s)=>{i.error("[TunnelClient] \u670D\u52A1\u7AEF\u62D2\u7EDD\u8FDE\u63A5\uFF08\u975E 101 \u54CD\u5E94\uFF09: server=",e.serverUrl,"statusCode=",s.statusCode,"statusMessage=",s.statusMessage)}),r.on("upgrade",o=>{i.debug("[TunnelClient] \u6536\u5230\u5347\u7EA7\u54CD\u5E94: statusCode=",o.statusCode)}),r.on("message",o=>{let s;typeof o=="string"?s=o:Buffer.isBuffer(o)?s=o.toString("utf-8"):s=Buffer.from(o).toString("utf-8");try{const c=JSON.parse(s);q(e,c)}catch(c){i.warn("[TunnelClient] \u89E3\u6790\u96A7\u9053\u6D88\u606F\u5931\u8D25:",String(c))}}),r.on("close",(o,s)=>{if(i.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u5173\u95ED: server=",e.serverUrl,"code=",o,"reason=",String(s)),b(e),o===J){i.warn("[TunnelClient] \u9274\u6743\u5931\u8D25\uFF084001\uFF09\uFF0C\u505C\u6B62\u81EA\u52A8\u91CD\u8FDE\uFF1B\u5F85\u91CD\u65B0\u6CE8\u518C\u540E\u518D\u542F\u52A8\u96A7\u9053: server=",e.serverUrl);return}k(e)}),r.on("error",o=>{i.warn("[TunnelClient] \u96A7\u9053\u8FDE\u63A5\u9519\u8BEF: server=",e.serverUrl,"err=",o.message,"code=",o.code),b(e),k(e)})}function b(e){e.timer&&(clearInterval(e.timer),e.timer=void 0);for(const[n,t]of e.streams.entries()){try{t.ws.close(1011,"tunnel disconnected")}catch{}e.streams.delete(n)}for(const n of Array.from(e.pendingReqChunks.keys()))E(e,n);e.ws=void 0}function k(e){if(e.shuttingDown||e.reconnectTimer)return;const n=(e.reconnectAttempts??0)+1;e.reconnectAttempts=n;const t=Math.min($*Math.pow(2,n-1),K),r=1-B+Math.random()*B*2,o=Math.round(t*r);i.debug("[TunnelClient] \u8BA1\u5212\u91CD\u8FDE: server=",e.serverUrl,"attempt=",n,"delayMs=",o),e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,M(e)},o)}function q(e,n){switch(n.t){case"req":n.chunked?z(e,n):I(e,n);break;case"reqchunk":V(e,n);break;case"reqend":Q(e,n);break;case"wsopen":Z(e,n);break;case"wsmsg":ee(e,n);break;case"wsclose":ne(e,n);break;case"ping":d(e,{t:"pong"});break;case"pong":break;default:i.debug("[TunnelClient] \u672A\u77E5\u6D88\u606F\u7C7B\u578B: t=",n.t)}}function z(e,n){E(e,n.id);const t=setTimeout(()=>{i.warn("[TunnelClient] \u8BF7\u6C42\u4F53\u62C6\u5E27\u8D85\u65F6\uFF0C\u4E22\u5F03\u534A\u5305:",n.id),e.pendingReqChunks.delete(n.id)},Y);t.unref?.(),e.pendingReqChunks.set(n.id,{method:n.method||"GET",path:n.path||"/",headers:n.headers,parts:[],timer:t})}function V(e,n){const t=e.pendingReqChunks.get(n.id);if(!t){i.debug("[TunnelClient] \u6536\u5230\u65E0\u4E3B reqchunk\uFF0C\u5DF2\u5FFD\u7565:",n.id);return}n.d&&t.parts.push(Buffer.from(n.d,"base64"))}async function Q(e,n){const t=e.pendingReqChunks.get(n.id);if(!t){i.debug("[TunnelClient] \u6536\u5230\u65E0\u4E3B reqend\uFF0C\u5DF2\u5FFD\u7565:",n.id);return}E(e,n.id);const r=Buffer.concat(t.parts);await I(e,{t:"req",id:n.id,method:t.method,path:t.path,headers:t.headers,body:r.length>0?r.toString("base64"):null})}function E(e,n){const t=e.pendingReqChunks.get(n);t&&(clearTimeout(t.timer),e.pendingReqChunks.delete(n))}async function I(e,n){const t=n.id,r=n.method||"GET",o=n.path||"/",s=`http://127.0.0.1:${v()}${o}`;try{const c=n.body?Buffer.from(n.body,"base64"):void 0,u={};if(n.headers)for(const[a,l]of Object.entries(n.headers))l&&l.length>0&&(u[a]=l[0]);u["x-bridge-tunnel-source"]=e.serverUrl;const h=await O.request({url:s,method:r,headers:u,data:c,timeout:0,responseType:"stream",validateStatus:()=>!0}),p={};for(const[a,l]of Object.entries(h.headers))l!==void 0&&(p[a]=Array.isArray(l)?l:[String(l)]);const R=h.data,U=String(p["content-type"]?.[0]||"").toLowerCase().includes("text/event-stream"),T=[];let w=0,C=!1,y=!1;try{if(R)for await(const a of R){const l=Buffer.isBuffer(a)?a:Buffer.from(a);if(l.length!==0){if(C){if(!_(e,t,l))return}else if(U){if(C=!0,y=!0,!d(e,{t:"res",id:t,status:h.status,headers:p,body:null,chunked:!0})||!_(e,t,l))return}else if(T.push(l),w+=l.length,w>F){if(C=!0,y=!0,!d(e,{t:"res",id:t,status:h.status,headers:p,body:null,chunked:!0}))return;for(const x of T)if(!_(e,t,x))return;T.length=0,w=0}}}}catch(a){const l=a instanceof Error?a.message:String(a);i.warn("[TunnelClient] \u672C\u5730\u6D41\u8BFB\u53D6\u4E2D\u65AD:",r,o,"->",l),y?d(e,{t:"resend",id:t,error:l}):d(e,{t:"res",id:t,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(l).toString("base64")});return}if(C){d(e,{t:"resend",id:t});return}const D=w>0?Buffer.concat(T).toString("base64"):"";d(e,{t:"res",id:t,status:h.status,headers:p,body:D||null})}catch(c){const u=c instanceof L?c.message:String(c);i.warn("[TunnelClient] \u672C\u5730\u8F6C\u53D1\u5931\u8D25:",r,o,"->",u),d(e,{t:"res",id:t,status:502,headers:{"content-type":["text/plain; charset=utf-8"]},body:Buffer.from(u).toString("base64")})}}function _(e,n,t){let r=0;for(;r<t.length;){const o=t.subarray(r,r+X);if(!d(e,{t:"reschunk",id:n,d:o.toString("base64")}))return!1;r+=o.length}return!0}function Z(e,n){const t=n.id,r=n.path||"/",o=`ws://127.0.0.1:${v()}${r}`;let s;try{s=new m(o,{handshakeTimeout:1e4})}catch(u){i.warn("[TunnelClient] \u672C\u5730 WS \u8FDE\u63A5\u5931\u8D25:",String(u)),d(e,{t:"wsclose",id:t,code:1011,reason:"local ws connect failed"});return}const c={ws:s,pending:[]};e.streams.set(t,c),s.on("open",()=>{for(const u of c.pending)N(c,u.data,u.bin);c.pending=[],d(e,{t:"wsopened",id:t})}),s.on("message",(u,h)=>{const p=Buffer.isBuffer(u)?u:Buffer.from(u);h&&e.ws&&e.ws.bufferedAmount>H||d(e,{t:"wsmsg",id:t,bin:h,d:p.toString("base64")})}),s.on("close",(u,h)=>{e.streams.delete(t),d(e,{t:"wsclose",id:t,code:u,reason:String(h)})}),s.on("error",u=>{i.warn("[TunnelClient] \u672C\u5730 WS \u9519\u8BEF: id=",t,"err=",u.message),e.streams.delete(t);try{s.close(1011,u.message)}catch{}d(e,{t:"wsclose",id:t,code:1011,reason:u.message})})}function N(e,n,t){t?e.ws.send(n):e.ws.send(n.toString("utf-8"))}function ee(e,n){const t=e.streams.get(n.id);if(!t)return;const r=n.d?Buffer.from(n.d,"base64"):Buffer.alloc(0);if(t.ws.readyState!==m.OPEN){t.pending.length>=G&&(t.pending.shift(),i.warn("[TunnelClient] \u672C\u5730 WS \u672A\u5C31\u7EEA\uFF0C\u6392\u961F\u6D88\u606F\u8D85\u4E0A\u9650\uFF0C\u4E22\u5F03\u6700\u65E7\u4E00\u6761: id=",n.id)),t.pending.push({data:r,bin:!!n.bin});return}N(t,r,!!n.bin)}function ne(e,n){const t=e.streams.get(n.id);if(t){e.streams.delete(n.id);try{t.ws.close(n.code??1e3,n.reason||"")}catch{}}}function d(e,n){if(!e.ws||e.ws.readyState!==m.OPEN)return!1;try{return e.ws.send(JSON.stringify(n)),!0}catch(t){return i.warn("[TunnelClient] sendJson \u5931\u8D25:",String(t)),!1}}const he={createState(e="http://server.test",n="test-instance"){return{serverUrl:e,targetKey:S(e,void 0),instanceId:n,streams:new Map,pendingReqChunks:new Map,shuttingDown:!1}},dispatch(e,n){q(e,n)},pendingChunkIds(e){return Array.from(e.pendingReqChunks.keys())},activeTargetKeys(){return[...f.keys()]},cleanup(e){b(e)},teardown(e){g(e)}};export{he as __tunnelClientTestHooks,ce as startTunnelClient,le as stopTunnelClient,fe as stopTunnelClientForServer,de as stopTunnelClientForTarget,ae as stopTunnelClientsExcept};
|
|
2
2
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
`,{encoding:"utf8",mode:384})}async function I(){const e=await S();if(!e.ok||!e.hasUpdate||!e.latestVersion||(await b()).latestVersion===e.latestVersion)return!1;const a=U().filter(t=>t.enabled&&!!t.serverUrl);if(a.length===0)return r.info(`[update-notifier] \u68C0\u6D4B\u5230\u65B0\u7248\u672C v${e.latestVersion}\uFF08\u5F53\u524D v${e.currentVersion}\uFF09\uFF0C\u4F46\u672A\u914D\u7F6E\u4EFB\u4F55\u8C03\u5EA6\u4E2D\u5FC3\uFF0C\u8DF3\u8FC7\u901A\u77E5`),!1;const i=e.currentVersion,l=e.latestVersion,
|
|
1
|
+
import d from"node:fs/promises";import g from"node:path";import E from"axios";import{getRuntimeHomeDir as w}from"../config.js";import{createLogger as A}from"../utils/logger.js";import{checkBridgeUpdate as S}from"../utils/npm-version.js";import{loadConfigs as U,resolveRuntimeBridgeBaseUrl as $}from"./auto-register.js";import{getRuntimeAccessToken as D}from"./runtime-binding.js";import{appendUpdateLog as N}from"./update-log.js";const r=A("update-notifier"),h=6*60*60*1e3,y=3e4,T="\u5F53\u524D\u5BA2\u6237\u7AEFbridge\u53EF\u66F4\u65B0\uFF0C\u8BF7\u53CA\u65F6\u66F4\u65B0~";function v(){return g.join(w(),".aws-bridge","update-notify-state.json")}async function b(){try{const e=await d.readFile(v(),"utf8"),n=JSON.parse(e);return{latestVersion:n.latestVersion,notifiedAt:n.notifiedAt}}catch{return{}}}async function B(e){const n=v();await d.mkdir(g.dirname(n),{recursive:!0}),await d.writeFile(n,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384})}async function I(){const e=await S();if(!e.ok||!e.hasUpdate||!e.latestVersion||(await b()).latestVersion===e.latestVersion)return!1;const a=U().filter(t=>t.enabled&&!!t.serverUrl);if(a.length===0)return r.info(`[update-notifier] \u68C0\u6D4B\u5230\u65B0\u7248\u672C v${e.latestVersion}\uFF08\u5F53\u524D v${e.currentVersion}\uFF09\uFF0C\u4F46\u672A\u914D\u7F6E\u4EFB\u4F55\u8C03\u5EA6\u4E2D\u5FC3\uFF0C\u8DF3\u8FC7\u901A\u77E5`),!1;const i=e.currentVersion,l=e.latestVersion,f=a[0]?.instanceName||"",u={eventType:"update-available",bridgeInstanceId:a[0]?.instanceId||"",bridgeInstanceName:f,currentVersion:i,latestVersion:l,message:T},c=await Promise.allSettled(a.map(async t=>{const s=String(t.serverUrl).replace(/\/+$/,""),p=D(s,t.userKey);if(!p)throw r.warn(`[update-notifier] \u8DF3\u8FC7 ${s}\uFF1A\u7F3A\u5C11 runtime access token\uFF08\u672A\u6CE8\u518C\uFF09`),new Error("\u7F3A\u5C11 runtime access token\uFF08\u672A\u6CE8\u518C\uFF09");const _=$(t);await E.post(`${s}/api/runtime/callback/bridge-update-notify`,{...u,bridgeInstanceId:t.instanceId||u.bridgeInstanceId,bridgeInstanceName:t.instanceName||f,runtimeBridgeBaseUrl:_},{headers:{"X-Runtime-Token":p},timeout:1e4})})),m=c.some(t=>t.status==="fulfilled");if(m)await B({latestVersion:l,notifiedAt:new Date().toISOString()}),r.info(`[update-notifier] \u5DF2\u901A\u77E5 ${c.filter(t=>t.status==="fulfilled").length}/${c.length} \u4E2A\u8C03\u5EA6\u4E2D\u5FC3\uFF1Av${i} -> v${l}`),N(`\u68C0\u6D4B\u5230\u65B0\u7248\u672C v${l}\uFF08\u5F53\u524D v${i}\uFF09\uFF0C\u5DF2\u53D1\u9001\u53EF\u66F4\u65B0\u901A\u77E5`).catch(()=>{});else{r.warn(`[update-notifier] \u5411 ${c.length} \u4E2A\u8C03\u5EA6\u4E2D\u5FC3\u53D1\u9001\u66F4\u65B0\u901A\u77E5\u5747\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u4E2A\u5468\u671F\u91CD\u8BD5`);for(const[t,s]of c.entries())s.status==="rejected"&&r.warn(`[update-notifier] \u901A\u77E5\u5931\u8D25: ${a[t]?.serverUrl}, ${s.reason?.message}`)}return m}let o=null;function M(){if(process.env.AWS_BRIDGE_UPDATE_CHECK_DISABLED==="true"){r.info("[update-notifier] \u7248\u672C\u68C0\u67E5\u5DF2\u901A\u8FC7 AWS_BRIDGE_UPDATE_CHECK_DISABLED \u5173\u95ED");return}if(o)return;const e=Number(process.env.AWS_BRIDGE_UPDATE_CHECK_INTERVAL_HOURS),n=Number.isFinite(e)&&e>0?e*60*60*1e3:h;setTimeout(()=>{I().catch(i=>{r.warn(`[update-notifier] \u68C0\u67E5\u5F02\u5E38: ${i?.message}`)})},y).unref?.(),o=setInterval(()=>{I().catch(i=>{r.warn(`[update-notifier] \u68C0\u67E5\u5F02\u5E38: ${i?.message}`)})},n),o.unref?.(),r.info(`[update-notifier] \u7248\u672C\u68C0\u67E5\u5B9A\u65F6\u4EFB\u52A1\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${Math.round(n/36e5)} \u5C0F\u65F6`)}function O(){o&&(clearInterval(o),o=null)}export{I as runUpdateCheck,M as startUpdateNotifier,O as stopUpdateNotifier};
|
|
3
3
|
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
import type { NextFunction, Request, Response } from "express";
|
|
27
|
+
export interface UserScope {
|
|
28
|
+
tenantId: string;
|
|
29
|
+
userId: string;
|
|
30
|
+
}
|
|
31
|
+
export declare const SCOPE_ID_PATTERN: RegExp;
|
|
32
|
+
|
|
33
|
+
export declare const LEGACY_SCOPE: Readonly<UserScope>;
|
|
34
|
+
|
|
35
|
+
export declare const TENANT_HEADER = "x-tenant-id";
|
|
36
|
+
export declare const USER_HEADER = "x-user-id";
|
|
37
|
+
declare module "express-serve-static-core" {
|
|
38
|
+
interface Request {
|
|
39
|
+
|
|
40
|
+
userScope?: UserScope;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
export declare function sanitizeScopeId(id: unknown): string;
|
|
53
|
+
|
|
54
|
+
export declare function isValidScopeId(id: unknown): id is string;
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
export declare function normalizeUserScope(tenantId: unknown, userId: unknown): UserScope | null;
|
|
60
|
+
|
|
61
|
+
export declare function scopeEquals(a: UserScope | null, b: UserScope | null): boolean;
|
|
62
|
+
|
|
63
|
+
export declare function isLegacyScope(scope: UserScope | null): boolean;
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
export declare function isLegacyScopeAllowed(): boolean;
|
|
69
|
+
|
|
70
|
+
export declare function isLegacyFallbackDisabled(): boolean;
|
|
71
|
+
|
|
72
|
+
export declare function getUserScopeRoot(scope: UserScope): string;
|
|
73
|
+
|
|
74
|
+
export declare function getUserAiConfigFile(scope: UserScope): string;
|
|
75
|
+
|
|
76
|
+
export declare function getUserSkillsDir(scope: UserScope): string;
|
|
77
|
+
|
|
78
|
+
export declare function getUserSkillsDeployedDir(scope: UserScope): string;
|
|
79
|
+
|
|
80
|
+
export declare function getUserMcpDir(scope: UserScope): string;
|
|
81
|
+
|
|
82
|
+
export declare function getUserMcpDeployedDir(scope: UserScope): string;
|
|
83
|
+
|
|
84
|
+
export declare function getUserMcpPackagesDir(scope: UserScope): string;
|
|
85
|
+
|
|
86
|
+
export declare function getUserPluginsDir(scope: UserScope): string;
|
|
87
|
+
|
|
88
|
+
export declare function getUserPluginsDeployedDir(scope: UserScope): string;
|
|
89
|
+
export type CapabilityType = "skills" | "mcp" | "plugins";
|
|
90
|
+
|
|
91
|
+
export declare function getUserCapabilityDir(scope: UserScope, type: CapabilityType): string;
|
|
92
|
+
|
|
93
|
+
export declare function getUserCapabilityDefaultsFile(scope: UserScope, type: CapabilityType): string;
|
|
94
|
+
|
|
95
|
+
export declare function getUserCapabilityAgentFile(scope: UserScope, type: CapabilityType, agentId: string): string;
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
export declare function extractUserScope(req: Request): UserScope | null;
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
export declare function resolveUserScope(req: Request, _res: Response, next: NextFunction): void;
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
export declare function requireUserScope(req: Request, res: Response, next: NextFunction): void;
|
|
111
|
+
|
|
112
|
+
export declare function getUserScopeOrThrow(req: Request): UserScope;
|
|
113
|
+
|
|
114
|
+
export declare function setAgentOwnershipChecker(checker: (agentId: string, scope: UserScope) => boolean): void;
|
|
115
|
+
export declare function requireAgentOwnership(req: Request, res: Response, next: NextFunction): void;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import n from"node:path";import{getBridgeDataHome as I}from"../config.js";import{loadRuntimeBinding as x}from"./runtime-binding.js";const m=/^[a-zA-Z0-9_.-]+$/,c=Object.freeze({tenantId:"_legacy",userId:"_legacy"}),y="x-tenant-id",U="x-user-id";function s(e){const r=String(e??"").replace(/[^a-zA-Z0-9_.-]/g,"_");return/^\.+$/.test(r)?"_":r.replace(/^\.+/g,"")}function w(e){return typeof e=="string"&&e.length>0&&m.test(e)}function p(e,r){const t=String(e??"").trim(),o=String(r??"").trim();return!t||!o?null:{tenantId:t,userId:o}}function D(e,r){return!e||!r?!1:s(e.tenantId)===s(r.tenantId)&&s(e.userId)===s(r.userId)}function b(e){return D(e,c)}function l(){return String(process.env.AWS_BRIDGE_LEGACY_SCOPE||"").trim().toLowerCase()==="1"}function L(){return String(process.env.AWS_BRIDGE_DISABLE_LEGACY_FALLBACK||"").trim().toLowerCase()==="1"}function _(e){return[s(e.tenantId),s(e.userId)]}function i(e){return n.join(I(),"users",..._(e))}function R(e){return n.join(i(e),"ai","acode.json")}function j(e){return n.join(i(e),"skills")}function O(e){return n.join(j(e),"deployed")}function d(e){return n.join(i(e),"mcp")}function P(e){return n.join(d(e),"deployed")}function B(e){return n.join(d(e),"packages")}function A(e){return n.join(i(e),"plugins")}function F(e){return n.join(A(e),"deployed")}function g(e,r){return n.join(i(e),"capability",r)}function T(e,r){return n.join(g(e,r),"config.json")}function z(e,r,t){return n.join(g(e,r),"agents",`${s(t)}.json`)}function E(...e){for(const r of e){const t=String(r??"").trim();if(t)return t}return""}function u(e){const r=p(e.header(y),e.header(U));if(r)return r;const t=e.body??{};return p(t.tenantId,E(t.ownerUserId,t.userId))}function S(){try{const e=x();return e?.userId?p("_local",e.userId):null}catch{return null}}function G(e,r,t){const o=u(e)??S();o?e.userScope=o:l()&&(e.userScope={...c}),t()}function v(e,r,t){const o=u(e)??S();if(o){e.userScope=o,t();return}if(l()){e.userScope={...c},t();return}r.status(400).json({ok:!1,error:"user-scope-required",message:"\u8BF7\u6C42\u7F3A\u5C11 X-Tenant-Id / X-User-Id\uFF08\u6216\u4F53 tenantId + ownerUserId\uFF09\u8EAB\u4EFD"})}function H(e){const r=e.userScope??u(e);if(!r)throw new Error("user-scope-required: \u8BF7\u6C42\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD");return r}let a=null;function N(e){a=e}function M(e,r,t){const o=String(e.params?.agentId??e.body?.agentId??"").trim();if(!o){t();return}const f=e.userScope??u(e);if(!f){r.status(400).json({ok:!1,error:"user-scope-required",message:"agent \u7EA7\u64CD\u4F5C\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD"});return}if(a&&!a(o,f)){r.status(403).json({ok:!1,error:"agent-ownership-mismatch",message:"\u8BE5\u5B9E\u4F8B\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237"});return}t()}export{c as LEGACY_SCOPE,m as SCOPE_ID_PATTERN,y as TENANT_HEADER,U as USER_HEADER,u as extractUserScope,R as getUserAiConfigFile,z as getUserCapabilityAgentFile,T as getUserCapabilityDefaultsFile,g as getUserCapabilityDir,P as getUserMcpDeployedDir,d as getUserMcpDir,B as getUserMcpPackagesDir,F as getUserPluginsDeployedDir,A as getUserPluginsDir,H as getUserScopeOrThrow,i as getUserScopeRoot,O as getUserSkillsDeployedDir,j as getUserSkillsDir,L as isLegacyFallbackDisabled,b as isLegacyScope,l as isLegacyScopeAllowed,w as isValidScopeId,p as normalizeUserScope,M as requireAgentOwnership,v as requireUserScope,G as resolveUserScope,s as sanitizeScopeId,D as scopeEquals,N as setAgentOwnershipChecker};
|
|
2
|
+
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
2
5
|
export interface WorkspaceFileItem {
|
|
3
6
|
name: string;
|
|
4
7
|
path: string;
|
|
@@ -185,16 +188,38 @@ export interface ChmodWorkspaceEntryResult {
|
|
|
185
188
|
changedCount: number;
|
|
186
189
|
}
|
|
187
190
|
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
|
|
188
197
|
export declare function listWorkspaceDirectory(params: WorkspacePathParams): Promise<ListWorkspaceDirectoryResult>;
|
|
189
198
|
|
|
199
|
+
|
|
200
|
+
|
|
190
201
|
export declare function readWorkspaceFile(params: WorkspaceFileParams): Promise<ReadWorkspaceFileResult>;
|
|
191
202
|
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
192
207
|
export declare function getWorkspaceEntryProperties(params: DeleteWorkspaceEntryParams): Promise<WorkspaceEntryPropertiesResult>;
|
|
193
208
|
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
|
|
194
212
|
export declare function chmodWorkspaceEntry(params: ChmodWorkspaceEntryParams): Promise<ChmodWorkspaceEntryResult>;
|
|
195
213
|
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
196
219
|
export declare function previewWorkspaceDocument(params: WorkspaceFileParams): Promise<WorkspaceDocumentPreviewResult>;
|
|
197
220
|
|
|
221
|
+
|
|
222
|
+
|
|
198
223
|
export declare function writeWorkspaceFile(params: WriteWorkspaceFileParams): Promise<{
|
|
199
224
|
ok: true;
|
|
200
225
|
workspacePath: string;
|
|
@@ -202,6 +227,8 @@ export declare function writeWorkspaceFile(params: WriteWorkspaceFileParams): Pr
|
|
|
202
227
|
mtimeMs: number;
|
|
203
228
|
}>;
|
|
204
229
|
|
|
230
|
+
|
|
231
|
+
|
|
205
232
|
export declare function createWorkspaceEntry(params: CreateWorkspaceEntryParams): Promise<{
|
|
206
233
|
ok: true;
|
|
207
234
|
workspacePath: string;
|
|
@@ -209,6 +236,8 @@ export declare function createWorkspaceEntry(params: CreateWorkspaceEntryParams)
|
|
|
209
236
|
isDirectory: boolean;
|
|
210
237
|
}>;
|
|
211
238
|
|
|
239
|
+
|
|
240
|
+
|
|
212
241
|
export declare function renameWorkspaceEntry(params: RenameWorkspaceEntryParams): Promise<{
|
|
213
242
|
ok: true;
|
|
214
243
|
workspacePath: string;
|
|
@@ -216,6 +245,8 @@ export declare function renameWorkspaceEntry(params: RenameWorkspaceEntryParams)
|
|
|
216
245
|
targetPath: string;
|
|
217
246
|
}>;
|
|
218
247
|
|
|
248
|
+
|
|
249
|
+
|
|
219
250
|
export declare function moveWorkspaceEntry(params: MoveWorkspaceEntryParams): Promise<{
|
|
220
251
|
ok: true;
|
|
221
252
|
workspacePath: string;
|
|
@@ -224,12 +255,16 @@ export declare function moveWorkspaceEntry(params: MoveWorkspaceEntryParams): Pr
|
|
|
224
255
|
destinationPath: string;
|
|
225
256
|
}>;
|
|
226
257
|
|
|
258
|
+
|
|
259
|
+
|
|
227
260
|
export declare function deleteWorkspaceEntry(params: DeleteWorkspaceEntryParams): Promise<{
|
|
228
261
|
ok: true;
|
|
229
262
|
workspacePath: string;
|
|
230
263
|
targetPath: string;
|
|
231
264
|
}>;
|
|
232
265
|
|
|
266
|
+
|
|
267
|
+
|
|
233
268
|
export declare function uploadWorkspaceFiles(params: UploadWorkspaceFilesParams): Promise<{
|
|
234
269
|
ok: true;
|
|
235
270
|
workspacePath: string;
|
|
@@ -242,17 +277,46 @@ export declare function uploadWorkspaceFiles(params: UploadWorkspaceFilesParams)
|
|
|
242
277
|
}>;
|
|
243
278
|
}>;
|
|
244
279
|
|
|
280
|
+
|
|
281
|
+
|
|
245
282
|
export declare function resolveWorkspaceDownloadTarget(params: DownloadWorkspaceEntryParams): Promise<WorkspaceDownloadTarget>;
|
|
246
283
|
|
|
284
|
+
|
|
285
|
+
|
|
247
286
|
export declare function streamWorkspaceDirectoryZip(directoryPath: string, output: NodeJS.WritableStream): Promise<void>;
|
|
248
287
|
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
|
|
249
299
|
export declare function zipWorkspaceDirectoryToTemp(directoryPath: string, zipName: string, onProgress?: (zippedBytes: number) => void, shouldCancel?: () => boolean): Promise<string>;
|
|
250
300
|
|
|
301
|
+
|
|
302
|
+
|
|
251
303
|
export declare function extractWorkspaceArchive(params: ExtractWorkspaceArchiveParams): Promise<WorkspaceArchiveExtractResult>;
|
|
252
304
|
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
|
|
253
308
|
export declare function searchWorkspaceFiles(params: SearchWorkspaceFilesParams): Promise<SearchWorkspaceFilesResult>;
|
|
254
309
|
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
|
|
255
316
|
export declare function searchWorkspacePaths(params: SearchWorkspacePathsParams): Promise<SearchWorkspacePathsResult>;
|
|
256
317
|
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
|
|
257
321
|
export declare function replaceWorkspaceFiles(params: ReplaceWorkspaceFilesParams): Promise<ReplaceWorkspaceFilesResult>;
|
|
258
322
|
export {};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import { type IndexQueryResult } from "./query.js";
|
|
12
|
+
import type { IndexBuildOptions, WorkspaceIndexSnapshot } from "./types.js";
|
|
13
|
+
export interface IndexStatus {
|
|
14
|
+
workspacePath: string;
|
|
15
|
+
ready: boolean;
|
|
16
|
+
building: boolean;
|
|
17
|
+
builtAt: number | null;
|
|
18
|
+
truncated: boolean;
|
|
19
|
+
stats: WorkspaceIndexSnapshot["stats"] | null;
|
|
20
|
+
error: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
export declare function ensureIndex(workspacePath: string, options?: IndexBuildOptions): Promise<WorkspaceIndexSnapshot>;
|
|
27
|
+
|
|
28
|
+
export declare function getIndexSnapshot(workspacePath: string): WorkspaceIndexSnapshot | null;
|
|
29
|
+
|
|
30
|
+
export declare function getIndexStatus(workspacePath: string): IndexStatus;
|
|
31
|
+
|
|
32
|
+
export declare function isIndexStale(workspacePath: string): boolean;
|
|
33
|
+
|
|
34
|
+
export declare function refreshIndexInBackground(workspacePath: string): void;
|
|
35
|
+
|
|
36
|
+
export declare function dropIndex(workspacePath: string): void;
|
|
37
|
+
|
|
38
|
+
export declare function runIndexQuery(workspacePath: string, params: {
|
|
39
|
+
kind: "definition" | "references" | "symbols" | "outline";
|
|
40
|
+
filePath?: string;
|
|
41
|
+
line?: number;
|
|
42
|
+
column?: number;
|
|
43
|
+
name?: string;
|
|
44
|
+
includeDeclaration?: boolean;
|
|
45
|
+
limit?: number;
|
|
46
|
+
}): Promise<IndexQueryResult>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import y from"node:crypto";import{existsSync as g,promises as d}from"node:fs";import u from"node:path";import{getBridgeDataHome as k}from"../../config.js";import{createLogger as b}from"../../utils/logger.js";import{buildWorkspaceIndex as x}from"./indexer.js";import{queryDefinition as P,queryOutline as S,queryReferences as C,querySymbols as I}from"./query.js";const c=b("workspace-index"),w=1,A=10*6e4,h=new Map;function N(){return u.join(k(),"workspace-index")}function m(t){const e=y.createHash("sha1").update(t).digest("hex").slice(0,16);return u.join(N(),`${e}.json`)}function l(t){return u.resolve(String(t||"").trim())}function f(t){const e=l(t);let n=h.get(e);return n||(n={workspacePath:e,snapshot:null,building:null,error:null,loadedFromCache:!1},h.set(e,n)),n}function v(t){return{version:w,workspacePath:t.workspacePath,builtAt:t.builtAt,truncated:t.truncated,stats:t.stats,files:[...t.files.values()]}}function $(t){const e=new Map,n=new Map,i=new Map;for(const r of t.files){e.set(r.filePath,r);for(const s of r.symbols){const o=s.name.trim().toLowerCase();if(!o)continue;const a=n.get(o);a?a.push(s):n.set(o,[s])}for(const s of r.identifierNames){const o=s.trim().toLowerCase();if(!o)continue;const a=i.get(o);a?a.add(r.filePath):i.set(o,new Set([r.filePath]))}}return{workspacePath:t.workspacePath,builtAt:t.builtAt,files:e,byName:n,filesByIdentifier:i,truncated:t.truncated,stats:t.stats}}async function F(t){const e=m(t);if(!g(e))return null;try{const n=await d.readFile(e,"utf8"),i=JSON.parse(n);return i.version!==w||l(i.workspacePath)!==l(t)?null:$(i)}catch(n){return c.warn(`[workspace-index] \u8BFB\u53D6\u7F13\u5B58\u5931\u8D25 ${e}: ${n.message}`),null}}async function D(t){const e=m(t.workspacePath);try{await d.mkdir(u.dirname(e),{recursive:!0}),await d.writeFile(e,JSON.stringify(v(t)),"utf8")}catch(n){c.warn(`[workspace-index] \u5199\u5165\u7F13\u5B58\u5931\u8D25 ${e}: ${n.message}`)}}async function p(t,e={}){const n=f(t);if(n.snapshot&&!e.force)return n.snapshot;if(n.building)return n.building;const i=(async()=>{if(!e.force){const r=await F(n.workspacePath);if(r)return c.info(`[workspace-index] \u547D\u4E2D\u78C1\u76D8\u7F13\u5B58 workspace=${n.workspacePath} files=${r.stats.fileCount}`),n.snapshot=r,n.loadedFromCache=!0,n.error=null,r}try{const r=await x(n.workspacePath,e);return n.snapshot=r,n.error=null,n.loadedFromCache=!1,D(r),r}catch(r){throw n.error=r.message,r}finally{n.building=null}})();return n.building=i,i}function M(t){return f(t).snapshot}function B(t){const e=f(t);return{workspacePath:e.workspacePath,ready:e.snapshot!==null,building:e.building!==null,builtAt:e.snapshot?.builtAt??null,truncated:e.snapshot?.truncated??!1,stats:e.snapshot?.stats??null,error:e.error}}function E(t){const e=M(t);return e?Date.now()-e.builtAt>A:!0}function J(t){f(t).building||p(t,{force:!0}).catch(n=>{c.warn(`[workspace-index] \u540E\u53F0\u5237\u65B0\u5931\u8D25: ${n.message}`)})}function R(t){h.delete(l(t))}async function T(t,e){const n=await p(t);return e.kind==="symbols"?I(n,String(e.name||""),e.limit??100):e.kind==="outline"?S(n,{filePath:String(e.filePath||"")}):e.kind==="references"?C(n,{filePath:String(e.filePath||""),line:Number(e.line||1),column:Number(e.column||1),name:e.name,includeDeclaration:e.includeDeclaration!==!1},e.limit??300):P(n,{filePath:String(e.filePath||""),line:Number(e.line||1),column:Number(e.column||1),name:e.name})}export{R as dropIndex,p as ensureIndex,M as getIndexSnapshot,B as getIndexStatus,E as isIndexStale,J as refreshIndexInBackground,T as runIndexQuery};
|
|
2
|
+
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{promises as k}from"node:fs";import g from"node:path";import{detectLanguage as v,extractFileIndex as C,getParserForLanguage as M}from"@agentswork/acode";import{createLogger as S}from"../../utils/logger.js";import{isIgnoredByGitIgnore as P,loadGitIgnoreRules as T}from"../gitignore.js";import{resolveImports as $}from"./resolver.js";import{DEFAULT_INDEX_OPTIONS as z,INDEX_SKIP_DIRS as L,INDEX_SUPPORTED_EXTENSIONS as _,symbolKey as B,toPosixPath as F}from"./types.js";const D=S("workspace-index"),A=4;async function R(i,n){const s=[];let e=0,r=!1,c=0,t=[];try{t=await T(i)}catch{}const y=[{dir:i,depth:0}];for(;y.length>0;){if(s.length>=n.maxFiles){r=!0;break}const l=y.shift();if(!l)break;if(l.depth>40){e+=1;continue}let h;try{h=await k.readdir(l.dir,{withFileTypes:!0})}catch{e+=1;continue}for(const u of h){const f=g.join(l.dir,u.name);if(u.isDirectory()){if(L.has(u.name))continue;const a=F(g.relative(i,f))+"/";if(P(a,!0,t))continue;y.push({dir:f,depth:l.depth+1});continue}if(!u.isFile())continue;const I=g.extname(u.name).toLowerCase();if(!_.has(I))continue;const d=F(g.relative(i,f));if(P(d,!1,t))continue;let m;try{m=await k.stat(f)}catch{e+=1;continue}if(m.size>n.maxFileBytes){e+=1;continue}if(c+=m.size,c>n.maxTotalBytes){r=!0;break}if(s.push(f),s.length>=n.maxFiles){r=!0;break}}}return{files:s,skipped:e,truncated:r}}async function O(i){const n=v(i);if(!n)return null;let s;try{s=await k.stat(i)}catch{return null}if(!s.isFile())return null;let e;try{e=await k.readFile(i,"utf8")}catch{return null}try{const r=await M(n);if(!r)return null;const c=r.parse(e);if(!c)return null;const t=C(c,n);return c.delete(),{index:t,mtimeMs:s.mtimeMs,size:s.size}}catch(r){return D.debug(`[workspace-index] \u89E3\u6790\u5931\u8D25 ${i}: ${r.message}`),null}}async function X(i,n,s){const e=new Array(i.length);let r=0;const c=Array.from({length:Math.min(n,i.length)},async()=>{for(;;){const t=r;if(r+=1,t>=i.length)return;e[t]=await s(i[t])}});return await Promise.all(c),e}async function H(i,n={}){const s=Date.now(),e=g.resolve(String(i||"").trim()),r={...z,...n.maxFiles!==void 0?{maxFiles:n.maxFiles}:{},...n.maxFileBytes!==void 0?{maxFileBytes:n.maxFileBytes}:{},...n.maxTotalBytes!==void 0?{maxTotalBytes:n.maxTotalBytes}:{}};let c;try{c=await k.stat(e)}catch{throw new Error(`workspace does not exist: ${e}`)}if(!c.isDirectory())throw new Error(`workspace is not a directory: ${e}`);const t=await R(e,r);D.info(`[workspace-index] \u626B\u63CF\u5B8C\u6210 workspace=${e} files=${t.files.length} skipped=${t.skipped} truncated=${t.truncated}`);const y=await X(t.files,A,O),l=new Map,h=new Map,u=new Map,f=new Map;let I=0;for(let d=0;d<t.files.length;d+=1){const m=t.files[d],a=y[d];if(!a)continue;const w=F(g.resolve(m)),E=F(g.relative(e,m)),N=a.index.symbols.map(o=>({name:o.name,kind:o.kind,filePath:w,line:o.line,column:o.column,endLine:o.endLine,endColumn:o.endColumn,signature:o.signature})),b={filePath:w,relativePath:E,language:a.index.language,mtimeMs:a.mtimeMs,size:a.size,symbols:N,imports:[],identifierNames:a.index.identifierNames,packageName:a.index.packageName};l.set(w,b),f.set(w,a.index),I+=N.length;for(const o of N){const p=B(o.name);if(!p)continue;const x=h.get(p);x?x.push(o):h.set(p,[o])}for(const o of a.index.identifierNames){const p=B(o);if(!p)continue;const x=u.get(p);x?x.add(w):u.set(p,new Set([w]))}}for(const[d,m]of l){const a=f.get(d);a&&(m.imports=$({workspaceRoot:F(e),filePath:d,language:a.language,packageName:a.packageName,rawImports:a.imports,files:l}))}return{workspacePath:e,builtAt:Date.now(),files:l,byName:h,filesByIdentifier:u,truncated:t.truncated,stats:{fileCount:l.size,symbolCount:I,skippedCount:t.skipped,durationMs:Date.now()-s}}}export{H as buildWorkspaceIndex};
|
|
2
|
+
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import { type WorkspaceIndexSnapshot } from "./types.js";
|
|
17
|
+
export interface IndexLocation {
|
|
18
|
+
|
|
19
|
+
filePath: string;
|
|
20
|
+
|
|
21
|
+
line: number;
|
|
22
|
+
|
|
23
|
+
column: number;
|
|
24
|
+
endLine: number;
|
|
25
|
+
endColumn: number;
|
|
26
|
+
|
|
27
|
+
name: string;
|
|
28
|
+
kind: string;
|
|
29
|
+
|
|
30
|
+
preview: string;
|
|
31
|
+
|
|
32
|
+
isDeclaration: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface IndexQueryResult {
|
|
35
|
+
ok: boolean;
|
|
36
|
+
provider: "syntax-index";
|
|
37
|
+
kind: "definition" | "references" | "symbols" | "outline";
|
|
38
|
+
|
|
39
|
+
symbol: string;
|
|
40
|
+
locations: IndexLocation[];
|
|
41
|
+
|
|
42
|
+
truncated: boolean;
|
|
43
|
+
|
|
44
|
+
indexed: boolean;
|
|
45
|
+
|
|
46
|
+
stats?: WorkspaceIndexSnapshot["stats"];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export declare function resolveSymbolAtPosition(filePath: string, line: number, column: number): Promise<string | null>;
|
|
50
|
+
|
|
51
|
+
export declare function querySymbols(snapshot: WorkspaceIndexSnapshot, name: string, limit?: number): IndexQueryResult;
|
|
52
|
+
|
|
53
|
+
export declare function queryDefinition(snapshot: WorkspaceIndexSnapshot, params: {
|
|
54
|
+
filePath: string;
|
|
55
|
+
line: number;
|
|
56
|
+
column: number;
|
|
57
|
+
name?: string;
|
|
58
|
+
}): Promise<IndexQueryResult>;
|
|
59
|
+
|
|
60
|
+
export declare function queryReferences(snapshot: WorkspaceIndexSnapshot, params: {
|
|
61
|
+
filePath: string;
|
|
62
|
+
line: number;
|
|
63
|
+
column: number;
|
|
64
|
+
name?: string;
|
|
65
|
+
includeDeclaration?: boolean;
|
|
66
|
+
}, limit?: number): Promise<IndexQueryResult>;
|
|
67
|
+
|
|
68
|
+
export declare function queryOutline(snapshot: WorkspaceIndexSnapshot, params: {
|
|
69
|
+
filePath: string;
|
|
70
|
+
}): Promise<IndexQueryResult>;
|
|
71
|
+
|
|
72
|
+
export declare function readLine(filePath: string, line: number): Promise<string>;
|
|
73
|
+
|
|
74
|
+
export declare function fillPreviews(snapshot: WorkspaceIndexSnapshot, locations: IndexLocation[]): Promise<IndexLocation[]>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{promises as p}from"node:fs";import m from"node:path";import{detectLanguage as b,findIdentifierOccurrences as I,getParserForLanguage as D,identifierAtPosition as M}from"@agentswork/acode";import{toPosixPath as x}from"./types.js";function C(e,t){if(e.filePath===t.currentFile)return 0;if(t.importedFiles.has(e.filePath))return 1;if(m.dirname(e.filePath)===t.currentDir)return 2;const r=t.files.get(e.filePath);return t.packageName&&r?.packageName===t.packageName?3:4}function N(e,t){return{filePath:x(e.filePath),line:e.line,column:e.column,endLine:e.endLine,endColumn:e.endColumn,name:e.name,kind:e.kind,preview:e.signature,isDeclaration:t}}function S(e,t){return x(m.relative(e.workspacePath,t))}function $(e,t){return{...t,filePath:S(e,t.filePath)}}function O(e,t){return m.resolve(e.workspacePath,t)}async function q(e,t,r){const i=b(e);if(!i)return null;let n;try{n=await p.readFile(e,"utf8")}catch{return null}const a=await D(i);if(!a)return null;const o=a.parse(n);if(!o)return null;try{const d=n.split(`
|
|
2
|
+
`);let f=0;for(let u=0;u<t-1&&u<d.length;u+=1)f+=d[u].length+1;return f+=Math.max(0,r-1),M(o,f,i)}finally{o.delete()}}function j(e,t,r=100){const i=t.trim().toLowerCase(),n=[];let a=!1;if(i)for(const o of e.byName.get(i)??[]){if(n.length>=r){a=!0;break}n.push($(e,N(o,!0)))}return{ok:!0,provider:"syntax-index",kind:"symbols",symbol:t,locations:n,truncated:a,indexed:!0,stats:e.stats}}async function G(e,t){const r=x(m.resolve(e.workspacePath,t.filePath)),i=t.name?.trim()||await q(r,t.line,t.column);if(!i)return{ok:!0,provider:"syntax-index",kind:"definition",symbol:"",locations:[],truncated:!1,indexed:!0,stats:e.stats};const n=e.files.get(r),a=new Set;for(const l of n?.imports??[])l.resolvedFile&&a.add(l.resolvedFile);const o={currentFile:r,currentDir:m.dirname(r),importedFiles:a,packageName:n?.packageName??null,files:e.files},d=e.byName.get(i.trim().toLowerCase())??[],f=[...d].sort((l,y)=>C(l,o)-C(y,o)),u=new Set,s=[];for(const l of f){const y=`${l.filePath}:${l.line}:${l.column}`;if(!u.has(y)&&(u.add(y),s.push($(e,N(l,!0))),s.length>=50))break}return{ok:!0,provider:"syntax-index",kind:"definition",symbol:i,locations:s,truncated:d.length>s.length,indexed:!0,stats:e.stats}}async function H(e,t,r=300){const i=x(m.resolve(e.workspacePath,t.filePath)),n=t.name?.trim()||await q(i,t.line,t.column);if(!n)return{ok:!0,provider:"syntax-index",kind:"references",symbol:"",locations:[],truncated:!1,indexed:!0,stats:e.stats};const a=n.trim().toLowerCase(),o=new Set(e.filesByIdentifier.get(a)??[]);o.add(i);const d=t.includeDeclaration!==!1,f=new Map;for(const c of e.byName.get(a)??[])f.set(`${c.filePath}:${c.line}:${c.column}`,c);const u=e.files.get(i),s=new Set;for(const c of u?.imports??[])c.resolvedFile&&s.add(c.resolvedFile);const l={currentFile:i,currentDir:m.dirname(i),importedFiles:s,packageName:u?.packageName??null,files:e.files},y=[...o].sort((c,k)=>{const h=c===l.currentFile?0:l.importedFiles.has(c)?1:m.dirname(c)===l.currentDir?2:4,v=k===l.currentFile?0:l.importedFiles.has(k)?1:m.dirname(k)===l.currentDir?2:4;return h-v}),w=[];let P=!1;for(const c of y){if(w.length>=r){P=!0;break}const k=b(c);if(!k)continue;let h;try{h=await p.readFile(c,"utf8")}catch{continue}const v=await D(k);if(!v)continue;const L=v.parse(h);if(L)try{const A=I(L,k,n,r);for(const g of A){const B=`${c}:${g.line}:${g.column}`,F=f.get(B);if(!(F&&!d)&&(w.push({filePath:S(e,c),line:g.line,column:g.column,endLine:g.line,endColumn:g.column+n.length,name:F?.name??n,kind:F?.kind??"reference",preview:g.context,isDeclaration:!!F}),w.length>=r)){P=!0;break}}}finally{L.delete()}}return{ok:!0,provider:"syntax-index",kind:"references",symbol:n,locations:w,truncated:P,indexed:!0,stats:e.stats}}async function J(e,t){const r=x(m.resolve(e.workspacePath,t.filePath)),i=e.files.get(r);if(!i){const n=b(r);if(!n)return{ok:!0,provider:"syntax-index",kind:"outline",symbol:"",locations:[],truncated:!1,indexed:!0,stats:e.stats};try{const a=await p.readFile(r,"utf8"),o=await D(n),d=o?.parse(a);if(o&&d){const{extractFileIndex:f}=await import("@agentswork/acode"),u=f(d,n);return d.delete(),{ok:!0,provider:"syntax-index",kind:"outline",symbol:"",locations:u.symbols.map(s=>({filePath:x(t.filePath),line:s.line,column:s.column,endLine:s.endLine,endColumn:s.endColumn,name:s.name,kind:s.kind,preview:s.signature,isDeclaration:!0})),truncated:!1,indexed:!0,stats:e.stats}}}catch{}return{ok:!0,provider:"syntax-index",kind:"outline",symbol:"",locations:[],truncated:!1,indexed:!0,stats:e.stats}}return{ok:!0,provider:"syntax-index",kind:"outline",symbol:"",locations:i.symbols.map(n=>$(e,N(n,!0))),truncated:!1,indexed:!0,stats:e.stats}}async function Q(e,t){try{return((await p.readFile(e,"utf8")).split(`
|
|
3
|
+
`)[t-1]??"").trim().slice(0,200)}catch{return""}}async function T(e,t){const r=new Map,i=[];for(const n of t){if(n.preview){i.push(n);continue}const a=O(e,n.filePath);let o=r.get(a);if(!o){try{o=(await p.readFile(a,"utf8")).split(`
|
|
4
|
+
`)}catch{o=[]}r.set(a,o)}i.push({...n,preview:(o[n.line-1]??"").trim().slice(0,200)})}return i}export{T as fillPreviews,G as queryDefinition,J as queryOutline,H as queryReferences,j as querySymbols,Q as readLine,q as resolveSymbolAtPosition};
|
|
5
|
+
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
import { type IndexedFile, type IndexedImport } from "./types.js";
|
|
10
|
+
export interface ResolveImportsInput {
|
|
11
|
+
workspaceRoot: string;
|
|
12
|
+
filePath: string;
|
|
13
|
+
language: string;
|
|
14
|
+
packageName: string | null;
|
|
15
|
+
rawImports: Array<{
|
|
16
|
+
text: string;
|
|
17
|
+
line: number;
|
|
18
|
+
}>;
|
|
19
|
+
|
|
20
|
+
files: Map<string, IndexedFile>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
export declare function resolveImports(input: ResolveImportsInput): IndexedImport[];
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import a from"node:path";import{toPosixPath as k}from"./types.js";const b={typescript:[".ts",".tsx",".mts",".cts",".js",".jsx",".json"],javascript:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".json"],python:[".py",".pyi"],go:[".go"],rust:[".rs"],java:[".java"],c:[".c",".h"],cpp:[".cpp",".cc",".cxx",".hpp",".hxx",".h"],"c-sharp":[".cs"],ruby:[".rb"],php:[".php"],lua:[".lua"]};function $(t){return k(a.resolve(t))}function u(t,s){const i=$(s);if(t.has(i))return i;const r=i.toLowerCase();for(const e of t.keys())if(e.toLowerCase()===r)return e;return null}function j(t,s,i,r){const e=a.dirname(t),o=a.resolve(e,s),c=b[i]??[],l=[o];for(const n of c)l.push(`${o}${n}`);for(const n of c)l.push(a.join(o,`index${n}`));for(const n of c)l.push(a.join(o,`mod${n}`));l.push(a.join(o,"__init__.py"));for(const n of l){const p=u(r,n);if(p)return p}return null}function N(t,s,i){const r=/\bfrom\s+['"]([^'"]+)['"]/.exec(s)??/\bimport\s+['"]([^'"]+)['"]/.exec(s);if(!r)return null;const e=r[1],o=[],c=/\{([^}]*)\}/.exec(s);if(c)for(const p of c[1].split(",")){const f=p.trim().split(/\s+as\s+/)[0]?.trim();f&&o.push(f)}const l=/^import\s+([A-Za-z_$][\w$]*)/.exec(s);l&&o.push(l[1]);const n=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(s);return n&&o.push(n[1]),e.startsWith(".")?{text:s,line:0,resolvedFile:j(t,e,"typescript",i),importedNames:o,moduleSpecifier:e}:{text:s,line:0,resolvedFile:null,importedNames:o,moduleSpecifier:e}}function S(t,s,i){const r=/^\s*from\s+([.\w]+)\s+import\s+(.+)$/.exec(s);if(r){const o=r[1],c=r[2].replace(/[()]/g,"").split(",").map(n=>n.trim().split(/\s+as\s+/)[0]?.trim()).filter(Boolean);let l=null;if(o.startsWith(".")){const n=/^\.+/.exec(o)?.[0].length??1,p=o.slice(n).replace(/\./g,"/");let f=a.dirname(t);for(let d=1;d<n;d+=1)f=a.dirname(f);const m=a.join(f,p);l=u(i,`${m}.py`)??u(i,a.join(m,"__init__.py"))}else{const p=o.split(".").join("/");for(const f of i.keys())if(f.endsWith(`/${p}.py`)||f.endsWith(`/${p}/__init__.py`)){l=f;break}}return{text:s,line:0,resolvedFile:l,importedNames:c,moduleSpecifier:o}}const e=/^\s*import\s+(.+)$/.exec(s);if(e){const o=e[1].split(",")[0]?.trim().split(/\s+as\s+/)[0]?.trim();if(!o)return null;const c=o.replace(/\./g,"/");let l=null;for(const n of i.keys())if(n.endsWith(`/${c}.py`)||n.endsWith(`/${c}/__init__.py`)){l=n;break}return{text:s,line:0,resolvedFile:l,importedNames:[o.split(".").pop()??o],moduleSpecifier:o}}return null}function F(t,s,i){const r=/^\s*import\s+(static\s+)?([\w.]+)(?:\.\*)?\s*;/.exec(s);if(!r)return null;const e=!!r[1],o=r[2],c=o.split("."),l=c[c.length-1],n=c.join("/"),p=e?[`${n}.java`,`${c.slice(0,-1).join("/")}.java`]:[`${n}.java`];for(const f of p)for(const m of i.keys())if(m.endsWith(`/${f}`))return{text:s,line:0,resolvedFile:m,importedNames:[l],moduleSpecifier:o};return{text:s,line:0,resolvedFile:null,importedNames:[l],moduleSpecifier:o}}function g(t,s,i){const r=/"([^"]+)"/.exec(s);if(!r)return null;const e=r[1],o=e.split("/").pop()??e;let c=null;for(const l of i.keys())if(!l.endsWith(`/${e}/`)&&(l.includes(`/${e}/`)||l.endsWith(`/${o}/${o}.go`))){c=l;break}return{text:s,line:0,resolvedFile:c,importedNames:o?[o]:[],moduleSpecifier:e}}function x(t,s,i){const r=/^\s*use\s+([^;]+);/.exec(s);if(!r)return null;const e=r[1].trim(),o=e.startsWith("crate::")||e.startsWith("self::")||e.startsWith("super::"),c=[],l=/\{([^}]*)\}/.exec(e);if(l)for(const p of l[1].split(",")){const f=p.trim().split(/\s+as\s+/)[0]?.trim();f&&f!=="self"&&c.push(f.split("::").pop()??f)}else c.push(e.split("::").pop()??e);let n=null;if(o){const p=a.dirname(t),f=e.replace(/^(crate|self|super)::/,"").replace(/\{.*$/,"").split("::").filter(Boolean);for(let m=f.length;m>0;m-=1){const d=f.slice(0,m).join("/"),v=[a.join(p,`${d}.rs`),a.join(p,d,"mod.rs")];for(const y of v){const h=u(i,y);if(h){n=h;break}}if(n)break}}return{text:s,line:0,resolvedFile:n,importedNames:c,moduleSpecifier:e}}function _(t,s,i){const r=/#\s*include\s*[<"]([^>"]+)[>"]/.exec(s);if(!r)return null;const e=r[1],o=a.dirname(t),c=[a.resolve(o,e),a.resolve(o,"..",e)];for(const l of c){const n=u(i,l);if(n)return{text:s,line:0,resolvedFile:n,importedNames:[],moduleSpecifier:e}}for(const l of i.keys())if(l.endsWith(`/${e}`))return{text:s,line:0,resolvedFile:l,importedNames:[],moduleSpecifier:e};return{text:s,line:0,resolvedFile:null,importedNames:[],moduleSpecifier:e}}function P(t){const s=/^\s*using\s+(?:static\s+)?([\w.]+)\s*;/.exec(t);if(!s)return null;const i=s[1],r=[i.split(".").pop()??i];return{text:t,line:0,resolvedFile:null,importedNames:r,moduleSpecifier:i}}function W(t,s,i){const r=/^\s*require(?:_relative)?\s+['"]([^'"]+)['"]/.exec(s);if(!r)return null;const e=r[1],o=a.dirname(t),c=[a.resolve(o,`${e}.rb`),a.resolve(o,e),a.resolve(o,`${e}.rb`)];for(const l of c){const n=u(i,l);if(n)return{text:s,line:0,resolvedFile:n,importedNames:[],moduleSpecifier:e}}for(const l of i.keys())if(l.endsWith(`/${e}.rb`))return{text:s,line:0,resolvedFile:l,importedNames:[],moduleSpecifier:e};return{text:s,line:0,resolvedFile:null,importedNames:[],moduleSpecifier:e}}function I(t,s,i){const r=/^\s*use\s+([\w\\]+)(?:\s+as\s+(\w+))?\s*;/.exec(s);if(!r)return null;const e=r[1].replace(/\\/g,"."),o=e.split("."),c=r[2]||o[o.length-1],l=o.join("/");for(const n of i.keys())if(n.endsWith(`/${l}.php`))return{text:s,line:0,resolvedFile:n,importedNames:[c],moduleSpecifier:e};return{text:s,line:0,resolvedFile:null,importedNames:[c],moduleSpecifier:e}}function w(t,s,i){const r=/require\s*\(?\s*['"]([^'"]+)['"]/.exec(s);if(!r)return null;const e=r[1],o=a.dirname(t),c=e.replace(/\./g,"/"),l=[a.resolve(o,`${c}.lua`),a.resolve(o,`${e}.lua`)];for(const n of l){const p=u(i,n);if(p)return{text:s,line:0,resolvedFile:p,importedNames:[],moduleSpecifier:e}}for(const n of i.keys())if(n.endsWith(`/${c}.lua`))return{text:s,line:0,resolvedFile:n,importedNames:[],moduleSpecifier:e};return{text:s,line:0,resolvedFile:null,importedNames:[],moduleSpecifier:e}}function L(t){const s=[];for(const i of t.rawImports){let r=null;switch(t.language){case"typescript":case"tsx":case"javascript":case"jsx":r=N(t.filePath,i.text,t.files);break;case"python":r=S(t.filePath,i.text,t.files);break;case"java":r=F(t.filePath,i.text,t.files);break;case"go":r=g(t.filePath,i.text,t.files);break;case"rust":r=x(t.filePath,i.text,t.files);break;case"c":case"cpp":r=_(t.filePath,i.text,t.files);break;case"c-sharp":r=P(i.text);break;case"ruby":r=W(t.filePath,i.text,t.files);break;case"php":r=I(t.filePath,i.text,t.files);break;case"lua":r=w(t.filePath,i.text,t.files);break;default:r=null}r&&s.push({...r,line:i.line})}return s}export{L as resolveImports};
|
|
2
|
+
|