@jayyuen66/dsh-scrapling 0.1.4 → 0.1.5

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/host.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // GENERATED by build-host.ts — edit host.ts / lib/*.ts, then run `node build-host.ts`.
2
2
  "use strict";
3
- import{access,chmod,cp,mkdir,open,readFile,readdir,rename,rm,rmdir,stat,writeFile}from"node:fs/promises";import os,{networkInterfaces}from"node:os";import path from"node:path";import Schema from"@deepseek-ai/schemastery";import{accessSync,constants,existsSync,readFileSync}from"node:fs";import{Remote,TypertRemoteService}from"@deepseek-ai/dsh-typert-protocol";import{createHash,randomUUID}from"node:crypto";import{spawn}from"node:child_process";import ipaddr from"ipaddr.js";import{WebError}from"@deepseek-ai/dsh-web";import{TextRetainer,formatRetentionNotice}from"@deepseek-ai/dsh-output-retention";import{createServer}from"node:http";import{defineTool}from"@deepseek-ai/dsh-tools";import{setTimeout as setTimeout$1}from"node:timers/promises";function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const t={absent:!0};function n(e,n){try{return{absent:!1,value:e[n]}}catch{return t}}function i(r,i){let a=e(r)?n(r,i):t;return a.absent?void 0:a.value}const FRAME_ERROR_KINDS={unparsableJson:`unparsable-json`,notAnObject:`not-an-object`,frameTooLarge:`frame-too-large`};var FrameError=class extends Error{kind;constructor(kind,message,options){super(message,options),this.name=`FrameError`,this.kind=kind}};function encodeFrame(value){let encoded;try{encoded=JSON.stringify(value)}catch(error){throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not JSON-serialisable`,{cause:error})}if(encoded===void 0)throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not JSON-serialisable`);return encoded}function decodeFrame(line){let parsed;try{parsed=JSON.parse(line)}catch(error){throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not valid JSON: ${line.slice(0,120)}`,{cause:error})}if(!e(parsed))throw new FrameError(FRAME_ERROR_KINDS.notAnObject,`frame must be a JSON object: ${line.slice(0,120)}`);return parsed}const MAX_FRAME_BYTES=8388608;var FrameSplitter=class{#buffer=``;push(chunk){this.#buffer+=chunk;let lines=[],newlineAt=this.#buffer.indexOf(`
3
+ import{access,chmod,cp,mkdir,open,readFile,readdir,rename,rm,rmdir,stat,writeFile}from"node:fs/promises";import os,{networkInterfaces}from"node:os";import path from"node:path";import Schema from"@deepseek-ai/schemastery";import{z}from"zod";import{accessSync,constants,existsSync,readFileSync}from"node:fs";import{Remote,TypertRemoteService}from"@deepseek-ai/dsh-typert-protocol";import{createHash,randomUUID}from"node:crypto";import{spawn}from"node:child_process";import ipaddr from"ipaddr.js";import{WebError}from"@deepseek-ai/dsh-web";import{TextRetainer,formatRetentionNotice}from"@deepseek-ai/dsh-output-retention";import{createServer}from"node:http";import{defineTool}from"@deepseek-ai/dsh-tools";import{setTimeout as setTimeout$1}from"node:timers/promises";function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const t={absent:!0};function n(e,n){try{return{absent:!1,value:e[n]}}catch{return t}}function i(r,i){let a=e(r)?n(r,i):t;return a.absent?void 0:a.value}const FRAME_ERROR_KINDS={unparsableJson:`unparsable-json`,notAnObject:`not-an-object`,frameTooLarge:`frame-too-large`};var FrameError=class extends Error{kind;constructor(kind,message,options){super(message,options),this.name=`FrameError`,this.kind=kind}};function encodeFrame(value){let encoded;try{encoded=JSON.stringify(value)}catch(error){throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not JSON-serialisable`,{cause:error})}if(encoded===void 0)throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not JSON-serialisable`);return encoded}function decodeFrame(line){let parsed;try{parsed=JSON.parse(line)}catch(error){throw new FrameError(FRAME_ERROR_KINDS.unparsableJson,`frame is not valid JSON: ${line.slice(0,120)}`,{cause:error})}if(!e(parsed))throw new FrameError(FRAME_ERROR_KINDS.notAnObject,`frame must be a JSON object: ${line.slice(0,120)}`);return parsed}const MAX_FRAME_BYTES=8388608;var FrameSplitter=class{#buffer=``;push(chunk){this.#buffer+=chunk;let lines=[],newlineAt=this.#buffer.indexOf(`
4
4
  `);for(;newlineAt>=0;){let line=this.#buffer.slice(0,newlineAt);this.#buffer=this.#buffer.slice(newlineAt+1),line.trim().length>0&&lines.push(line),newlineAt=this.#buffer.indexOf(`
5
5
  `)}if(this.#buffer.length>MAX_FRAME_BYTES)throw this.#buffer=``,new FrameError(FRAME_ERROR_KINDS.frameTooLarge,`a frame went over ${MAX_FRAME_BYTES} bytes without a newline`);return lines}flush(){let rest=this.#buffer.trim();return this.#buffer=``,rest.length>0?[rest]:[]}};function pumpFrames(stream,onFrame,onError=()=>void 0){let splitter=new FrameSplitter,state={stopped:!1},report=error=>{try{onError(error)}catch{}},handle=chunk=>{
6
6
  /* v8 ignore next 3 */
@@ -9,17 +9,15 @@ if(state.stopped)return;
9
9
  let text=typeof chunk==`string`?chunk:chunk.toString(`utf8`);try{for(let line of splitter.push(text)){if(state.stopped)return;onFrame(line)}}catch(error){report(error)}};return stream.setEncoding(`utf8`),stream.on(`data`,handle),stream.on(`end`,()=>{try{for(let line of splitter.flush())state.stopped||onFrame(line)}catch(error){report(error)}}),stream.on(`error`,error=>{report(error)}),()=>{state.stopped=!0,stream.off(`data`,handle)}}var SidecarError=class extends Error{code;details;constructor(code,message,options,details={}){super(message,options),this.name=`SidecarError`,this.code=code,this.details=details}};function asText(value,fallback){return typeof value==`string`?value.trim().length>0?value:fallback:typeof value==`number`||typeof value==`boolean`||typeof value==`bigint`?String(value):fallback}
10
10
  /* v8 ignore next 4 —— 占位实现本身永远不会被调用:构造对象时需要它满足类型,
11
11
  紧接着就被真正的回调改写掉。 */
12
- function noop(){}function parseProxySummary(value){if(!e(value))return null;let{configured,source,server}=value;return typeof configured==`boolean`&&typeof source==`string`&&typeof server==`string`?{configured,source,server}:null}function parseCapabilities(value){let record=e(value)?value:{},flag=key=>record[key]===!0,{version,proxy,websocketGuard}=record,summary=parseProxySummary(proxy);return{scrapling:flag(`scrapling`),static:flag(`static`),extract:flag(`extract`),browser:flag(`browser`),writeMethods:flag(`writeMethods`),...typeof websocketGuard==`boolean`?{websocketGuard}:{},...typeof version==`string`?{version}:{},...summary===null?{}:{proxy:summary}}}const BASE_ONLY_METHODS=/* @__PURE__ */ new Set([`select`,`locate`,`links`]);async function gateRequestUrls(params,gate,method){let one=async(target,key)=>{let value=Reflect.get(target,key);if(typeof value!=`string`||value.length===0)return target;let normalized=await gate(value);return typeof normalized!=`string`||normalized===value?target:{...target,[key]:normalized}};return one(await one(BASE_ONLY_METHODS.has(method)?params:await one(params,`url`),`sitemapUrl`),`feedUrl`)}var SidecarClient=class SidecarClient{#ctx;#options;#pending=/* @__PURE__ */ new Map;#readyWaiters=[];#handle;#stopPump;#capabilities;#starting;#stopped=!1;#nextId=0;constructor(ctx,options){this.#ctx=ctx,this.#options=options}get capabilities(){return this.#capabilities}get alive(){return this.#handle!==void 0&&this.#capabilities!==void 0&&!this.#stopped}#log(line){this.#options.log?.(line)}#rejectAll(error){let entries=Array.from(this.#pending.values());for(let entry of entries)SidecarClient.#settle(entry,error);for(this.#pending.clear();this.#readyWaiters.length>0;)this.#readyWaiters.shift()?.reject(error)}static#settle(entry,error){entry.timer!==void 0&&(clearTimeout(entry.timer),entry.timer=void 0),entry.detachAbort?.(),entry.detachAbort=void 0,entry.reject(error)}#routeResponse(frame){let rawId=frame.id;if(typeof rawId!=`string`){this.#log(`[sidecar] response frame without id`);return}let entry=this.#pending.get(rawId);if(entry===void 0){this.#log(`[sidecar] response for unknown id ${rawId}`);return}if(this.#pending.delete(rawId),entry.timer!==void 0&&(clearTimeout(entry.timer),entry.timer=void 0),entry.detachAbort?.(),entry.detachAbort=void 0,frame.ok===!0){entry.resolve(frame.result);return}let rawError=frame.error,message=e(rawError)?rawError.message:void 0,code=e(rawError)&&typeof rawError.code==`string`?rawError.code:`SIDECAR_REQUEST_FAILED`,details=e(rawError)&&e(rawError.details)?rawError.details:void 0;entry.reject(new SidecarError(code,asText(message,`unknown sidecar error`),void 0,details))}#onFrame(line){let frame;try{frame=decodeFrame(line)}catch(error){this.#log(`[sidecar] unparsable frame: ${String(error)}`);return}if(frame.event===`ready`)this.#readyWaiters.shift()?.resolve(frame);else if(typeof frame.event==`string`)try{this.#options.onEvent?.(frame)}catch(error){this.#log(`[sidecar] onEvent handler threw: ${String(error)}`)}else this.#routeResponse(frame)}async#teardown(reason,code,origin){if(origin!==void 0&&this.#handle!==origin){this.#log(`[sidecar] ignoring stale teardown: ${reason}`);return}this.#log(`[sidecar] teardown: ${reason}`),this.#stopPump?.(),this.#stopPump=void 0;let child=this.#handle;if(this.#handle=void 0,this.#capabilities=void 0,this.#starting=void 0,this.#rejectAll(new SidecarError(code,reason)),child!==void 0)try{child.terminate(),await child.waitForExit()}catch(error){this.#log(`[sidecar] terminate failed: ${String(error)}`)}}async#waitForReady(timeoutMs){return new Promise((resolve,reject)=>{let waiter={resolve:noop,reject:noop},timer=setTimeout(()=>{let index=this.#readyWaiters.indexOf(waiter);
12
+ function noop(){}const PROXY_SUMMARY_SCHEMA=z.object({configured:z.boolean(),source:z.string(),server:z.string()}),CAPABILITIES_SCHEMA=z.object({scrapling:z.preprocess(value=>value===!0,z.boolean()),static:z.preprocess(value=>value===!0,z.boolean()),extract:z.preprocess(value=>value===!0,z.boolean()),browser:z.preprocess(value=>value===!0,z.boolean()),writeMethods:z.preprocess(value=>value===!0,z.boolean()),websocketGuard:z.preprocess(value=>typeof value==`boolean`?value:void 0,z.boolean().optional()),version:z.preprocess(value=>typeof value==`string`?value:void 0,z.string().optional()),proxy:z.preprocess(value=>PROXY_SUMMARY_SCHEMA.safeParse(value).success?value:void 0,PROXY_SUMMARY_SCHEMA.optional())}),EMPTY_CAPABILITIES={scrapling:!1,static:!1,extract:!1,browser:!1,writeMethods:!1};function parseCapabilities(value){let parsed=CAPABILITIES_SCHEMA.safeParse(value);if(!parsed.success)return EMPTY_CAPABILITIES;let{scrapling,static:staticCapability,extract,browser,writeMethods,websocketGuard,version,proxy}=parsed.data;return{scrapling,static:staticCapability,extract,browser,writeMethods,...websocketGuard===void 0?{}:{websocketGuard},...version===void 0?{}:{version},...proxy===void 0?{}:{proxy}}}const BASE_ONLY_METHODS=/* @__PURE__ */ new Set([`select`,`locate`,`links`]);async function gateRequestUrls(params,gate,method){let one=async(target,key)=>{let value=Reflect.get(target,key);if(typeof value!=`string`||value.length===0)return target;let normalized=await gate(value);return typeof normalized!=`string`||normalized===value?target:{...target,[key]:normalized}};return one(await one(BASE_ONLY_METHODS.has(method)?params:await one(params,`url`),`sitemapUrl`),`feedUrl`)}var SidecarClient=class SidecarClient{#ctx;#options;#pending=/* @__PURE__ */ new Map;#readyWaiters=[];#handle;#stopPump;#capabilities;#starting;#stopped=!1;#nextId=0;constructor(ctx,options){this.#ctx=ctx,this.#options=options}get capabilities(){return this.#capabilities}get alive(){return this.#handle!==void 0&&this.#capabilities!==void 0&&!this.#stopped}#log(line){this.#options.log?.(line)}#rejectAll(error){let entries=Array.from(this.#pending.values());for(let entry of entries)SidecarClient.#settle(entry,error);for(this.#pending.clear();this.#readyWaiters.length>0;)this.#readyWaiters.shift()?.reject(error)}static#settle(entry,error){entry.timer!==void 0&&(clearTimeout(entry.timer),entry.timer=void 0),entry.detachAbort?.(),entry.detachAbort=void 0,entry.reject(error)}#routeResponse(frame){let rawId=frame.id;if(typeof rawId!=`string`){this.#log(`[sidecar] response frame without id`);return}let entry=this.#pending.get(rawId);if(entry===void 0){this.#log(`[sidecar] response for unknown id ${rawId}`);return}if(this.#pending.delete(rawId),entry.timer!==void 0&&(clearTimeout(entry.timer),entry.timer=void 0),entry.detachAbort?.(),entry.detachAbort=void 0,frame.ok===!0){entry.resolve(frame.result);return}let rawError=frame.error,message=e(rawError)?rawError.message:void 0,code=e(rawError)&&typeof rawError.code==`string`?rawError.code:`SIDECAR_REQUEST_FAILED`,details=e(rawError)&&e(rawError.details)?rawError.details:void 0;entry.reject(new SidecarError(code,asText(message,`unknown sidecar error`),void 0,details))}#onFrame(line){let frame;try{frame=decodeFrame(line)}catch(error){this.#log(`[sidecar] unparsable frame: ${String(error)}`);return}if(frame.event===`ready`)this.#readyWaiters.shift()?.resolve(frame);else if(typeof frame.event==`string`)try{this.#options.onEvent?.(frame)}catch(error){this.#log(`[sidecar] onEvent handler threw: ${String(error)}`)}else this.#routeResponse(frame)}async#teardown(reason,code,origin){if(origin!==void 0&&this.#handle!==origin){this.#log(`[sidecar] ignoring stale teardown: ${reason}`);return}this.#log(`[sidecar] teardown: ${reason}`),this.#stopPump?.(),this.#stopPump=void 0;let child=this.#handle;if(this.#handle=void 0,this.#capabilities=void 0,this.#starting=void 0,this.#rejectAll(new SidecarError(code,reason)),child!==void 0)try{child.terminate(),await child.waitForExit()}catch(error){this.#log(`[sidecar] terminate failed: ${String(error)}`)}}async#waitForReady(timeoutMs){return new Promise((resolve,reject)=>{let waiter={resolve:noop,reject:noop},timer=setTimeout(()=>{let index=this.#readyWaiters.indexOf(waiter);
13
13
  /* v8 ignore next 3 */
14
14
  index!==-1&&this.#readyWaiters.splice(index,1);let reason=`no ready frame within ${timeoutMs}ms`;(async()=>{await this.#teardown(reason,`SIDECAR_HANDSHAKE_FAILED`),reject(new SidecarError(`SIDECAR_HANDSHAKE_FAILED`,reason))})()},timeoutMs);waiter.resolve=frame=>{clearTimeout(timer),resolve(frame)},waiter.reject=error=>{clearTimeout(timer),reject(error)},this.#readyWaiters.push(waiter)})}async#spawnOnce(signal){let{subprocess}=this.#ctx,python=await subprocess.resolveExecutable(this.#options.pythonBin),child=subprocess.spawn({argv:[python,`-u`,`-I`,this.#options.bridgePath],cwd:this.#options.cwd,stdio:{stdin:`pipe`,stdout:`pipe`,stderr:`pipe`},graceMs:this.#options.graceMs,env:{PYTHONUNBUFFERED:`1`,...this.#options.env},...signal===void 0?{}:{signal}});this.#handle=child;let{stdin,stdout}=child;if(stdin===void 0||stdout===void 0)throw await this.#teardown(`sidecar stdio pipes were not created`,`SIDECAR_UNAVAILABLE`),new SidecarError(`SIDECAR_UNAVAILABLE`,`sidecar stdio pipes were not created`);if(this.#stopped)throw child.terminate(),await child.waitForExit(),this.#handle=void 0,new SidecarError(`SIDECAR_UNAVAILABLE`,`sidecar client has been disposed`);this.#stopPump=pumpFrames(stdout,line=>{this.#onFrame(line)},error=>{this.#teardown(`sidecar stream failed: ${String(error)}`,`SIDECAR_CRASHED`,child)}),child.stderr?.setEncoding(`utf8`),child.stderr?.on(`data`,chunk=>{for(let line of String(chunk).split(`
15
15
  `))line.trim().length>0&&this.#log(`[sidecar] ${line}`)}),child.stderr?.on(`error`,error=>{this.#teardown(`sidecar stderr failed: ${String(error)}`,`SIDECAR_CRASHED`,child)}),stdin.on(`error`,error=>{this.#teardown(`sidecar stdin failed: ${String(error)}`,`SIDECAR_CRASHED`,child)}),child.done.then(()=>this.#teardown(`sidecar exited`,`SIDECAR_CLOSED`,child),error=>this.#teardown(`sidecar exited: ${String(error)}`,`SIDECAR_CRASHED`,child));let ready=await this.#waitForReady(this.#options.handshakeTimeoutMs);if(ready.protocol!==1){let seen=asText(ready.protocol,`unknown`);throw await this.#teardown(`protocol mismatch`,`SIDECAR_PROTOCOL_MISMATCH`),new SidecarError(`SIDECAR_PROTOCOL_MISMATCH`,`sidecar speaks protocol ${seen}, host expects 1`)}return this.#capabilities=parseCapabilities(ready.capabilities),this.#capabilities}async ensureStarted(signal){if(this.#stopped)throw new SidecarError(`SIDECAR_UNAVAILABLE`,`sidecar client has been disposed`);if(this.#capabilities!==void 0)return this.#capabilities;let starting=this.#starting;starting===void 0&&(starting=this.#spawnOnce(signal),this.#starting=starting);try{return await starting}finally{this.#starting===starting&&(this.#starting=void 0)}}async call(method,params={},options={}){let gate=this.#options.urlGate,outgoing=gate===void 0?params:await gateRequestUrls(params,gate,method);await this.ensureStarted(options.signal);let stdin=this.#handle?.stdin;
16
16
  /* v8 ignore next 3 */
17
- if(stdin===void 0)throw new SidecarError(`SIDECAR_UNAVAILABLE`,`sidecar is not running`);this.#nextId+=1;let id=`h${this.#nextId}`,timeoutMs=options.timeoutMs===void 0?this.#options.requestTimeoutMs:options.timeoutMs,frame=`${encodeFrame({id,method,params:outgoing})}\n`,settled=new Promise((resolve,reject)=>{let entry={resolve,reject,timer:void 0,detachAbort:void 0};this.#pending.set(id,entry);let{signal}=options,failRequest=(code,message)=>{this.#pending.delete(id),SidecarClient.#settle(entry,new SidecarError(code,message))};if(timeoutMs!==null&&(entry.timer=setTimeout(()=>{this.#pending.delete(id),SidecarClient.#settle(entry,new SidecarError(`SIDECAR_TIMEOUT`,`${method} timed out after ${timeoutMs}ms`)),this.#teardown(`${method} timed out after ${timeoutMs}ms`,`SIDECAR_TIMEOUT`)},timeoutMs)),signal!==void 0){let onAbort=()=>{failRequest(`SIDECAR_ABORTED`,`${method} was aborted`)};signal.aborted?onAbort():(signal.addEventListener(`abort`,onAbort,{once:!0}),entry.detachAbort=()=>{signal.removeEventListener(`abort`,onAbort)})}});if(!this.#pending.has(id))return settled;if(stdin.destroyed)return this.#teardown(`failed to send ${method}: stdin is gone`,`SIDECAR_CRASHED`),settled;try{stdin.write(frame)}catch(error){this.#teardown(`failed to send ${method}: ${String(error)}`,`SIDECAR_CRASHED`)}return settled}async dispose(){if(this.#stopped)return;this.#stopped=!0;let child=this.#handle;if(child?.stdin!==void 0){try{child.stdin.write(`${encodeFrame({id:`dispose`,method:`shutdown`,params:{}})}\n`)}catch{}let exited=child.done.then(()=>!0,()=>!0),timer,grace=new Promise(resolve=>{timer=setTimeout(()=>{resolve(!1)},this.#options.graceMs)}),finished=await Promise.race([exited,grace]);if(clearTimeout(timer),finished){this.#stopPump?.(),this.#stopPump=void 0,this.#handle=void 0,this.#capabilities=void 0,this.#starting=void 0,this.#rejectAll(new SidecarError(`SIDECAR_CLOSED`,`client disposed`));return}}await this.#teardown(`client disposed`,`SIDECAR_CLOSED`)}};function createSidecar(ctx,options){return new SidecarClient(ctx,options)}function sidecarErrorWithCode(code,message,options,details={}){return new SidecarError(code,message.startsWith(`${code}: `)?message:`${code}: ${message}`,options,details)}async function callSidecar(client,method,params={},options={}){try{return await client.call(method,params,options)}catch(error){throw error instanceof SidecarError?sidecarErrorWithCode(error.code,error.message,{cause:error},error.details):error}}function isRecord(value){return typeof value==`object`&&!!value&&!Array.isArray(value)}function isAsset(value){return isRecord(value)&&typeof value.platform==`string`&&typeof value.arch==`string`&&typeof value.pythonVersion==`string`&&typeof value.release==`string`&&typeof value.url==`string`&&typeof value.sha256==`string`&&typeof value.sizeBytes==`number`}function isManifest(value){return isRecord(value)&&isAsset(value.darwinArm64)&&isRecord(value.unsupported)}
18
- /* v8 ignore next 1 */
19
- const packageRoot=existsSync(path.join(import.meta.dirname,`runtime-manifest.json`))?import.meta.dirname:path.resolve(import.meta.dirname,`..`);function parseRuntimeManifest(text){let parsed=JSON.parse(text);if(!isManifest(parsed))throw Error(`runtime-manifest.json is missing the darwinArm64 asset`);return parsed}const runtimeManifest=parseRuntimeManifest(readFileSync(path.join(packageRoot,`runtime-manifest.json`),`utf8`));function managedPythonPath(dataDir){return path.join(dataDir,`runtime`,`python`,runtimeManifest.darwinArm64.pythonVersion,`bin`,`python3`)}function executable(file){try{return accessSync(file,constants.X_OK),!0}catch{return!1}}function repoPythonPath(repoRoot){return process.platform===`win32`?path.join(repoRoot,`_env`,`.venv`,`Scripts`,`python.exe`):path.join(repoRoot,`_env`,`.venv`,`bin`,`python`)}function resolveRuntime(options){let explicit=options.pythonBin.trim();if(explicit.length>0)return{pythonPath:explicit,via:`configured`,version:`unknown`};if(process.platform===`darwin`&&process.arch===`arm64`&&options.dataDir.length>0){let managed=managedPythonPath(options.dataDir);if(executable(managed))return{pythonPath:managed,via:`managed`,version:runtimeManifest.darwinArm64.pythonVersion}}let repoPython=repoPythonPath(options.repoRoot);return executable(repoPython)?{pythonPath:repoPython,via:`repo`,version:`unknown`}:{pythonPath:process.platform===`win32`?`python.exe`:`python3`,via:`path`,version:`unknown`}}function isPlainRecord(value){return typeof value==`object`&&!!value&&!Array.isArray(value)}const STATE_FILE=`state.json`;function installerSupported(){return process.platform===`darwin`&&process.arch===`arm64`}const CHROMIUM_MARKERS=/* @__PURE__ */ new Set([`Chromium`,`chrome`,`chrome.exe`,`Google Chrome for Testing`]);var InstallError=class extends Error{code;constructor(code,message,options){super(message,options),this.name=`InstallError`,this.code=code}};async function run(argv,options={}){return new Promise(resolve=>{let child=spawn(argv[0]??``,argv.slice(1),{env:{...process.env,...options.env},stdio:[`ignore`,`pipe`,`pipe`]}),stdout=``,stderr=``;child.stdout.on(`data`,chunk=>{stdout+=chunk.toString(`utf8`)}),child.stderr.on(`data`,chunk=>{stderr+=chunk.toString(`utf8`)}),child.on(`error`,error=>{resolve({code:null,stdout,stderr:`${stderr}${String(error)}`})}),child.on(`close`,code=>{resolve({code,stdout,stderr})})})}function createCurlDownloader(runStep){return async url=>{let target=path.join(os.tmpdir(),`dsh-scrapling-dl-${randomUUID()}`),result=await runStep([`curl`,`--fail`,`--location`,`--silent`,`--show-error`,`--output`,target,url]);if(result.code===0)try{return new Uint8Array(await readFile(target))}finally{await rm(target,{force:!0})}if(await rm(target,{force:!0}),result.code!==null)throw new InstallError(`INSTALL_NETWORK`,`curl failed for ${url}: ${result.stderr.slice(0,400)}`);let response=await fetch(url);if(!response.ok)throw new InstallError(`INSTALL_NETWORK`,`${url} answered HTTP ${response.status}`);return new Uint8Array(await response.arrayBuffer())}}const defaultInstallerIO={download:createCurlDownloader(run),extract:async(archive,destination)=>{let result=await run([`tar`,`-xzf`,archive,`-C`,destination]);if(result.code!==0)throw new InstallError(`INSTALL_FAILED`,`tar failed: ${result.stderr.slice(0,400)}`)},spawn:run};async function exists(file){try{return await access(file,constants.F_OK),!0}catch{return!1}}async function readLockOwner(lockPath){let text=``;try{text=await readFile(lockPath,`utf8`)}catch{}let pid=Math.trunc(Number(text.trim().split(/\s+/u)[0]));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}async function lockHeldByLivingProcess(lockPath){let text,modifiedAt;try{let[content,stats]=await Promise.all([readFile(lockPath,`utf8`),stat(lockPath)]);text=content,modifiedAt=stats.mtimeMs}catch{return!0}let[pidText=``]=text.trim().split(/\s+/u),pid=Math.trunc(Number(pidText));if(Number.isSafeInteger(pid)&&pid>0){if(pid===process.pid)return!0;try{return process.kill(pid,0),!0}catch(error){return error.code===`EPERM`}}return Date.now()-modifiedAt<1e4}async function acquireLock(lockPath,openLock=open){try{return await openLock(lockPath,`wx`)}catch{if(await lockHeldByLivingProcess(lockPath))throw new InstallError(`INSTALL_BUSY`,`another install holds ${lockPath}`);await rm(lockPath,{force:!0});try{return await openLock(lockPath,`wx`)}catch{throw new InstallError(`INSTALL_BUSY`,`another install holds ${lockPath}`)}}}async function releaseLock(lockPath,handle){try{await handle.close()}catch{}if(await readLockOwner(lockPath)===process.pid)try{await rm(lockPath,{force:!0})}catch{}}const heldLockDepths=/* @__PURE__ */ new Map;function releaseLockDepth(key,held){held<=1?heldLockDepths.delete(key):heldLockDepths.set(key,held-1)}async function ensureRuntimeDir(dataDir){let runtimeDir=path.join(dataDir,`runtime`);return await mkdir(runtimeDir,{recursive:!0}),process.platform!==`win32`&&await chmod(runtimeDir,448),runtimeDir}async function withInstallLock(dataDir,work,openLock=open){let runtimeDir=path.join(dataDir,`runtime`),lockPath=path.join(runtimeDir,`install.lock`),key=path.resolve(lockPath),depth=heldLockDepths.get(key)??0;if(depth>0){heldLockDepths.set(key,depth+1);try{return await work()}finally{releaseLockDepth(key,depth+1)}}await ensureRuntimeDir(dataDir);let handle=await acquireLock(lockPath,openLock);heldLockDepths.set(key,1);try{return await handle.writeFile(`${process.pid} ${Date.now()}\n`),await work()}finally{releaseLockDepth(key,1),await releaseLock(lockPath,handle)}}async function offlineArchive(assets,url){let raw=path.basename(new URL(url).pathname),decoded=decodeURIComponent(raw),names=raw===decoded?[raw]:[decoded,raw],bytes=(await Promise.all(names.map(async name=>({name,bytes:await readFile(path.join(assets,name)).catch(()=>null)})))).find(item=>item.bytes!==null)?.bytes;if(bytes==null)throw new InstallError(`INSTALL_OFFLINE_ASSETS`,`offline python archive missing under ${assets}: expected ${names.join(` or `)}`);return new Uint8Array(bytes)}async function installPython(asset,dataDir,io,assets){return withInstallLock(dataDir,async()=>{let tmpRoot=path.join(dataDir,`runtime`,`.tmp`,randomUUID());await mkdir(tmpRoot,{recursive:!0});let archive=path.join(tmpRoot,`python.tar.gz`);try{let bytes=assets===void 0?await io.download(asset.url):await offlineArchive(assets,asset.url),digest=createHash(`sha256`).update(bytes).digest(`hex`);if(digest!==asset.sha256)throw new InstallError(`INSTALL_HASH_MISMATCH`,`python archive hash ${digest} does not match ${asset.sha256}`);await writeFile(archive,bytes);let extractDir=path.join(tmpRoot,`extract`);await mkdir(extractDir,{recursive:!0}),await io.extract(archive,extractDir);let layout=path.join(extractDir,`python`),source=await exists(path.join(layout,`bin`,`python3`))?layout:extractDir,target=path.dirname(path.dirname(managedPythonPath(dataDir)));await rm(target,{recursive:!0,force:!0}),await mkdir(path.dirname(target),{recursive:!0}),await cp(source,target,{recursive:!0,dereference:!0});let pythonPath=managedPythonPath(dataDir);if(!await exists(pythonPath))throw new InstallError(`INSTALL_FAILED`,`python archive did not contain bin/python3`);return{pythonPath,version:asset.pythonVersion}}finally{await rm(tmpRoot,{recursive:!0,force:!0}),await rmdir(path.join(dataDir,`runtime`,`.tmp`)).catch(()=>null)}})}async function readRuntimeState(dataDir){let statePath=path.join(dataDir,`runtime`,STATE_FILE),text;try{text=await readFile(statePath,`utf8`)}catch(error){if(error.code===`ENOENT`)return{packs:{}};throw new InstallError(`INSTALL_STATE_CORRUPT`,`cannot read ${statePath}: ${String(error)}; delete it and install again`,{cause:error})}let parsed;try{parsed=JSON.parse(text)}catch(error){throw new InstallError(`INSTALL_STATE_CORRUPT`,`${statePath} is not valid JSON; delete it and install again`,{cause:error})}if(!isPlainRecord(parsed))throw new InstallError(`INSTALL_STATE_CORRUPT`,`${statePath} does not hold a JSON object; delete it and install again`);return parsed}async function writeRuntimeState(dataDir,state){let runtimeDir=await ensureRuntimeDir(dataDir),target=path.join(runtimeDir,STATE_FILE),staging=`${target}.${randomUUID()}.tmp`;try{await writeFile(staging,JSON.stringify(state,null,2),`utf8`),await rename(staging,target)}finally{try{await rm(staging,{force:!0})}catch{}}}async function rewriteShebangs(scanDir,from,to,readScript=file=>readFile(file,`utf8`)){let binDir=path.join(scanDir,`bin`),stale=`#!${from}/`,files=(await readdir(binDir,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isFile()).map(entry=>path.join(binDir,entry.name));await Promise.all(files.map(async file=>{let text=await readScript(file).catch(()=>``),newline=text.indexOf(`
20
- `),head=newline===-1?text:text.slice(0,newline);if(!head.startsWith(stale))return;let tail=newline===-1?``:text.slice(newline);await writeFile(file,`#!${to}/${head.slice(stale.length)}${tail}`,`utf8`)}))}async function finishCoreInstall(paths,restore){if(restore){try{await rm(paths.venv,{recursive:!0,force:!0})}catch{}try{await rename(paths.previousVenv,paths.venv)}catch{}}try{await rm(paths.previousVenv,{recursive:!0,force:!0})}catch{}try{await rm(paths.staging,{recursive:!0,force:!0})}catch{}}async function installCore(options){let{io}=options;await withInstallLock(options.dataDir,async()=>{let runtimeDir=await ensureRuntimeDir(options.dataDir),venv=path.join(runtimeDir,`venv`),staging=path.join(runtimeDir,`.tmp`,`venv-${randomUUID()}`),previousVenv=path.join(runtimeDir,`.tmp`,`venv-previous-${randomUUID()}`),requirements=path.join(options.repoRoot,`py`,`runtime-requirements.txt`),movedAside=!1,committed=!1;try{let created=await io.spawn([options.pythonPath,`-m`,`venv`,staging]);if(created.code!==0)throw new InstallError(`INSTALL_FAILED`,`venv failed: ${created.stderr.slice(0,400)}`);let stagingPython=path.join(staging,`bin`,`python3`),offlineArgs=options.assets===void 0?[]:[`--no-index`,`--find-links`,path.join(options.assets,`wheels`)],installed=await io.spawn([stagingPython,`-m`,`pip`,`install`,`--only-binary=:all:`,`--require-hashes`,`-r`,requirements,...offlineArgs],{env:{PIP_DISABLE_PIP_VERSION_CHECK:`1`}});if(installed.code!==0){let text=`${installed.stdout}\n${installed.stderr}`;throw/No matching distribution|Could not find a version|no matching distribution/iu.test(text)?new InstallError(`INSTALL_NO_WHEEL`,`a dependency has no wheel for this platform`):/Network|Temporary failure|Connection|timed out/iu.test(text)?new InstallError(`INSTALL_NETWORK`,`pip could not reach the package index`):new InstallError(`INSTALL_FAILED`,`pip failed: ${installed.stderr.slice(0,400)}`)}await rewriteShebangs(staging,staging,venv);try{await exists(venv)&&(await rename(venv,previousVenv),movedAside=!0),await rename(staging,venv)}catch(error){throw new InstallError(`INSTALL_FAILED`,`cannot replace ${venv}: ${String(error)}`,{cause:error})}let previous=await readRuntimeState(options.dataDir),packs={...isPlainRecord(previous.packs)?previous.packs:{},core:`ready`};await writeRuntimeState(options.dataDir,{...previous,packs,python:options.pythonPath}),committed=!0}finally{await finishCoreInstall({venv,previousVenv,staging},movedAside&&!committed)}})}async function installBrowser(options){let{io}=options;return withInstallLock(options.dataDir,async()=>{let browsersPath=path.join(options.dataDir,`runtime`,`browsers`);await mkdir(browsersPath,{recursive:!0});let installed=await io.spawn([options.pythonPath,`-m`,`patchright`,`install`,`chromium`],{env:{PLAYWRIGHT_BROWSERS_PATH:browsersPath}});if(installed.code!==0)throw new InstallError(`INSTALL_BROWSER_FAILED`,`chromium install failed: ${installed.stderr.slice(0,400)}`);let hasBrowser;try{hasBrowser=(await readdir(browsersPath,{recursive:!0})).some(entry=>CHROMIUM_MARKERS.has(path.basename(entry)))}catch{hasBrowser=!1}if(!hasBrowser)throw new InstallError(`INSTALL_BROWSER_FAILED`,`no chromium executable found under ${browsersPath}`);let previous=await readRuntimeState(options.dataDir),packs={...isPlainRecord(previous.packs)?previous.packs:{},browser:`ready`};return await writeRuntimeState(options.dataDir,{...previous,packs,browsersPath}),{browsersPath}})}async function chromiumInstalled(dataDir){try{return(await readdir(path.join(dataDir,`runtime`,`browsers`),{recursive:!0})).some(entry=>CHROMIUM_MARKERS.has(path.basename(entry)))}catch{return!1}}function stateOf(marked,installed){return marked===`ready`?installed?`ready`:`corrupt`:`missing`}async function packStates(dataDir,installing){if(!installerSupported())return{core:`blocked`,browser:`blocked`,search:`blocked`,media:`blocked`,"adaptive-redis":`blocked`,mcp:`blocked`};let raw=(await readRuntimeState(dataDir)).packs,packs=isPlainRecord(raw)?raw:{},core=stateOf(packs.core,await exists(path.join(dataDir,`runtime`,`venv`,`bin`,`python3`))),result={core,browser:stateOf(packs.browser,await chromiumInstalled(dataDir)),search:core,media:core,"adaptive-redis":core,mcp:core};return installing!==void 0&&(result[installing]=`installing`),result}function throwIfAborted(signal){if(signal?.aborted===!0)throw new InstallError(`INSTALL_FAILED`,`install cancelled`)}async function ensurePython(dataDir,io,signal,asset,assets){let managed=managedPythonPath(dataDir);return await exists(managed)?managed:(throwIfAborted(signal),(await installPython(asset,dataDir,io,assets)).pythonPath)}async function installCapabilityPack(pack,options){if(!installerSupported())throw new InstallError(`INSTALL_PACK_BLOCKED`,`runtime packs are verified on macOS arm64 only; this host is ${process.platform}/${process.arch}`);let{dataDir,repoRoot,io,signal,onProgress,assets}=options,asset=options.asset??runtimeManifest.darwinArm64;if(assets!==void 0&&!await exists(path.join(assets,`wheels`)))throw new InstallError(`INSTALL_OFFLINE_ASSETS`,`offline wheelhouse missing: ${path.join(assets,`wheels`)}`);throwIfAborted(signal),onProgress?.(`installing ${pack}`);let pythonPath=await ensurePython(dataDir,io,signal,asset,assets);throwIfAborted(signal),onProgress?.(`installing core packages into ${pythonPath}`),await installCore({pythonPath,dataDir,repoRoot,io,...assets===void 0?{}:{assets}}),throwIfAborted(signal),pack===`browser`&&(onProgress?.(`installing full chromium`),await installBrowser({pythonPath:path.join(dataDir,`runtime`,`venv`,`bin`,`python3`),dataDir,io}),throwIfAborted(signal)),onProgress?.(`${pack} ready`)}const PACK_NAMES=/* @__PURE__ */ new Set([`core`,`browser`,`search`,`media`,`adaptive-redis`,`mcp`]);function isRuntimePack(value){return typeof value==`string`&&PACK_NAMES.has(value)}function refused$1(status,error){return{ok:!1,status,error}}function field(record,key){return record[key]}function isLive(status){return status===`running`||status===`stopping`}function outputOf(read){let text=read.chunks.map(chunk=>chunk.text).join(``);return text.length>4e3?text.slice(-4e3):text}var ScraplingRuntimeService=class extends TypertRemoteService{deps;job=null;constructor(ctx,deps){super(ctx,`scraplingRuntime`),this.deps=deps}jobView(jobs){if(this.job===null||jobs===void 0)return null;try{let view=jobs.get(this.job.id);return{id:String(this.job.id),pack:this.job.pack,status:view.status,output:outputOf(jobs.readAt(this.job.id,0))}}catch{return null}}liveJob(jobs){return this.job===null?null:isLive(jobs.get(this.job.id).status)?this.job:null}async status(){let jobs=this.deps.jobsOf(),job=this.jobView(jobs),installing=job!==null&&isLive(job.status)?job.pack:void 0,python=resolveRuntime({pythonBin:this.deps.pythonBin,dataDir:this.deps.dataDir,repoRoot:this.deps.repoRoot});return{ok:!0,packs:await packStates(this.deps.dataDir,installing),python:{path:python.pythonPath,via:python.via,version:python.version},dataDir:this.deps.dataDir,jobsReady:jobs!==void 0,job}}installPack(request){return this.start(request,`install`)}repairPack(request){return this.start(request,`repair`)}start(request,action){let record=e(request)?request:void 0,raw=record===void 0?void 0:field(record,`pack`);if(!isRuntimePack(raw))return refused$1(400,`pack must be one of core|browser|search|media|adaptive-redis|mcp`);let jobs=this.deps.jobsOf();if(jobs===void 0)return refused$1(503,`this profile has no jobs backend; run the CLI instead`);let running;try{running=this.liveJob(jobs)}catch(error){return refused$1(500,`cannot read the last install job: ${String(error)}`)}if(running!==null)return refused$1(409,`another install is running: ${String(running.id)}`);let pack=raw,controller=new AbortController,spec={kind:`scrapling-runtime`,label:`${action} ${pack}`,run:job=>{let progress=line=>{job.updateProgress(line),job.append(`${line}\n`,{channel:`log`})};return{cancel:()=>{controller.abort()},done:(async()=>{try{return await this.deps.installPackFn(pack,{dataDir:this.deps.dataDir,repoRoot:this.deps.repoRoot,io:this.deps.io,signal:controller.signal,onProgress:progress}),{status:`completed`}}catch(error){return controller.signal.aborted?{status:`killed`,detail:`cancelled from settings card`}:{status:`failed`,detail:String(error)}}})()}}},id;try{let detach=jobs.attachController(`scrapling: runtime`);try{id=jobs.start(spec)}finally{detach()}}catch(error){return refused$1(500,String(error))}return this.job={id,pack},{ok:!0,jobId:String(id)}}cancelJob(request){let record=e(request)?request:void 0,raw=record===void 0?void 0:field(record,`jobId`);if(typeof raw!=`string`||raw.length===0)return refused$1(400,`cancel requires a jobId`);if(this.job===null||String(this.job.id)!==raw)return refused$1(404,`unknown jobId: ${raw}`);let jobs=this.deps.jobsOf();if(jobs===void 0)return refused$1(503,`this profile has no jobs backend`);try{jobs.kill(this.job.id,void 0,`cancelled from settings card`)}catch(error){return refused$1(500,String(error))}return{ok:!0,jobId:String(this.job.id)}}};function markRemote(prototype,methodName){let context={kind:`method`,name:methodName,static:!1,private:!1,addInitializer:initializer=>{Reflect.apply(initializer,Object.create(prototype),[])}},decorate=Remote(methodName);Reflect.apply(decorate,void 0,[Reflect.get(prototype,methodName),context])}markRemote(ScraplingRuntimeService.prototype,`status`),markRemote(ScraplingRuntimeService.prototype,`installPack`),markRemote(ScraplingRuntimeService.prototype,`repairPack`),markRemote(ScraplingRuntimeService.prototype,`cancelJob`);function installRuntimeRemote(ctx,deps){let reflect=Reflect.get(ctx,`reflect`);return!e(reflect)||typeof field(reflect,`provide`)!=`function`?!1:(new ScraplingRuntimeService(ctx,deps),!0)}function tryParse(address){try{return{ok:!0,value:ipaddr.parse(address)}}catch{return{ok:!1}}}const ALLOWED_PROTOCOLS=/* @__PURE__ */ new Set([`http:`,`https:`]),DEFAULT_NAT64_PREFIXES=[`64:ff9b::/96`,`64:ff9b:1::/48`],NAT64_EMBEDDED_OFFSETS={96:12,64:9,56:7,48:6,40:5,32:4};function stripBrackets(hostname){return hostname.startsWith(`[`)&&hostname.endsWith(`]`)?hostname.slice(1,-1):hostname}function buildNat64Table(prefixes){return prefixes.map(prefix=>{let[netHex=``,bitsText=``]=prefix.split(`/`),{value}=tryParse(netHex),bits=Math.trunc(Number(bitsText)),offset=NAT64_EMBEDDED_OFFSETS[bits];if(!(value instanceof ipaddr.IPv6)||offset===void 0)throw Error(`malformed NAT64 prefix: ${prefix}`);return{network:value,bits,offset}})}function nat64InnerBytes(packed,offset){return packed.slice(offset,offset+5).filter((_byte,index)=>offset+index!==8).slice(0,4)}function extractNat64(parsed,entry){if(!parsed.match(entry.network,entry.bits))return null;let inner=ipaddr.fromByteArray(nat64InnerBytes(parsed.toByteArray(),entry.offset)),ipv4=inner instanceof ipaddr.IPv4?inner:inner.toIPv4Address();return{address:ipv4.toString(),range:ipv4.range()}}function embeddedV4(parsed,table){return table.map(entry=>extractNat64(parsed,entry)).find(hit=>hit!==null)??null}function ipv4Compatible(parsed){let packed=parsed.toByteArray();if(packed.slice(0,12).some(byte=>byte!==0))return null;let inner=ipaddr.fromByteArray(packed.slice(12,16)),ipv4=inner instanceof ipaddr.IPv4?inner:inner.toIPv4Address();return{address:ipv4.toString(),range:ipv4.range()}}function effectiveRange(address,table){let{value}=tryParse(address);if(value===void 0)return`unparsable`;if(value instanceof ipaddr.IPv6&&value.range()===`ipv4Mapped`)return value.toIPv4Address().range();if(value instanceof ipaddr.IPv6){let inner=embeddedV4(value,table);if(inner!==null)return inner.range;let compat=ipv4Compatible(value);if(compat!==null)return compat.range}return value.range()}function isPublicAddress(address,table){return effectiveRange(address,table)===`unicast`}function ipv4ToLong(parsed){return parsed.toByteArray().reduce((accumulator,byte)=>accumulator*256+byte,0)}function isAcceptableAnswer(address,table,pools){if(isPublicAddress(address,table))return!0;let parsed=tryParse(address).value;if(!(parsed instanceof ipaddr.IPv4))return!1;let value=ipv4ToLong(parsed);return pools.some(({first,last})=>value>=first&&value<=last)}const SYNTHETIC_POOLS=[{first:ipv4ToLong(ipaddr.IPv4.parse(`198.18.0.0`)),last:ipv4ToLong(ipaddr.IPv4.parse(`198.19.255.255`))},{first:ipv4ToLong(ipaddr.IPv4.parse(`100.64.0.0`)),last:ipv4ToLong(ipaddr.IPv4.parse(`100.127.255.255`))}];function parseSyntheticRange(entry){let parsed,bits;try{[parsed,bits]=ipaddr.parseCIDR(entry.trim())}catch{return null}if(!(parsed instanceof ipaddr.IPv4)||bits>32)return null;let span=2**(32-bits),first=Math.floor(ipv4ToLong(parsed)/span)*span;return{first,last:first+span-1}}const CONTROL_HOSTS=[`example.com`,`www.iana.org`,`www.wikipedia.org`];function isPoolMember(value){return SYNTHETIC_POOLS.some(pool=>value>=pool.first&&value<=pool.last)}async function detectSyntheticResolver(resolve,table){let flat=(await Promise.all(CONTROL_HOSTS.map(async host=>{try{return await resolve(host)}catch{return[]}}))).flat();if(flat.length<CONTROL_HOSTS.length||new Set(flat).size<2||!flat.every(address=>!isPublicAddress(address,table)))return[];let longs=[];for(let address of flat){let parsed=tryParse(address).value;if(!(parsed instanceof ipaddr.IPv4))return[];longs.push(ipv4ToLong(parsed))}return longs.every(value=>!isPoolMember(value))?[]:SYNTHETIC_POOLS}function isIpLiteral(hostname){return tryParse(stripBrackets(hostname)).ok}function isAuthorityAmbiguity(char){
17
+ if(stdin===void 0)throw new SidecarError(`SIDECAR_UNAVAILABLE`,`sidecar is not running`);this.#nextId+=1;let id=`h${this.#nextId}`,timeoutMs=options.timeoutMs===void 0?this.#options.requestTimeoutMs:options.timeoutMs,frame=`${encodeFrame({id,method,params:outgoing})}\n`,settled=new Promise((resolve,reject)=>{let entry={resolve,reject,timer:void 0,detachAbort:void 0};this.#pending.set(id,entry);let{signal}=options,failRequest=(code,message)=>{this.#pending.delete(id),SidecarClient.#settle(entry,new SidecarError(code,message))};if(timeoutMs!==null&&(entry.timer=setTimeout(()=>{this.#pending.delete(id),SidecarClient.#settle(entry,new SidecarError(`SIDECAR_TIMEOUT`,`${method} timed out after ${timeoutMs}ms`)),this.#teardown(`${method} timed out after ${timeoutMs}ms`,`SIDECAR_TIMEOUT`)},timeoutMs)),signal!==void 0){let onAbort=()=>{failRequest(`SIDECAR_ABORTED`,`${method} was aborted`)};signal.aborted?onAbort():(signal.addEventListener(`abort`,onAbort,{once:!0}),entry.detachAbort=()=>{signal.removeEventListener(`abort`,onAbort)})}});if(!this.#pending.has(id))return settled;if(stdin.destroyed)return this.#teardown(`failed to send ${method}: stdin is gone`,`SIDECAR_CRASHED`),settled;try{stdin.write(frame)}catch(error){this.#teardown(`failed to send ${method}: ${String(error)}`,`SIDECAR_CRASHED`)}return settled}async dispose(){if(this.#stopped)return;this.#stopped=!0;let child=this.#handle;if(child?.stdin!==void 0){try{child.stdin.write(`${encodeFrame({id:`dispose`,method:`shutdown`,params:{}})}\n`)}catch{}let exited=child.done.then(()=>!0,()=>!0),timer,grace=new Promise(resolve=>{timer=setTimeout(()=>{resolve(!1)},this.#options.graceMs)}),finished=await Promise.race([exited,grace]);if(clearTimeout(timer),finished){this.#stopPump?.(),this.#stopPump=void 0,this.#handle=void 0,this.#capabilities=void 0,this.#starting=void 0,this.#rejectAll(new SidecarError(`SIDECAR_CLOSED`,`client disposed`));return}}await this.#teardown(`client disposed`,`SIDECAR_CLOSED`)}};function createSidecar(ctx,options){return new SidecarClient(ctx,options)}function sidecarErrorWithCode(code,message,options,details={}){return new SidecarError(code,message.startsWith(`${code}: `)?message:`${code}: ${message}`,options,details)}async function callSidecar(client,method,params={},options={}){try{return await client.call(method,params,options)}catch(error){throw error instanceof SidecarError?sidecarErrorWithCode(error.code,error.message,{cause:error},error.details):error}}const RUNTIME_ASSET_SCHEMA=z.object({platform:z.string(),arch:z.string(),pythonVersion:z.string(),release:z.string(),url:z.url(),sha256:z.string(),sizeBytes:z.int().positive()}),RUNTIME_MANIFEST_SCHEMA=z.object({darwinArm64:RUNTIME_ASSET_SCHEMA,unsupported:z.record(z.string(),z.string())}),packageRoot=existsSync(path.join(import.meta.dirname,`runtime-manifest.json`))?import.meta.dirname:path.resolve(import.meta.dirname,`..`);function parseRuntimeManifest(text){let parsed=JSON.parse(text),result=RUNTIME_MANIFEST_SCHEMA.safeParse(parsed);if(!result.success)throw Error(`runtime-manifest.json is invalid: ${z.prettifyError(result.error)}`);return result.data}const runtimeManifest=parseRuntimeManifest(readFileSync(path.join(packageRoot,`runtime-manifest.json`),`utf8`));function managedPythonPath(dataDir){return path.join(dataDir,`runtime`,`python`,runtimeManifest.darwinArm64.pythonVersion,`bin`,`python3`)}function executable(file){try{return accessSync(file,constants.X_OK),!0}catch{return!1}}function repoPythonPath(repoRoot){return process.platform===`win32`?path.join(repoRoot,`_env`,`.venv`,`Scripts`,`python.exe`):path.join(repoRoot,`_env`,`.venv`,`bin`,`python`)}function resolveRuntime(options){let explicit=options.pythonBin.trim();if(explicit.length>0)return{pythonPath:explicit,via:`configured`,version:`unknown`};if(process.platform===`darwin`&&process.arch===`arm64`&&options.dataDir.length>0){let managed=managedPythonPath(options.dataDir);if(executable(managed))return{pythonPath:managed,via:`managed`,version:runtimeManifest.darwinArm64.pythonVersion}}let repoPython=repoPythonPath(options.repoRoot);return executable(repoPython)?{pythonPath:repoPython,via:`repo`,version:`unknown`}:{pythonPath:process.platform===`win32`?`python.exe`:`python3`,via:`path`,version:`unknown`}}function isPlainRecord(value){return typeof value==`object`&&!!value&&!Array.isArray(value)}const STATE_FILE=`state.json`,WHITESPACE_RUNS=/\s+/u,PIP_NO_WHEEL=/No matching distribution|Could not find a version/iu,PIP_NETWORK=/Network|Temporary failure|Connection|timed out/iu;function installerSupported(){return process.platform===`darwin`&&process.arch===`arm64`}const CHROMIUM_MARKERS=/* @__PURE__ */ new Set([`Chromium`,`chrome`,`chrome.exe`,`Google Chrome for Testing`]);var InstallError=class extends Error{code;constructor(code,message,options){super(message,options),this.name=`InstallError`,this.code=code}};async function run(argv,options={}){return new Promise(resolve=>{let child=spawn(argv[0]??``,argv.slice(1),{env:{...process.env,...options.env},stdio:[`ignore`,`pipe`,`pipe`]}),stdout=``,stderr=``;child.stdout.on(`data`,chunk=>{stdout+=chunk.toString(`utf8`)}),child.stderr.on(`data`,chunk=>{stderr+=chunk.toString(`utf8`)}),child.on(`error`,error=>{resolve({code:null,stdout,stderr:`${stderr}${String(error)}`})}),child.on(`close`,code=>{resolve({code,stdout,stderr})})})}function createCurlDownloader(runStep){return async url=>{let target=path.join(os.tmpdir(),`dsh-scrapling-dl-${randomUUID()}`),result=await runStep([`curl`,`--fail`,`--location`,`--silent`,`--show-error`,`--output`,target,url]);if(result.code===0)try{return new Uint8Array(await readFile(target))}finally{await rm(target,{force:!0})}if(await rm(target,{force:!0}),result.code!==null)throw new InstallError(`INSTALL_NETWORK`,`curl failed for ${url}: ${result.stderr.slice(0,400)}`);let response=await fetch(url);if(!response.ok)throw new InstallError(`INSTALL_NETWORK`,`${url} answered HTTP ${response.status}`);return new Uint8Array(await response.arrayBuffer())}}const defaultInstallerIO={download:createCurlDownloader(run),extract:async(archive,destination)=>{let result=await run([`tar`,`-xzf`,archive,`-C`,destination]);if(result.code!==0)throw new InstallError(`INSTALL_FAILED`,`tar failed: ${result.stderr.slice(0,400)}`)},spawn:run};async function exists(file){try{return await access(file,constants.F_OK),!0}catch{return!1}}async function readLockOwner(lockPath){let text=``;try{text=await readFile(lockPath,`utf8`)}catch{}let pid=Math.trunc(Number(text.trim().split(WHITESPACE_RUNS)[0]));return Number.isSafeInteger(pid)&&pid>0?pid:void 0}async function lockHeldByLivingProcess(lockPath){let text,modifiedAt;try{let[content,stats]=await Promise.all([readFile(lockPath,`utf8`),stat(lockPath)]);text=content,modifiedAt=stats.mtimeMs}catch{return!0}let[pidText=``]=text.trim().split(WHITESPACE_RUNS),pid=Math.trunc(Number(pidText));if(Number.isSafeInteger(pid)&&pid>0){if(pid===process.pid)return!0;try{return process.kill(pid,0),!0}catch(error){return error.code===`EPERM`}}return Date.now()-modifiedAt<1e4}async function acquireLock(lockPath,openLock=open){try{return await openLock(lockPath,`wx`)}catch{if(await lockHeldByLivingProcess(lockPath))throw new InstallError(`INSTALL_BUSY`,`another install holds ${lockPath}`);await rm(lockPath,{force:!0});try{return await openLock(lockPath,`wx`)}catch{throw new InstallError(`INSTALL_BUSY`,`another install holds ${lockPath}`)}}}async function releaseLock(lockPath,handle){try{await handle.close()}catch{}if(await readLockOwner(lockPath)===process.pid)try{await rm(lockPath,{force:!0})}catch{}}const heldLockDepths=/* @__PURE__ */ new Map;function releaseLockDepth(key,held){held<=1?heldLockDepths.delete(key):heldLockDepths.set(key,held-1)}async function ensureRuntimeDir(dataDir){let runtimeDir=path.join(dataDir,`runtime`);return await mkdir(runtimeDir,{recursive:!0}),process.platform!==`win32`&&await chmod(runtimeDir,448),runtimeDir}async function withInstallLock(dataDir,work,openLock=open){let runtimeDir=path.join(dataDir,`runtime`),lockPath=path.join(runtimeDir,`install.lock`),key=path.resolve(lockPath),depth=heldLockDepths.get(key)??0;if(depth>0){heldLockDepths.set(key,depth+1);try{return await work()}finally{releaseLockDepth(key,depth+1)}}await ensureRuntimeDir(dataDir);let handle=await acquireLock(lockPath,openLock);heldLockDepths.set(key,1);try{return await handle.writeFile(`${process.pid} ${Date.now()}\n`),await work()}finally{releaseLockDepth(key,1),await releaseLock(lockPath,handle)}}async function offlineArchive(assets,url){let raw=path.basename(new URL(url).pathname),decoded=decodeURIComponent(raw),names=raw===decoded?[raw]:[decoded,raw],bytes=(await Promise.all(names.map(async name=>({name,bytes:await readFile(path.join(assets,name)).catch(()=>null)})))).find(item=>item.bytes!==null)?.bytes;if(bytes==null)throw new InstallError(`INSTALL_OFFLINE_ASSETS`,`offline python archive missing under ${assets}: expected ${names.join(` or `)}`);return new Uint8Array(bytes)}async function installPython(asset,dataDir,io,assets){return withInstallLock(dataDir,async()=>{let tmpRoot=path.join(dataDir,`runtime`,`.tmp`,randomUUID());await mkdir(tmpRoot,{recursive:!0});let archive=path.join(tmpRoot,`python.tar.gz`);try{let bytes=assets===void 0?await io.download(asset.url):await offlineArchive(assets,asset.url),digest=createHash(`sha256`).update(bytes).digest(`hex`);if(digest!==asset.sha256)throw new InstallError(`INSTALL_HASH_MISMATCH`,`python archive hash ${digest} does not match ${asset.sha256}`);await writeFile(archive,bytes);let extractDir=path.join(tmpRoot,`extract`);await mkdir(extractDir,{recursive:!0}),await io.extract(archive,extractDir);let layout=path.join(extractDir,`python`),source=await exists(path.join(layout,`bin`,`python3`))?layout:extractDir,target=path.dirname(path.dirname(managedPythonPath(dataDir)));await rm(target,{recursive:!0,force:!0}),await mkdir(path.dirname(target),{recursive:!0}),await cp(source,target,{recursive:!0,dereference:!0});let pythonPath=managedPythonPath(dataDir);if(!await exists(pythonPath))throw new InstallError(`INSTALL_FAILED`,`python archive did not contain bin/python3`);return{pythonPath,version:asset.pythonVersion}}finally{await rm(tmpRoot,{recursive:!0,force:!0}),await rmdir(path.join(dataDir,`runtime`,`.tmp`)).catch(()=>null)}})}async function readRuntimeState(dataDir){let statePath=path.join(dataDir,`runtime`,STATE_FILE),text;try{text=await readFile(statePath,`utf8`)}catch(error){if(error.code===`ENOENT`)return{packs:{}};throw new InstallError(`INSTALL_STATE_CORRUPT`,`cannot read ${statePath}: ${String(error)}; delete it and install again`,{cause:error})}let parsed;try{parsed=JSON.parse(text)}catch(error){throw new InstallError(`INSTALL_STATE_CORRUPT`,`${statePath} is not valid JSON; delete it and install again`,{cause:error})}if(!isPlainRecord(parsed))throw new InstallError(`INSTALL_STATE_CORRUPT`,`${statePath} does not hold a JSON object; delete it and install again`);return parsed}async function writeRuntimeState(dataDir,state){let runtimeDir=await ensureRuntimeDir(dataDir),target=path.join(runtimeDir,STATE_FILE),staging=`${target}.${randomUUID()}.tmp`;try{await writeFile(staging,JSON.stringify(state,null,2),`utf8`),await rename(staging,target)}finally{try{await rm(staging,{force:!0})}catch{}}}async function rewriteShebangs(scanDir,from,to,readScript=file=>readFile(file,`utf8`)){let binDir=path.join(scanDir,`bin`),stale=`#!${from}/`,files=(await readdir(binDir,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isFile()).map(entry=>path.join(binDir,entry.name));await Promise.all(files.map(async file=>{let text=await readScript(file).catch(()=>``),newline=text.indexOf(`
18
+ `),head=newline===-1?text:text.slice(0,newline);if(!head.startsWith(stale))return;let tail=newline===-1?``:text.slice(newline);await writeFile(file,`#!${to}/${head.slice(stale.length)}${tail}`,`utf8`)}))}async function finishCoreInstall(paths,restore){if(restore){try{await rm(paths.venv,{recursive:!0,force:!0})}catch{}try{await rename(paths.previousVenv,paths.venv)}catch{}}try{await rm(paths.previousVenv,{recursive:!0,force:!0})}catch{}try{await rm(paths.staging,{recursive:!0,force:!0})}catch{}}async function installCore(options){let{io}=options;await withInstallLock(options.dataDir,async()=>{let runtimeDir=await ensureRuntimeDir(options.dataDir),venv=path.join(runtimeDir,`venv`),staging=path.join(runtimeDir,`.tmp`,`venv-${randomUUID()}`),previousVenv=path.join(runtimeDir,`.tmp`,`venv-previous-${randomUUID()}`),requirements=path.join(options.repoRoot,`py`,`runtime-requirements.txt`),movedAside=!1,committed=!1;try{let created=await io.spawn([options.pythonPath,`-m`,`venv`,staging]);if(created.code!==0)throw new InstallError(`INSTALL_FAILED`,`venv failed: ${created.stderr.slice(0,400)}`);let stagingPython=path.join(staging,`bin`,`python3`),offlineArgs=options.assets===void 0?[]:[`--no-index`,`--find-links`,path.join(options.assets,`wheels`)],installed=await io.spawn([stagingPython,`-m`,`pip`,`install`,`--only-binary=:all:`,`--require-hashes`,`-r`,requirements,...offlineArgs],{env:{PIP_DISABLE_PIP_VERSION_CHECK:`1`}});if(installed.code!==0){let text=`${installed.stdout}\n${installed.stderr}`;throw PIP_NO_WHEEL.test(text)?new InstallError(`INSTALL_NO_WHEEL`,`a dependency has no wheel for this platform`):PIP_NETWORK.test(text)?new InstallError(`INSTALL_NETWORK`,`pip could not reach the package index`):new InstallError(`INSTALL_FAILED`,`pip failed: ${installed.stderr.slice(0,400)}`)}await rewriteShebangs(staging,staging,venv);try{await exists(venv)&&(await rename(venv,previousVenv),movedAside=!0),await rename(staging,venv)}catch(error){throw new InstallError(`INSTALL_FAILED`,`cannot replace ${venv}: ${String(error)}`,{cause:error})}let previous=await readRuntimeState(options.dataDir),packs={...isPlainRecord(previous.packs)?previous.packs:{},core:`ready`};await writeRuntimeState(options.dataDir,{...previous,packs,python:options.pythonPath}),committed=!0}finally{await finishCoreInstall({venv,previousVenv,staging},movedAside&&!committed)}})}async function installBrowser(options){let{io}=options;return withInstallLock(options.dataDir,async()=>{let browsersPath=path.join(options.dataDir,`runtime`,`browsers`);await mkdir(browsersPath,{recursive:!0});let installed=await io.spawn([options.pythonPath,`-m`,`patchright`,`install`,`chromium`],{env:{PLAYWRIGHT_BROWSERS_PATH:browsersPath}});if(installed.code!==0)throw new InstallError(`INSTALL_BROWSER_FAILED`,`chromium install failed: ${installed.stderr.slice(0,400)}`);let hasBrowser;try{hasBrowser=(await readdir(browsersPath,{recursive:!0})).some(entry=>CHROMIUM_MARKERS.has(path.basename(entry)))}catch{hasBrowser=!1}if(!hasBrowser)throw new InstallError(`INSTALL_BROWSER_FAILED`,`no chromium executable found under ${browsersPath}`);let previous=await readRuntimeState(options.dataDir),packs={...isPlainRecord(previous.packs)?previous.packs:{},browser:`ready`};return await writeRuntimeState(options.dataDir,{...previous,packs,browsersPath}),{browsersPath}})}async function chromiumInstalled(dataDir){try{return(await readdir(path.join(dataDir,`runtime`,`browsers`),{recursive:!0})).some(entry=>CHROMIUM_MARKERS.has(path.basename(entry)))}catch{return!1}}function stateOf(marked,installed){return marked===`ready`?installed?`ready`:`corrupt`:`missing`}async function packStates(dataDir,installing){if(!installerSupported())return{core:`blocked`,browser:`blocked`,search:`blocked`,media:`blocked`,"adaptive-redis":`blocked`,mcp:`blocked`};let raw=(await readRuntimeState(dataDir)).packs,packs=isPlainRecord(raw)?raw:{},core=stateOf(packs.core,await exists(path.join(dataDir,`runtime`,`venv`,`bin`,`python3`))),result={core,browser:stateOf(packs.browser,await chromiumInstalled(dataDir)),search:core,media:core,"adaptive-redis":core,mcp:core};return installing!==void 0&&(result[installing]=`installing`),result}function throwIfAborted(signal){if(signal?.aborted===!0)throw new InstallError(`INSTALL_FAILED`,`install cancelled`)}async function ensurePython(dataDir,io,signal,asset,assets){let managed=managedPythonPath(dataDir);return await exists(managed)?managed:(throwIfAborted(signal),(await installPython(asset,dataDir,io,assets)).pythonPath)}async function installCapabilityPack(pack,options){if(!installerSupported())throw new InstallError(`INSTALL_PACK_BLOCKED`,`runtime packs are verified on macOS arm64 only; this host is ${process.platform}/${process.arch}`);let{dataDir,repoRoot,io,signal,onProgress,assets}=options,asset=options.asset??runtimeManifest.darwinArm64;if(assets!==void 0&&!await exists(path.join(assets,`wheels`)))throw new InstallError(`INSTALL_OFFLINE_ASSETS`,`offline wheelhouse missing: ${path.join(assets,`wheels`)}`);throwIfAborted(signal),onProgress?.(`installing ${pack}`);let pythonPath=await ensurePython(dataDir,io,signal,asset,assets);throwIfAborted(signal),onProgress?.(`installing core packages into ${pythonPath}`),await installCore({pythonPath,dataDir,repoRoot,io,...assets===void 0?{}:{assets}}),throwIfAborted(signal),pack===`browser`&&(onProgress?.(`installing full chromium`),await installBrowser({pythonPath:path.join(dataDir,`runtime`,`venv`,`bin`,`python3`),dataDir,io}),throwIfAborted(signal)),onProgress?.(`${pack} ready`)}const PACK_NAMES=/* @__PURE__ */ new Set([`core`,`browser`,`search`,`media`,`adaptive-redis`,`mcp`]);function isRuntimePack(value){return typeof value==`string`&&PACK_NAMES.has(value)}function refused$1(status,error){return{ok:!1,status,error}}function field(record,key){return record[key]}function isLive(status){return status===`running`||status===`stopping`}function outputOf(read){let text=read.chunks.map(chunk=>chunk.text).join(``);return text.length>4e3?text.slice(-4e3):text}var ScraplingRuntimeService=class extends TypertRemoteService{deps;job=null;constructor(ctx,deps){super(ctx,`scraplingRuntime`),this.deps=deps}jobView(jobs){if(this.job===null||jobs===void 0)return null;try{let view=jobs.get(this.job.id);return{id:String(this.job.id),pack:this.job.pack,status:view.status,output:outputOf(jobs.readAt(this.job.id,0))}}catch{return null}}liveJob(jobs){return this.job===null?null:isLive(jobs.get(this.job.id).status)?this.job:null}async status(){let jobs=this.deps.jobsOf(),job=this.jobView(jobs),installing=job!==null&&isLive(job.status)?job.pack:void 0,python=resolveRuntime({pythonBin:this.deps.pythonBin,dataDir:this.deps.dataDir,repoRoot:this.deps.repoRoot});return{ok:!0,packs:await packStates(this.deps.dataDir,installing),python:{path:python.pythonPath,via:python.via,version:python.version},dataDir:this.deps.dataDir,jobsReady:jobs!==void 0,job}}installPack(request){return this.start(request,`install`)}repairPack(request){return this.start(request,`repair`)}start(request,action){let record=e(request)?request:void 0,raw=record===void 0?void 0:field(record,`pack`);if(!isRuntimePack(raw))return refused$1(400,`pack must be one of core|browser|search|media|adaptive-redis|mcp`);let jobs=this.deps.jobsOf();if(jobs===void 0)return refused$1(503,`this profile has no jobs backend; run the CLI instead`);let running;try{running=this.liveJob(jobs)}catch(error){return refused$1(500,`cannot read the last install job: ${String(error)}`)}if(running!==null)return refused$1(409,`another install is running: ${String(running.id)}`);let pack=raw,controller=new AbortController,spec={kind:`scrapling-runtime`,label:`${action} ${pack}`,run:job=>{let progress=line=>{job.updateProgress(line),job.append(`${line}\n`,{channel:`log`})};return{cancel:()=>{controller.abort()},done:(async()=>{try{return await this.deps.installPackFn(pack,{dataDir:this.deps.dataDir,repoRoot:this.deps.repoRoot,io:this.deps.io,signal:controller.signal,onProgress:progress}),{status:`completed`}}catch(error){return controller.signal.aborted?{status:`killed`,detail:`cancelled from settings card`}:{status:`failed`,detail:String(error)}}})()}}},id;try{let detach=jobs.attachController(`scrapling: runtime`);try{id=jobs.start(spec)}finally{detach()}}catch(error){return refused$1(500,String(error))}return this.job={id,pack},{ok:!0,jobId:String(id)}}cancelJob(request){let record=e(request)?request:void 0,raw=record===void 0?void 0:field(record,`jobId`);if(typeof raw!=`string`||raw.length===0)return refused$1(400,`cancel requires a jobId`);if(this.job===null||String(this.job.id)!==raw)return refused$1(404,`unknown jobId: ${raw}`);let jobs=this.deps.jobsOf();if(jobs===void 0)return refused$1(503,`this profile has no jobs backend`);try{jobs.kill(this.job.id,void 0,`cancelled from settings card`)}catch(error){return refused$1(500,String(error))}return{ok:!0,jobId:String(this.job.id)}}};function markRemote(prototype,methodName){let context={kind:`method`,name:methodName,static:!1,private:!1,addInitializer:initializer=>{Reflect.apply(initializer,Object.create(prototype),[])}},decorate=Remote(methodName);Reflect.apply(decorate,void 0,[Reflect.get(prototype,methodName),context])}markRemote(ScraplingRuntimeService.prototype,`status`),markRemote(ScraplingRuntimeService.prototype,`installPack`),markRemote(ScraplingRuntimeService.prototype,`repairPack`),markRemote(ScraplingRuntimeService.prototype,`cancelJob`);function installRuntimeRemote(ctx,deps){let reflect=Reflect.get(ctx,`reflect`);return!e(reflect)||typeof field(reflect,`provide`)!=`function`?!1:(new ScraplingRuntimeService(ctx,deps),!0)}const AUTHORITY_END=/[/?#]/u,URL_USERINFO=/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)[^/?#]*@/iu;function tryParse(address){try{return{ok:!0,value:ipaddr.parse(address)}}catch{return{ok:!1}}}const ALLOWED_PROTOCOLS=/* @__PURE__ */ new Set([`http:`,`https:`]),DEFAULT_NAT64_PREFIXES=[`64:ff9b::/96`,`64:ff9b:1::/48`],NAT64_EMBEDDED_OFFSETS={96:12,64:9,56:7,48:6,40:5,32:4};function stripBrackets(hostname){return hostname.startsWith(`[`)&&hostname.endsWith(`]`)?hostname.slice(1,-1):hostname}function buildNat64Table(prefixes){return prefixes.map(prefix=>{let[netHex=``,bitsText=``]=prefix.split(`/`),{value}=tryParse(netHex),bits=Math.trunc(Number(bitsText)),offset=NAT64_EMBEDDED_OFFSETS[bits];if(!(value instanceof ipaddr.IPv6)||offset===void 0)throw Error(`malformed NAT64 prefix: ${prefix}`);return{network:value,bits,offset}})}function nat64InnerBytes(packed,offset){return packed.slice(offset,offset+5).filter((_byte,index)=>offset+index!==8).slice(0,4)}function extractNat64(parsed,entry){if(!parsed.match(entry.network,entry.bits))return null;let inner=ipaddr.fromByteArray(nat64InnerBytes(parsed.toByteArray(),entry.offset)),ipv4=inner instanceof ipaddr.IPv4?inner:inner.toIPv4Address();return{address:ipv4.toString(),range:ipv4.range()}}function embeddedV4(parsed,table){return table.map(entry=>extractNat64(parsed,entry)).find(hit=>hit!==null)??null}function ipv4Compatible(parsed){let packed=parsed.toByteArray();if(packed.slice(0,12).some(byte=>byte!==0))return null;let inner=ipaddr.fromByteArray(packed.slice(12,16)),ipv4=inner instanceof ipaddr.IPv4?inner:inner.toIPv4Address();return{address:ipv4.toString(),range:ipv4.range()}}function effectiveRange(address,table){let{value}=tryParse(address);if(value===void 0)return`unparsable`;if(value instanceof ipaddr.IPv6&&value.range()===`ipv4Mapped`)return value.toIPv4Address().range();if(value instanceof ipaddr.IPv6){let inner=embeddedV4(value,table);if(inner!==null)return inner.range;let compat=ipv4Compatible(value);if(compat!==null)return compat.range}return value.range()}function isPublicAddress(address,table){return effectiveRange(address,table)===`unicast`}function ipv4ToLong(parsed){return parsed.toByteArray().reduce((accumulator,byte)=>accumulator*256+byte,0)}function isAcceptableAnswer(address,table,pools){if(isPublicAddress(address,table))return!0;let parsed=tryParse(address).value;if(!(parsed instanceof ipaddr.IPv4))return!1;let value=ipv4ToLong(parsed);return pools.some(({first,last})=>value>=first&&value<=last)}const SYNTHETIC_POOLS=[{first:ipv4ToLong(ipaddr.IPv4.parse(`198.18.0.0`)),last:ipv4ToLong(ipaddr.IPv4.parse(`198.19.255.255`))},{first:ipv4ToLong(ipaddr.IPv4.parse(`100.64.0.0`)),last:ipv4ToLong(ipaddr.IPv4.parse(`100.127.255.255`))}];function parseSyntheticRange(entry){let parsed,bits;try{[parsed,bits]=ipaddr.parseCIDR(entry.trim())}catch{return null}if(!(parsed instanceof ipaddr.IPv4)||bits>32)return null;let span=2**(32-bits),first=Math.floor(ipv4ToLong(parsed)/span)*span;return{first,last:first+span-1}}const CONTROL_HOSTS=[`example.com`,`www.iana.org`,`www.wikipedia.org`];function isPoolMember(value){return SYNTHETIC_POOLS.some(pool=>value>=pool.first&&value<=pool.last)}async function detectSyntheticResolver(resolve,table){let flat=(await Promise.all(CONTROL_HOSTS.map(async host=>{try{return await resolve(host)}catch{return[]}}))).flat();if(flat.length<CONTROL_HOSTS.length||new Set(flat).size<2||!flat.every(address=>!isPublicAddress(address,table)))return[];let longs=[];for(let address of flat){let parsed=tryParse(address).value;if(!(parsed instanceof ipaddr.IPv4))return[];longs.push(ipv4ToLong(parsed))}return longs.every(value=>!isPoolMember(value))?[]:SYNTHETIC_POOLS}function isIpLiteral(hostname){return tryParse(stripBrackets(hostname)).ok}function isAuthorityAmbiguity(char){
21
19
  /* v8 ignore next -- 调用方是 split("") 的结果,不会产出空串,这个兜底到不了 */
22
- let code=char.codePointAt(0)??0;return char===`\\`||code<=31||code===127}function authorityOf(input){let schemeEnd=input.indexOf(`://`),rest=schemeEnd===-1?input:input.slice(schemeEnd+3),end=rest.search(/[/?#]/u);return end===-1?rest:rest.slice(0,end)}function redactUrlSecrets(input){let masked=input.replace(/^(?<scheme>[a-z][a-z0-9+.-]*:\/\/)[^/?#]*@/iu,`$<scheme>***@`);if(masked!==input)return masked;let at=input.indexOf(`@`);return at>0&&!input.slice(0,at).includes(`/`)?`***@${input.slice(at+1)}`:input}async function resolveWithNodeDns(hostname){let{lookup}=await import(`node:dns/promises`);return(await lookup(hostname,{all:!0})).map(entry=>entry.address)}function createUrlPolicy(options){let{maxUrlLength}=options,resolve=options.resolve??resolveWithNodeDns,table=buildNat64Table([...DEFAULT_NAT64_PREFIXES,...options.nat64Prefixes??[]]),allowed=new Set((options.allowHosts??[]).map(host=>host.trim().toLowerCase())),manualRanges=(options.syntheticRanges??[]).map(entry=>parseSyntheticRange(entry)).filter(range=>range!==null),detected,screen=input=>{if(input.length>maxUrlLength)return{ok:!1,reason:`too-long`,message:`URL exceeds the maximum length of ${maxUrlLength}`};if(authorityOf(input).split(``).some(char=>isAuthorityAmbiguity(char)))return{ok:!1,reason:`ambiguous-authority`,message:`URL authority contains a backslash or a control character`};let url;try{url=new URL(input)}catch{return{ok:!1,reason:`invalid-url`,message:`invalid URL: ${redactUrlSecrets(input)}`}}return ALLOWED_PROTOCOLS.has(url.protocol)?url.username.length>0||url.password.length>0?{ok:!1,reason:`credentials-not-allowed`,message:`credentials in URLs are not allowed`}:{ok:!0,url}:{ok:!1,reason:`scheme-not-allowed`,message:`unsupported URL scheme "${url.protocol}" (only http and https are allowed)`}};return{screen,verify:async input=>{let screened=screen(input);if(!screened.ok)return screened;let{url}=screened,literal=isIpLiteral(url.hostname),addresses;if(literal)addresses=[stripBrackets(url.hostname)];else try{addresses=await resolve(url.hostname)}catch(error){return{ok:!1,reason:`resolve-failed`,message:`failed to resolve host: ${url.hostname} (${String(error)})`}}if(addresses.length===0)return{ok:!1,reason:`no-address`,message:`host resolved to no addresses: ${url.hostname}`};if(allowed.has(url.hostname.toLowerCase()))return screened;let pools=literal?[]:[...manualRanges,...await(detected??=detectSyntheticResolver(resolve,table))],offender=addresses.find(address=>!isAcceptableAnswer(address,table,pools));return offender===void 0?screened:{ok:!1,reason:`private-address`,message:`host resolves to a non-public address (${offender}): ${url.hostname}`}},isPublicAddress:address=>isPublicAddress(address,table)}}const SELECT_TRUNCATION_HINT=`结果被截断:请减小 limit,或提高 maxContentChars 后再取。`;function tailOf(notice,truncated){return notice!==void 0&&notice.length>0?notice:truncated?SELECT_TRUNCATION_HINT:``}function normalizeBudget(budgetBytes){return!Number.isFinite(budgetBytes)||budgetBytes<1?2e5:Math.floor(budgetBytes)}function capText(text,budgetBytes,recovery){let budget=normalizeBudget(budgetBytes);if(Buffer.byteLength(text,`utf8`)<=budget)return{text,truncated:!1,notice:``};let headBytes=Math.min(Math.max(1,Math.floor(budget*2/3)),budget-1),tailBytes=budget-headBytes,retainer=new TextRetainer({kind:`headTail`,headBytes,tailBytes});retainer.push(text);let kept=retainer.finish();
20
+ let code=char.codePointAt(0)??0;return char===`\\`||code<=31||code===127}function authorityOf(input){let schemeEnd=input.indexOf(`://`),rest=schemeEnd===-1?input:input.slice(schemeEnd+3),end=rest.search(AUTHORITY_END);return end===-1?rest:rest.slice(0,end)}function redactUrlSecrets(input){let masked=input.replace(URL_USERINFO,`$<scheme>***@`);if(masked!==input)return masked;let at=input.indexOf(`@`);return at>0&&!input.slice(0,at).includes(`/`)?`***@${input.slice(at+1)}`:input}async function resolveWithNodeDns(hostname){let{lookup}=await import(`node:dns/promises`);return(await lookup(hostname,{all:!0})).map(entry=>entry.address)}function createUrlPolicy(options){let{maxUrlLength}=options,resolve=options.resolve??resolveWithNodeDns,table=buildNat64Table([...DEFAULT_NAT64_PREFIXES,...options.nat64Prefixes??[]]),allowed=new Set((options.allowHosts??[]).map(host=>host.trim().toLowerCase())),manualRanges=(options.syntheticRanges??[]).map(entry=>parseSyntheticRange(entry)).filter(range=>range!==null),detected,screen=input=>{if(input.length>maxUrlLength)return{ok:!1,reason:`too-long`,message:`URL exceeds the maximum length of ${maxUrlLength}`};if(authorityOf(input).split(``).some(char=>isAuthorityAmbiguity(char)))return{ok:!1,reason:`ambiguous-authority`,message:`URL authority contains a backslash or a control character`};let url;try{url=new URL(input)}catch{return{ok:!1,reason:`invalid-url`,message:`invalid URL: ${redactUrlSecrets(input)}`}}return ALLOWED_PROTOCOLS.has(url.protocol)?url.username.length>0||url.password.length>0?{ok:!1,reason:`credentials-not-allowed`,message:`credentials in URLs are not allowed`}:{ok:!0,url}:{ok:!1,reason:`scheme-not-allowed`,message:`unsupported URL scheme "${url.protocol}" (only http and https are allowed)`}};return{screen,verify:async input=>{let screened=screen(input);if(!screened.ok)return screened;let{url}=screened,literal=isIpLiteral(url.hostname),addresses;if(literal)addresses=[stripBrackets(url.hostname)];else try{addresses=await resolve(url.hostname)}catch(error){return{ok:!1,reason:`resolve-failed`,message:`failed to resolve host: ${url.hostname} (${String(error)})`}}if(addresses.length===0)return{ok:!1,reason:`no-address`,message:`host resolved to no addresses: ${url.hostname}`};if(allowed.has(url.hostname.toLowerCase()))return screened;let pools=literal?[]:[...manualRanges,...await(detected??=detectSyntheticResolver(resolve,table))],offender=addresses.find(address=>!isAcceptableAnswer(address,table,pools));return offender===void 0?screened:{ok:!1,reason:`private-address`,message:`host resolves to a non-public address (${offender}): ${url.hostname}`}},isPublicAddress:address=>isPublicAddress(address,table)}}const SELECT_TRUNCATION_HINT=`结果被截断:请减小 limit,或提高 maxContentChars 后再取。`;function tailOf(notice,truncated){return notice!==void 0&&notice.length>0?notice:truncated?SELECT_TRUNCATION_HINT:``}function normalizeBudget(budgetBytes){return!Number.isFinite(budgetBytes)||budgetBytes<1?2e5:Math.floor(budgetBytes)}function capText(text,budgetBytes,recovery){let budget=normalizeBudget(budgetBytes);if(Buffer.byteLength(text,`utf8`)<=budget)return{text,truncated:!1,notice:``};let headBytes=Math.min(Math.max(1,Math.floor(budget*2/3)),budget-1),tailBytes=budget-headBytes,retainer=new TextRetainer({kind:`headTail`,headBytes,tailBytes});retainer.push(text);let kept=retainer.finish();
23
21
  /* v8 ignore next 3 */
24
22
  if(!kept.truncated)return{text:kept.text,truncated:!1,notice:``};let notice=formatRetentionNotice({scope:`body`,strategy:`headTail`,unit:`bytes`,limit:{head:headBytes,tail:tailBytes},kept:Buffer.byteLength(kept.text,`utf8`),omitted:kept.omittedBytes},()=>recovery);return{text:kept.text,truncated:kept.truncated,notice}}function renderLocate(value){let body=value.matches.length===0?`no matches`:value.matches.map(item=>{let lines=[`<${item.tag}> ${item.text}`,` css: ${item.cssSelector}`,` xpath: ${item.xpathSelector}`];if(Object.keys(item.attributes).length>0&&lines.push(` attributes: ${JSON.stringify(item.attributes)}`),item.fullCssSelector.length>0&&item.fullCssSelector!==item.cssSelector&&lines.push(` full css: ${item.fullCssSelector}`),item.fullXpathSelector.length>0&&item.fullXpathSelector!==item.xpathSelector&&lines.push(` full xpath: ${item.fullXpathSelector}`),item.ancestors.length>0){let chain=item.ancestors.map(ancestor=>{let attrs=Object.keys(ancestor.attributes).length>0?` ${JSON.stringify(ancestor.attributes)}`:``;return`<${ancestor.tag}>${attrs}`}).join(` < `);lines.push(` ancestors: ${chain}`)}return lines.join(`
25
23
  `)}).join(`
@@ -34,7 +32,7 @@ if(!kept.truncated)return{text:kept.text,truncated:!1,notice:``};let notice=form
34
32
  `),metadata=jsonRecordOf(raw.metadata);return{url:textOf$2(raw,`url`),title:textOf$2(raw,`title`),content:capped.text,truncated:boolOf$1(raw,`truncated`)||capped.truncated,notice,...metadata===void 0?{}:{metadata}}},presentCall:args=>({card:`generic`,title:args.sessionId,kind:`fetch`})})}function createSessionActTool(deps){let{sidecar,settings}=deps;return defineTool({name:`scrapling_session_act`,description:`在已开会话的当前页上按顺序执行结构化动作(点击、输入、等待等)。只接受白名单动作,不执行任意 JavaScript;首个失败会点名动作序号。`,parameters:{sessionId:{type:`string`,required:!0,description:`浏览器会话 id。`},actions:{type:`json`,required:!0,description:`动作数组,按顺序执行。`},slowly:{type:`boolean`,description:`每个动作之间等 100ms。`},maxActions:{type:`integer`,description:`最多多少个动作,默认 20,上限 50。`},timeoutMs:{type:`integer`,description:`单个动作的超时(毫秒)。`}},output:{schema:{type:`object`,additionalProperties:!1,properties:{completed:{type:`integer`,required:!0},finalUrl:{type:`string`,required:!0},title:{type:`string`,required:!0}}},render:(_args,value)=>[{type:`text`,text:`completed ${value.completed} action(s); now at ${value.finalUrl} (${value.title})`}],presentationMeta:(_args,value)=>({count:value.completed})},timeoutMs:settings.timeoutMs,isConcurrencySafe:()=>!1,async execute(args,exec){let raw=await callSidecar(sidecar,`session.act`,{sessionId:args.sessionId,actions:args.actions,slowly:args.slowly===!0,maxActions:args.maxActions??20,timeoutMs:args.timeoutMs??settings.timeoutMs},{signal:exec.signal,timeoutMs:settings.timeoutMs});return{completed:intOf$1(raw,`completed`),finalUrl:textOf$2(raw,`finalUrl`),title:textOf$2(raw,`title`)}},presentCall:args=>({card:`generic`,title:args.sessionId,kind:`search`})})}function createDownloadTool(deps){let{sidecar,settings}=deps;return defineTool({name:`scrapling_download`,description:`把一个 URL 的字节写进插件的下载目录,返回路径、大小与 sha256。不覆盖已有文件;不返回文件内容。`,parameters:{url:{type:`string`,required:!0,description:`要下载的 HTTP(S) URL。`},filename:{type:`string`,description:`保存的文件名;留空从 URL 推导。`},maxBytes:{type:`integer`,description:`本次下载的字节上限。`},headers:{type:`json`,description:`请求头(对象)。`},cookies:{type:`json`,description:`Cookie 键值对(对象)。`},impersonate:{type:`string`,description:`TLS 指纹伪装目标。`},useBrowser:{type:`boolean`,description:`用真实浏览器取字节,默认 false。`}},output:{schema:{type:`object`,additionalProperties:!1,properties:{path:{type:`string`,required:!0},bytes:{type:`integer`,required:!0},sha256:{type:`string`,required:!0},contentType:{type:`string`,required:!0},status:{type:`integer`,required:!0}}},render:(_args,value)=>[{type:`text`,text:`saved ${value.bytes}B to ${value.path}\nsha256: ${value.sha256}\ncontent-type: ${value.contentType||`(unknown)`} (HTTP ${value.status})`}],presentationMeta:(_args,value)=>({url:value.path,statusCode:value.status})},timeoutMs:settings.timeoutMs,isConcurrencySafe:()=>!0,async execute(args,exec){let requested=typeof args.maxBytes==`number`?args.maxBytes:settings.downloadMaxBytes,maxBytes=Math.min(requested,settings.downloadMaxBytes),raw=await callSidecar(sidecar,`download`,{url:args.url,filename:args.filename??``,maxBytes,headers:args.headers??null,cookies:args.cookies??null,impersonate:args.impersonate??``,useBrowser:args.useBrowser===!0,timeoutSeconds:settings.requestTimeoutSeconds,deployment:{downloadDir:settings.downloadDir,downloadMaxBytes:settings.downloadMaxBytes}},{signal:exec.signal,timeoutMs:settings.timeoutMs});return{path:textOf$2(raw,`path`),bytes:intOf$1(raw,`bytes`),sha256:textOf$2(raw,`sha256`),contentType:textOf$2(raw,`contentType`),status:intOf$1(raw,`status`)}},presentCall:args=>({card:`generic`,title:args.url,kind:`fetch`})})}function createScreenshotTool(deps){let{sidecar,settings,attachments}=deps;return defineTool({name:`scrapling_screenshot`,description:`对已开会话的当前页或页内单个元素截图,作为图片附件返回。截图不经文本清洗,可能包含页面上的敏感视觉信息。`,parameters:{sessionId:{type:`string`,required:!0,description:`浏览器会话 id。`},imageType:{type:`string`,enum:[`png`,`jpeg`],description:`图片格式,默认 png。`},fullPage:{type:`boolean`,description:`截整页,默认 false。`},quality:{type:`integer`,description:`JPEG 质量 1–100;PNG 不可用。`},selector:{type:`string`,description:`只截这一个元素;与 fullPage 互斥。`},timeoutMs:{type:`integer`,description:`截图超时(毫秒)。`}},output:{schema:{type:`object`,additionalProperties:!1,properties:{url:{type:`string`,required:!0},mediaType:{type:`string`,required:!0},width:{type:`integer`,required:!0},height:{type:`integer`,required:!0},attachment:{type:`json`,required:!0}}},render:(_args,value)=>[{type:`image`,attachment:value.attachment},{type:`text`,text:`screenshot of ${value.url} (${value.width}x${value.height}, ${value.mediaType})`}],presentationMeta:(_args,value)=>({url:value.url})},timeoutMs:settings.timeoutMs,isConcurrencySafe:()=>!1,async execute(args,exec){if(attachments===void 0)throw new SidecarError(`ATTACHMENT_UNAVAILABLE`,`no attachment service is mounted`);let raw=await callSidecar(sidecar,`screenshot`,{sessionId:args.sessionId,imageType:args.imageType??`png`,fullPage:args.fullPage===!0,quality:args.quality??null,selector:args.selector??null,timeoutMs:args.timeoutMs??settings.timeoutMs},{signal:exec.signal,timeoutMs:settings.timeoutMs}),mediaType=textOf$2(raw,`mediaType`);if(mediaType!==`image/png`&&mediaType!==`image/jpeg`)throw new SidecarError(`SIDECAR_REQUEST_FAILED`,`unexpected media type: ${mediaType}`);let data=Buffer.from(textOf$2(raw,`base64`),`base64`),attachment=jsonOf(await attachments.saveImage({data:new Uint8Array(data),mediaType,name:mediaType===`image/png`?`screenshot.png`:`screenshot.jpg`}));return{url:textOf$2(raw,`url`),mediaType,width:intOf$1(raw,`width`),height:intOf$1(raw,`height`),attachment}},presentCall:args=>({card:`generic`,title:args.sessionId,kind:`fetch`})})}const HIDDEN_TOOLS=/* @__PURE__ */ new Set([`scrapling_answer`]);var McpServerError=class extends Error{code;constructor(code,message){super(message),this.name=`McpServerError`,this.code=code}};function mcpRawName(name){return name.startsWith(`scrapling_`)?name.slice(10):name}function mcpToolEntries(tools,search){let entries=tools.filter(tool=>!HIDDEN_TOOLS.has(tool.name)).map(tool=>({name:mcpRawName(tool.name),definition:tool.definition}));return search!==void 0&&entries.push({name:`search`,definition:search}),entries}function createMcpImageSink(){let stored=/* @__PURE__ */ new Map,seq=0;return{saveImage:input=>{seq+=1;let id=`mcp-${String(seq)}`;return stored.set(id,{data:Buffer.from(input.data).toString(`base64`),mimeType:input.mediaType}),Promise.resolve({id})},take:id=>{let found=stored.get(id);return stored.delete(id),found}}}function fieldOf(block,key){return e(block)?block[key]:void 0}function projectBlocks(blocks,sink){return blocks.map(block=>{let kind=fieldOf(block,`type`),text=fieldOf(block,`text`);if(kind===`text`&&typeof text==`string`)return{type:`text`,text};let id=fieldOf(fieldOf(block,`attachment`),`id`);if(kind===`image`&&sink!==void 0&&typeof id==`string`){let stored=sink.take(id);if(stored!==void 0)return{type:`image`,data:stored.data,mimeType:stored.mimeType}}return{type:`text`,text:JSON.stringify(block)}})}const SEARCH_PARAMETERS={query:{type:`string`,required:!0,description:`要检索的词。`},maxResults:{type:`integer`,description:`返回来源的条数上限;不给就用部署设置的那一档。`}},SEARCH_OUTPUT_SCHEMA={type:`object`,additionalProperties:!1,properties:{query:{type:`string`,required:!0},count:{type:`integer`,required:!0},truncated:{type:`boolean`,required:!0},sources:{type:`array`,required:!0,items:{type:`object`,additionalProperties:!1,properties:{url:{type:`string`,required:!0},title:{type:`string`,required:!0},snippet:{type:`string`,required:!0}}}},content:{type:`string`,required:!0}}};function textOf$1(value){return typeof value==`string`?value:``}function normalizeSearch(query,raw){let sources=e(raw)&&Array.isArray(raw.sources)?raw.sources:[];return{query,count:sources.length,truncated:e(raw)?raw.truncated===!0:!1,sources:sources.map(item=>({url:textOf$1(fieldOf(item,`url`)),title:textOf$1(fieldOf(item,`title`)),snippet:textOf$1(fieldOf(item,`snippet`))})),content:e(raw)?textOf$1(raw.content):``}}function renderSearch(value){let lines=[`scrapling search: ${value.query}`];value.sources.length===0&&lines.push(`(no sources passed the URL gate)`);for(let[index,item]of value.sources.entries()){let label=item.title.length>0?item.title:item.url;lines.push(`${String(index+1)}. ${label}`),item.snippet.length>0&&lines.push(` ${item.snippet}`)}return value.truncated&&lines.push(`(结果被上限截断)`),lines.join(`
35
33
  `)}function mcpSearchTool(provider){return defineTool({name:`search`,description:`用本插件的搜索发现层检索一次,返回可引用的来源与已渲染正文。`,parameters:SEARCH_PARAMETERS,output:{schema:SEARCH_OUTPUT_SCHEMA,render:(_args,value)=>[{type:`text`,text:renderSearch(value)}]},async execute(args,exec){let{maxResults,query}=args;return normalizeSearch(query,await provider.search({query,...maxResults===void 0?{}:{maxResults}},exec.signal))}})}async function runEntry(entry,args,signal,sink){let params=args??{};try{let exec={signal},value=jsonOf(await entry.definition.execute(params,exec));return{content:projectBlocks(entry.definition.output.render(params,value),sink)}}catch(error){return{isError:!0,content:[{type:`text`,text:String(error)}]}}}function pathOf(url){
36
34
  /* v8 ignore next 2 —— 兜的是类型上的 undefined,不是运行期到得了的一支。 */
37
- return(url??``).split(`?`)[0]??``}function oversized(req){let length=Number(req.headers[`content-length`]);return Number.isFinite(length)&&length>1048576}function authorized(req,token){return token===void 0||req.headers.authorization===`Bearer ${token}`}function refused(res,status,challenge){res.writeHead(status,challenge?{"www-authenticate":`Bearer`}:void 0),res.end()}function listenFailure(error,port,host){return error.code===`EADDRINUSE`?new McpServerError(`MCP_PORT_IN_USE`,`MCP server cannot listen on ${host}:${String(port)} — that port is taken; move it with the mcpPort setting`):new McpServerError(`MCP_SERVER_FAILED`,`MCP server cannot listen on ${host}:${String(port)} — ${error.message}`)}function boundPort(address){if(address===null||typeof address==`string`)throw new McpServerError(`MCP_SERVER_FAILED`,`MCP server did not report a TCP bound address`);return address.port}function isWildcardHost(host){return host===``||host===`0.0.0.0`||host===`::`||host===`[::]`}function isLoopbackHost(host){return host===`localhost`||host===`::1`||host===`[::1]`||host.startsWith(`127.`)}function wildcardNames(){let names=/* @__PURE__ */ new Set([`127.0.0.1`,`localhost`,`[::1]`]);for(let addresses of Object.values(networkInterfaces()))for(let address of addresses??[])address.internal||names.add(address.address.includes(`:`)?`[${address.address}]`:address.address);return[...names]}function endpointNames(host){return isWildcardHost(host)?wildcardNames():isLoopbackHost(host)?[host===`::1`?`[::1]`:host,`localhost`]:[host]}function allowedEndpoints(host,port){let allowedHosts=[...new Set(endpointNames(host))].map(name=>`${name}:${String(port)}`);return{allowedHosts,allowedOrigins:allowedHosts.map(entry=>`http://${entry}`)}}async function listenOn(http,port,host){return new Promise((resolve,reject)=>{http.once(`error`,error=>{reject(listenFailure(error,port,host))}),http.listen(port,host,()=>{resolve(boundPort(http.address()))})})}async function settled(http){return new Promise(resolve=>{http.close(()=>{resolve()}),http.closeAllConnections()})}async function startMcpServer(options){let host=options.host??`127.0.0.1`,bound=0,guard,serverModule=await import(`@modelcontextprotocol/sdk/server/index.js`),types=await import(`@modelcontextprotocol/sdk/types.js`),{StreamableHTTPServerTransport}=await import(`@modelcontextprotocol/sdk/server/streamableHttp.js`);async function handle(request,response){try{let protocol=new serverModule.Server({name:`scrapling`,version:`0.1.4`},{capabilities:{tools:{}}});protocol.setRequestHandler(types.ListToolsRequestSchema,()=>({tools:options.entries.map(entry=>({name:entry.name,description:entry.definition.description,inputSchema:entry.definition.parameters}))})),protocol.setRequestHandler(types.CallToolRequestSchema,async(call,extra)=>{let entry=options.entries.find(item=>item.name===call.params.name);return entry===void 0?{isError:!0,content:[{type:`text`,text:`unknown tool: ${call.params.name}`}]}:runEntry(entry,call.params.arguments,extra.signal,options.imageSink)}),guard??=allowedEndpoints(host,bound);let transport=new StreamableHTTPServerTransport({enableDnsRebindingProtection:!0,allowedHosts:[...guard.allowedHosts],allowedOrigins:[...guard.allowedOrigins]});response.on(`close`,()=>{transport.close(),protocol.close()}),await protocol.connect(transport),await transport.handleRequest(request,response)}catch{
35
+ return(url??``).split(`?`)[0]??``}function oversized(req){let length=Number(req.headers[`content-length`]);return Number.isFinite(length)&&length>1048576}function authorized(req,token){return token===void 0||req.headers.authorization===`Bearer ${token}`}function refused(res,status,challenge){res.writeHead(status,challenge?{"www-authenticate":`Bearer`}:void 0),res.end()}function listenFailure(error,port,host){return error.code===`EADDRINUSE`?new McpServerError(`MCP_PORT_IN_USE`,`MCP server cannot listen on ${host}:${String(port)} — that port is taken; move it with the mcpPort setting`):new McpServerError(`MCP_SERVER_FAILED`,`MCP server cannot listen on ${host}:${String(port)} — ${error.message}`)}function boundPort(address){if(address===null||typeof address==`string`)throw new McpServerError(`MCP_SERVER_FAILED`,`MCP server did not report a TCP bound address`);return address.port}function isWildcardHost(host){return host===``||host===`0.0.0.0`||host===`::`||host===`[::]`}function isLoopbackHost(host){return host===`localhost`||host===`::1`||host===`[::1]`||host.startsWith(`127.`)}function wildcardNames(){let names=/* @__PURE__ */ new Set([`127.0.0.1`,`localhost`,`[::1]`]);for(let addresses of Object.values(networkInterfaces()))for(let address of addresses??[])address.internal||names.add(address.address.includes(`:`)?`[${address.address}]`:address.address);return[...names]}function endpointNames(host){return isWildcardHost(host)?wildcardNames():isLoopbackHost(host)?[host===`::1`?`[::1]`:host,`localhost`]:[host]}function allowedEndpoints(host,port){let allowedHosts=Array.from(new Set(endpointNames(host)),name=>`${name}:${String(port)}`);return{allowedHosts,allowedOrigins:allowedHosts.map(entry=>`http://${entry}`)}}async function listenOn(http,port,host){return new Promise((resolve,reject)=>{http.once(`error`,error=>{reject(listenFailure(error,port,host))}),http.listen(port,host,()=>{resolve(boundPort(http.address()))})})}async function settled(http){return new Promise(resolve=>{http.close(()=>{resolve()}),http.closeAllConnections()})}async function startMcpServer(options){let host=options.host??`127.0.0.1`,bound=0,guard,serverModule=await import(`@modelcontextprotocol/sdk/server/index.js`),types=await import(`@modelcontextprotocol/sdk/types.js`),{StreamableHTTPServerTransport}=await import(`@modelcontextprotocol/sdk/server/streamableHttp.js`);async function handle(request,response){try{let protocol=new serverModule.Server({name:`scrapling`,version:`0.1.5`},{capabilities:{tools:{}}});protocol.setRequestHandler(types.ListToolsRequestSchema,()=>({tools:options.entries.map(entry=>({name:entry.name,description:entry.definition.description,inputSchema:entry.definition.parameters}))})),protocol.setRequestHandler(types.CallToolRequestSchema,async(call,extra)=>{let entry=options.entries.find(item=>item.name===call.params.name);return entry===void 0?{isError:!0,content:[{type:`text`,text:`unknown tool: ${call.params.name}`}]}:runEntry(entry,call.params.arguments,extra.signal,options.imageSink)}),guard??=allowedEndpoints(host,bound);let transport=new StreamableHTTPServerTransport({enableDnsRebindingProtection:!0,allowedHosts:[...guard.allowedHosts],allowedOrigins:[...guard.allowedOrigins]});response.on(`close`,()=>{transport.close(),protocol.close()}),await protocol.connect(transport),await transport.handleRequest(request,response)}catch{
38
36
  /* v8 ignore next 2 —— 到不了的一层:SDK 那两步只回错误响应,不抛。 */
39
37
  refused(response,500,!1)}}function accept(request,response){authorized(request,options.token)?pathOf(request.url)===`/mcp`?oversized(request)?refused(response,413,!1):handle(request,response):refused(response,404,!1):refused(response,401,!0)}let http=createServer((request,response)=>{accept(request,response)}),port=await listenOn(http,options.port,host);return bound=port,options.token===void 0&&process.stderr.write(`[dsh-scrapling] MCP server is listening on ${host}:${String(port)} WITHOUT authentication: any local process can call these tools. Set DSH_SCRAPLING_MCP_TOKEN in the host's environment and restart the host to require a bearer token.\n`),{port,url:mcpUrl(port,host),close:async()=>{await settled(http)}}}function officialMcpHint(enabled){return enabled?`生成接入配置请跑 setup:dsh-scrapling setup --mode official-mcp --accept-risk。official-mcp 直连官方 scrapling-mcp:那 16 个工具不经本插件的 URL 守卫与会话闸门(含 browser_evaluate 的任意 JS),用的是它自己的会话与状态,本插件既不复用也不拦截。`:`official-mcp 未启用:先在部署配置里设 officialMcpEnabled=true,再跑 setup --mode official-mcp --accept-risk。`}function escapePageText(text){return text.replaceAll(/<\s*\/\s*page\s*>/giu,`〔page-close〕`).replaceAll(`§page_end§`,`〔page-end〕`)}function buildAnswerPrompt(request){return`<page url="${request.url.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`)}">\n${escapePageText(request.context)}\n§page_end§\n\n问题:${request.question}`}function methodOf(value,name){let member=i(value,name);return typeof member==`function`?Reflect.apply(member,value,[]):void 0}function routeOf(provider,model){return typeof provider==`string`&&provider.length>0&&typeof model==`string`&&model.length>0?{provider,model}:void 0}function sessionRoute(agent){let config=i(methodOf(i(agent,`session`),`requestHeader`),`config`);return routeOf(i(config,`provider`),i(config,`model`))}function profileRoute(service){let selection=methodOf(service,`currentSelection`);return routeOf(i(selection,`provider`),i(selection,`model`))}function resolveAnswerRoute(override,agent,fallback){let route=override??sessionRoute(agent)??fallback;if(route===void 0)throw new SidecarError(`ANSWER_NO_ROUTE`,`拿不到可用的模型路由:部署没配 answerProvider/answerModel,这次调用又不来自某个会话,profile 也没有默认模型`);return route}function createAnswerer(deps){let{ctx,override,fallback,maxTokens}=deps;return async request=>{let llm=ctx.get(`llm`);if(llm===void 0)throw new SidecarError(`ANSWER_UNAVAILABLE`,`这个 profile 没有 ctx.llm,scrapling_answer 无法调用模型;其余抓取工具不受影响`);let answer=``,finished=!1,route;try{route=resolveAnswerRoute(override,request.agent,fallback);for await(let chunk of llm.stream({provider:route.provider,model:route.model,system:`你是一个网页阅读助手。用户会给你一个问题的原文,以及一个网页的正文。
40
38
  规则:
@@ -60,4 +58,4 @@ sessionId:typeof args.sessionId==`string`?args.sessionId:``,count:e(raw)&&typeof
60
58
  `)}function outputBudgetOf(config,toolName){return toolName===`scrapling_fetch`?config.fetchMaxOutputChars.get():toolName===`scrapling_extract`||toolName===`scrapling_session_read`||toolName===`scrapling_locate`||toolName===`scrapling_links`?config.extractMaxOutputChars.get():toolName===`scrapling_capture_xhr`?config.xhrMaxOutputChars.get():config.renderMaxOutputChars.get()}const NONE=`none`;function planTools(flags,capabilities,jobsReady=!1,attachmentsReady=!0,sessionStateReady=!1){let ready=[],skipped=[],satisfied=requires=>capabilities===void 0||!capabilities.scrapling?`scrapling-missing`:requires===`browser`&&!capabilities.browser?`browser-missing`:requires===`jobs`&&!jobsReady?`jobs-unavailable`:requires===SESSION_STATE_REQUIREMENT&&!sessionStateReady?`session-state-unavailable`:NONE;for(let spec of TOOL_SPECS){let missing=satisfied(spec.requires),enabled=flags[spec.flag];missing===NONE?enabled?spec.name===`scrapling_screenshot`&&!attachmentsReady?skipped.push({name:spec.name,reason:`attachments-missing`}):ready.push(spec.name):skipped.push({name:spec.name,reason:`disabled`}):skipped.push({name:spec.name,reason:missing})}return{ready,skipped}}function resolveDataDir(configured){let trimmed=configured.trim();return trimmed.length>0?path.resolve(trimmed):path.join(os.homedir(),`.dsh-scrapling`)}function resolvePythonBin(configured,packageRoot,dataDir=``){let runtime=resolveRuntime({pythonBin:configured,dataDir,repoRoot:packageRoot});return runtime.via===`repo`?{path:runtime.pythonPath,via:`_env/.venv`}:runtime.via===`path`?{path:runtime.pythonPath,via:`PATH`}:{path:runtime.pythonPath,via:runtime.via}}async function ensureDataDir(dir){await mkdir(dir,{recursive:!0})}function handleDataDirFailure(error,dataDir,failFast){let detail=`dataDir 指向的 ${dataDir} 建不出来:${String(error)}。`;if(failFast)throw new SidecarError(`CONFIG_INVALID`,`${detail}插件已拒绝加载;把 dataDir 指向一个可写的目录,或把 failFastOnMissingPython 关掉降级运行。`);return`[dsh-scrapling] ${detail}本插件不注册任何工具。`}function createCrawlEventRouter(){let sinks=/* @__PURE__ */ new Map;return{register:(crawlId,sink)=>{sinks.set(crawlId,sink)},forget:sink=>{for(let[crawlId,registered]of sinks)registered===sink&&sinks.delete(crawlId)},route:(crawlId,text)=>{sinks.get(crawlId)?.append(`${text}\n`)}}}function sinkOf(job,signal,router){let sink={append:text=>{job.append(text)},progress:line=>{job.updateProgress(line)},signal,track:crawlId=>{router.register(crawlId,sink)}};return sink}function probeJobsReady(jobs){if(typeof jobs!=`object`||!jobs)return!1;let face=jobs;return typeof face.attachController==`function`&&typeof face.start==`function`}function startUnderCrawlController(jobs,spec){let detach=jobs.attachController(`scrapling: crawl`);try{return jobs.start(spec)}finally{detach()}}function crawlFailureDetail(error){return error instanceof SidecarError?sidecarErrorWithCode(error.code,error.message,{cause:error},error.details).message:String(error)}function startCrawlJob(ctx,router,label,run){let jobs=ctx.get(`jobs`);if(jobs===void 0)return Promise.reject(new SidecarError(`JOBS_UNAVAILABLE`,`这个 profile 没有作业后端(ctx.jobs 不可用),scrapling_crawl 需要它来跑后台作业。本插件在注册时已按能力跳过 crawl,走到这里说明注册之后后端被卸载了。单页抓取(scrapling_fetch / extract / render)不受影响。`));try{return Promise.resolve(startUnderCrawlController(jobs,{kind:`scrapling`,label,run:job=>{let controller=new AbortController,sink=sinkOf(job,controller.signal,router);return controller.signal.addEventListener(`abort`,()=>{router.forget(sink)},{once:!0}),{cancel:()=>{controller.abort()},done:(async()=>{try{return await run(sink),{status:`completed`}}catch(error){return controller.signal.aborted?{status:`killed`,detail:`cancelled`}:{status:`failed`,detail:crawlFailureDetail(error)}}finally{router.forget(sink)}})()}}}))}catch(error){return Promise.reject(new SidecarError(`JOBS_UNAVAILABLE`,`作业后端在起作业那一刻抛错:${String(error)}。scrapling_crawl 需要一个能 attach controller 的作业后端;单页抓取(scrapling_fetch / extract / render)不受影响。`))}}function probeFailure(error){return`[dsh-scrapling] 未能启动 Python sidecar:${String(error)}`}function proxyOf(config){return config.proxyUrl.get().trim()}function createUrlGate(config){let nat64Prefixes=config.nat64Prefixes.get().split(`,`).map(item=>item.trim()).filter(item=>item.length>0),allowHosts=config.allowedHosts.get().split(`,`).map(item=>item.trim()).filter(item=>item.length>0),policy=(()=>{try{let syntheticRanges=config.syntheticDnsRanges.get().split(`,`).map(item=>item.trim()).filter(item=>item.length>0);return createUrlPolicy({maxUrlLength:config.maxUrlLength,...nat64Prefixes.length>0?{nat64Prefixes}:{},...allowHosts.length>0?{allowHosts}:{},...syntheticRanges.length>0?{syntheticRanges}:{}})}catch(error){throw new SidecarError(`CONFIG_INVALID`,`nat64Prefixes 配置非法:${String(error)}。每项须形如 <IPv6 前缀>/<32|40|48|56|64|96>,逗号分隔。插件已拒绝加载,以免把藏在 IPv6 里的私网 IPv4 当成公网放行。`)}})();return async url=>{let verdict=await policy.verify(url);if(!verdict.ok)throw new SidecarError(`URL_BLOCKED`,`${redactUrlSecrets(url)}: ${verdict.message}`);return verdict.url.toString()}}function registerFetchProvider(ctx,sidecar,config){let provider=createWebFetchProvider({sidecar,maxOutputBytes:config.fetchMaxOutputChars.get(),timeoutMs:config.fetchTimeoutMs.get()});provider.available()?(ctx.web.registerFetchProvider(provider),ctx.logger.info(`[dsh-scrapling] 已注册 ctx.web fetch provider(id=${PROVIDER_ID})。内置 web_fetch 要真正走它,部署配置里还需写 fetchProvider: "scrapling"。`)):ctx.logger.warn(`[dsh-scrapling] 跳过注册 fetch provider:sidecar 尚未可用`)}function searchProviderOf(config,sidecar,urlGate){return createWebSearchProvider({sidecar,backend:config.searchBackend.get(),apiKey:config.tavilyApiKey.get(),braveApiKey:config.braveApiKey.get(),serperApiKey:config.serperApiKey.get(),apiEndpoint:config.tavilyApiEndpoint,bingEndpoint:config.bingEndpoint,braveEndpoint:`https://api.search.brave.com/res/v1/web/search`,serperEndpoint:`https://google.serper.dev/search`,duckduckgoEndpoint:config.duckduckgoEndpoint,searxngEndpoint:config.searxngEndpoint.get(),publicFallback:config.searchPublicFallback.get(),renderTopN:config.searchRenderTopN,maxOutputBytes:config.fetchMaxOutputChars.get(),timeoutMs:config.fetchTimeoutMs.get(),urlGate})}async function startMcpSurface(args){let{config,ctx,depsFor,env,plan,search}=args,sink=createMcpImageSink(),ready=new Set(plan.ready),tools=[];for(let spec of TOOL_SPECS)ready.has(spec.name)&&tools.push({name:spec.name,definition:spec.build({...depsFor(spec),attachments:sink})});let entries=mcpToolEntries(tools,search.available()?mcpSearchTool(search):void 0),token=(env.DSH_SCRAPLING_MCP_TOKEN??``).trim(),handle=await startMcpServer({port:config.mcpPort,entries,imageSink:sink,...token.length>0?{token}:{}});ctx.effect(()=>()=>handle.close());let notice=token.length>0?` · 需要 bearer token`:` · 无 token,只绑回环`;return ctx.logger.info(`[dsh-scrapling] MCP server:${handle.url} · ${String(entries.length)} 个工具${notice}`),handle}async function registerSurface(args){let{config,ctx,depsFor,plan}=args;if(config.integrationMode===`mcp`){await startMcpSurface(args);return}if(config.integrationMode===`official-mcp`){ctx.logger.info(`[dsh-scrapling] integrationMode=official-mcp:不注册原生工具,也不起本插件的 MCP server。${officialMcpHint(config.officialMcpEnabled)}`);return}let ready=new Set(plan.ready);for(let spec of TOOL_SPECS)ready.has(spec.name)&&ctx.tools.register(spec.build(depsFor(spec)))}function registerSearchProvider(ctx,provider,backend){provider.available()?(ctx.web.registerSearchProvider(provider),ctx.logger.info(`[dsh-scrapling] 已注册 ctx.web search provider(id=${SEARCH_PROVIDER_ID}, backend=${backend})。内置 web_search 要真正走它,部署配置里还需写 searchProvider: "scrapling"。`)):ctx.logger.warn(`[dsh-scrapling] 跳过注册 search provider:sidecar 不可用,或 auto 后端没有任何可用发现路径(未配 key / SearXNG,且 searchPublicFallback 为 false)`)}function baseSettingsOf(config,dataDir){return{downloadDir:path.join(dataDir,`downloads`),downloadMaxBytes:config.downloadMaxBytes,extractionType:config.extractionType.get(),mainContentOnly:config.mainContentOnly.get(),timeoutMs:config.fetchTimeoutMs.get(),headless:config.headless.get(),networkIdle:config.networkIdle.get(),pageTimeoutMs:config.fetchTimeoutMs.get(),waitSelectorState:config.waitSelectorState.get(),pierceShadow:config.pierceShadow.get(),requestTimeoutSeconds:config.requestTimeoutSeconds,blockAds:config.blockAds.get(),crawlMaxItems:config.crawlMaxItems.get(),crawlMaxRuntimeSeconds:config.crawlMaxRuntimeSeconds,browserExecutablePath:config.browserExecutablePath,browserCdpUrl:config.browserCdpUrl,browserInitScript:config.browserInitScript,browserRealChrome:config.browserRealChrome,browserDnsOverHttps:config.browserDnsOverHttps,recordRequests:config.recordRequests,maxRecordedRequests:config.maxRecordedRequests,sessionStateDir:config.sessionStateDir,adaptiveStorage:config.adaptiveStorage,redisUrl:config.redisUrl,crawlRespectRobots:config.crawlRespectRobots,crawlDownloadDelayMs:config.crawlDownloadDelayMs,crawlConcurrentRequests:config.crawlConcurrentRequests,crawlAutothrottle:config.crawlAutothrottle,crawlStrategy:config.crawlStrategy,crawlCheckpointDir:config.crawlCheckpointDir,allowWriteMethods:config.allowWriteMethods,stripInlineImages:config.stripInlineImages.get()}}function makeSidecar(options){let{ctx,config,python,urlGate,crawlEvents}=options;return createSidecar(ctx,{pythonBin:python.path,bridgePath:path.join(import.meta.dirname,`py`,`bridge.py`),cwd:resolveDataDir(config.dataDir.get()),handshakeTimeoutMs:config.sidecarHandshakeTimeoutMs.get(),requestTimeoutMs:config.fetchTimeoutMs.get(),graceMs:config.sidecarGraceMs.get(),urlGate,env:{DSH_SCRAPLING_ALLOWED_HOSTS:config.allowedHosts.get(),DSH_SCRAPLING_NAT64_PREFIXES:config.nat64Prefixes.get(),DSH_SCRAPLING_SYNTHETIC_RANGES:config.syntheticDnsRanges.get(),DSH_SCRAPLING_PROXY:proxyOf(config),DSH_SCRAPLING_PROXY_BYPASS:config.proxyBypass.get(),DSH_SCRAPLING_ALLOW_WRITE_METHODS:config.allowWriteMethods?`1`:`0`,DSH_SCRAPLING_ALLOW_BROWSER_ACTIONS:config.allowBrowserActions?`1`:`0`,DSH_SCRAPLING_ALLOW_FILE_DOWNLOADS:config.allowFileDownloads?`1`:`0`},log:line=>{ctx.logger.debug(line)},onEvent:frame=>{
61
59
  /* v8 ignore start —— 非字符串兜底到不了:py/crawl.py 每帧都带 text 与 crawlId。
62
60
  留着只为防对端改协议时打挂宿主(那时退回整帧 JSON 也还读得懂)。 */
63
- let text=typeof frame.text==`string`?frame.text:JSON.stringify(frame);crawlEvents.route(typeof frame.crawlId==`string`?frame.crawlId:``,text)}})}function warnJobsUnavailable(ctx,plan){plan.skipped.some(item=>item.reason===`jobs-unavailable`)&&ctx.logger.warn("[dsh-scrapling] scrapling_crawl 不注册:这个 profile 的作业后端没有 controller 附着。修法是在 profile 的 cordis.patch.yml 里显式启用 host 层的 tool-jobs:`- id: tool-jobs` / ` name: '@deepseek-ai/dsh-tool-jobs'` / ` disabled: false`,改完重启宿主。其余工具不受影响。")}function warnSessionStateUnavailable(ctx,plan){plan.skipped.some(item=>item.reason===`session-state-unavailable`)&&ctx.logger.warn(`[dsh-scrapling] scrapling_session_state_save/_load 不注册:sessionStateDir 未配置。在设置卡里填一个可写目录(例如 ~/.dsh-scrapling/sessions),或留空就维持这一档 ——它会同时保存 cookie / localStorage / IndexedDB。其余会话工具不受影响。`)}function warnScraplingMissing(ctx,plan,python){plan.skipped.some(item=>item.reason===`scrapling-missing`)&&ctx.logger.warn(`[dsh-scrapling] 选中的解释器 ${python.path} 里没有可用的 Scrapling:装上它(pip install "scrapling[rag]>=0.5,<0.6"),或把 pythonBin 指向装了它的解释器。`)}async function apply(ctx,config){ctx.effect(()=>ctx.settings.configure({auto:!1},ctx.fiber),`scrapling: settings page`);let flags=snapshotFlags(config),dataDir=resolveDataDir(config.dataDir.get()),python=resolvePythonBin(config.pythonBin.get(),import.meta.dirname,dataDir);ctx.logger.info(`[dsh-scrapling] Python 解释器:${python.path}(${python.via})`);let urlGate=createUrlGate(config),crawlEvents=createCrawlEventRouter();try{await ensureDataDir(dataDir)}catch(error){ctx.logger.warn(handleDataDirFailure(error,dataDir,config.failFastOnMissingPython.get()));return}installRuntimeRemote(ctx,{dataDir,repoRoot:import.meta.dirname,pythonBin:config.pythonBin.get(),io:defaultInstallerIO,jobsOf:()=>ctx.get(`jobs`),installPackFn:installCapabilityPack})||ctx.logger.warn(`[dsh-scrapling] 运行环境远程面未注册:当前上下文没有服务注册口`);let sidecar=makeSidecar({ctx,config,python,urlGate,crawlEvents}),disposeSidecar=()=>sidecar.dispose();ctx.effect(()=>disposeSidecar);let capabilities;try{capabilities=await sidecar.ensureStarted()}catch(error){if(config.failFastOnMissingPython.get())throw error;ctx.logger.warn(probeFailure(error))}let jobsReady=probeJobsReady(ctx.get(`jobs`)),attachments=ctx.get(`attachments`),plan=planTools(flags,capabilities,jobsReady,attachments!==void 0,config.sessionStateDir.trim().length>0);for(let item of plan.skipped)item.reason!==`disabled`&&ctx.logger.warn(`[dsh-scrapling] ${item.name} 不注册:${item.reason}`);warnScraplingMissing(ctx,plan,python),warnJobsUnavailable(ctx,plan),warnSessionStateUnavailable(ctx,plan);let startJob=(label,run)=>startCrawlJob(ctx,crawlEvents,label,run),answerProvider=config.answerProvider.get().trim(),answerModel=config.answerModel.get().trim(),defaultSelection=profileRoute(ctx.get(`agentDefaultModel`)),answer=createAnswerer({ctx,override:answerProvider.length>0&&answerModel.length>0?{provider:answerProvider,model:answerModel}:void 0,fallback:defaultSelection,maxTokens:config.answerMaxTokens.get()}),baseSettings=baseSettingsOf(config,dataDir),searchProvider=searchProviderOf(config,sidecar,urlGate);await registerSurface({ctx,config,plan,depsFor:spec=>({sidecar,settings:{...baseSettings,maxOutputBytes:outputBudgetOf(config,spec.name)},startCrawlJob:startJob,answer,attachments}),search:searchProvider,env:process.env}),ctx.effect(()=>ctx.systemPrompt.section({name:`scrapling-usage`,order:ctx.systemPrompt.getSectionOrder(`TOOL_WEB_FETCH`),text:({scope})=>guidanceFor(snapshotFlags(config),tool=>ctx.tools.get(tool,scope)!==void 0)}),`scrapling: system prompt guidance`),config.provideWebFetch.get()&&registerFetchProvider(ctx,sidecar,config),config.provideWebSearch.get()&&registerSearchProvider(ctx,searchProvider,config.searchBackend.get()),ctx.logger.info(`[dsh-scrapling] 能力 ${JSON.stringify(capabilities??null)};注册 ${plan.ready.length}/${TOOL_SPECS.length}:${plan.ready.join(`, `)||`(none)`}`)}export{configSchema as Config,TOOL_SPECS,apply,crawlFailureDetail,createCrawlEventRouter,createUrlGate,guidanceFor,inject,name,outputBudgetOf,planTools,resolveDataDir,resolvePythonBin,snapshotFlags,startMcpSurface};
61
+ let text=typeof frame.text==`string`?frame.text:JSON.stringify(frame);crawlEvents.route(typeof frame.crawlId==`string`?frame.crawlId:``,text)}})}function warnJobsUnavailable(ctx,plan){plan.skipped.some(item=>item.reason===`jobs-unavailable`)&&ctx.logger.warn("[dsh-scrapling] scrapling_crawl 不注册:这个 profile 的作业后端没有 controller 附着。修法是在 profile 的 cordis.patch.yml 里显式启用 host 层的 tool-jobs:`- id: tool-jobs` / ` name: '@deepseek-ai/dsh-tool-jobs'` / ` disabled: false`,改完重启宿主。其余工具不受影响。")}function warnSessionStateUnavailable(ctx,plan){plan.skipped.some(item=>item.reason===`session-state-unavailable`)&&ctx.logger.warn(`[dsh-scrapling] scrapling_session_state_save/_load 不注册:sessionStateDir 未配置。在设置卡里填一个可写目录(例如 ~/.dsh-scrapling/sessions),或留空就维持这一档 ——它会同时保存 cookie / localStorage / IndexedDB。其余会话工具不受影响。`)}function warnScraplingMissing(ctx,plan,python){plan.skipped.some(item=>item.reason===`scrapling-missing`)&&ctx.logger.warn(`[dsh-scrapling] 选中的解释器 ${python.path} 里没有可用的 Scrapling:装上它(pip install "scrapling[rag]>=0.5,<0.6"),或把 pythonBin 指向装了它的解释器。`)}async function apply(ctx,config){ctx.effect(()=>ctx.settings.configure({auto:!1},ctx.fiber),`scrapling: settings page`);let flags=snapshotFlags(config),dataDir=resolveDataDir(config.dataDir.get()),python=resolvePythonBin(config.pythonBin.get(),import.meta.dirname,dataDir);ctx.logger.info(`[dsh-scrapling] Python 解释器:${python.path}(${python.via})`);let urlGate=createUrlGate(config),crawlEvents=createCrawlEventRouter();try{await ensureDataDir(dataDir)}catch(error){ctx.logger.warn(handleDataDirFailure(error,dataDir,config.failFastOnMissingPython.get()));return}installRuntimeRemote(ctx,{dataDir,repoRoot:import.meta.dirname,pythonBin:config.pythonBin.get(),io:defaultInstallerIO,jobsOf:()=>ctx.get(`jobs`),installPackFn:installCapabilityPack})||ctx.logger.warn(`[dsh-scrapling] 运行环境远程面未注册:当前上下文没有服务注册口`);let sidecar=makeSidecar({ctx,config,python,urlGate,crawlEvents}),disposeSidecar=()=>sidecar.dispose();ctx.effect(()=>disposeSidecar);let capabilities;try{capabilities=await sidecar.ensureStarted()}catch(error){if(config.failFastOnMissingPython.get())throw error;ctx.logger.warn(probeFailure(error))}let jobsReady=probeJobsReady(ctx.get(`jobs`)),attachments=ctx.get(`attachments`),plan=planTools(flags,capabilities,jobsReady,attachments!==void 0,config.sessionStateDir.trim().length>0);for(let item of plan.skipped)item.reason!==`disabled`&&ctx.logger.warn(`[dsh-scrapling] ${item.name} 不注册:${item.reason}`);warnScraplingMissing(ctx,plan,python),warnJobsUnavailable(ctx,plan),warnSessionStateUnavailable(ctx,plan);let startJob=(label,run)=>startCrawlJob(ctx,crawlEvents,label,run),answerProvider=config.answerProvider.get().trim(),answerModel=config.answerModel.get().trim(),defaultSelection=profileRoute(ctx.get(`agentDefaultModel`)),answer=createAnswerer({ctx,override:answerProvider.length>0&&answerModel.length>0?{provider:answerProvider,model:answerModel}:void 0,fallback:defaultSelection,maxTokens:config.answerMaxTokens.get()}),baseSettings=baseSettingsOf(config,dataDir),searchProvider=searchProviderOf(config,sidecar,urlGate);await registerSurface({ctx,config,plan,depsFor:spec=>({sidecar,settings:{...baseSettings,maxOutputBytes:outputBudgetOf(config,spec.name)},startCrawlJob:startJob,answer,attachments}),search:searchProvider,env:process.env}),ctx.effect(()=>ctx.systemPrompt.section({name:`scrapling-usage`,order:ctx.systemPrompt.getSectionOrder(`TOOL_WEB_FETCH`),text:({scope,toolSet})=>guidanceFor(snapshotFlags(config),tool=>toolSet===void 0?ctx.tools.get(tool,scope)!==void 0:toolSet.view(scope).has(tool))}),`scrapling: system prompt guidance`),config.provideWebFetch.get()&&registerFetchProvider(ctx,sidecar,config),config.provideWebSearch.get()&&registerSearchProvider(ctx,searchProvider,config.searchBackend.get()),ctx.logger.info(`[dsh-scrapling] 能力 ${JSON.stringify(capabilities??null)};注册 ${plan.ready.length}/${TOOL_SPECS.length}:${plan.ready.join(`, `)||`(none)`}`)}export{configSchema as Config,TOOL_SPECS,apply,crawlFailureDetail,createCrawlEventRouter,createUrlGate,guidanceFor,inject,name,outputBudgetOf,planTools,resolveDataDir,resolvePythonBin,snapshotFlags,startMcpSurface};
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Scrapling web scraping",
4
+ "description": "Fetches and extracts web pages with self-healing selectors, browser rendering, session state and background crawling, driven by one resident Python process.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Scrapling 网页抓取",
4
+ "description": "静态与浏览器抓取、CSS/XPath 结构化抽取、选择器自愈、会话登录态与后台爬虫,由一个常驻 Python 进程驱动。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jayyuen66/dsh-scrapling",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Scrapling 网页抓取插件(dsh):静态/浏览器抓取 + CSS/XPath 结构化抽取 + 选择器自愈 + capture_xhr 与会话网络历史 + 登录态存取 + Spider 爬虫,由常驻 Python 进程驱动。",
5
5
  "keywords": [
6
6
  "dsh",
@@ -24,6 +24,9 @@
24
24
  "dsh-scrapling": "./bin/dsh-scrapling.mjs"
25
25
  },
26
26
  "files": [
27
+ "locale/zh.json",
28
+ "locale/en.json",
29
+ "docs",
27
30
  "icon.svg",
28
31
  "bin/dsh-scrapling.mjs",
29
32
  "host.js",
@@ -55,6 +58,7 @@
55
58
  "./client": "./client.js",
56
59
  "./cordis.patch.yml": "./cordis.patch.yml",
57
60
  "./py/*": "./py/*",
61
+ "./locale/*.json": "./locale/*.json",
58
62
  "./package.json": "./package.json"
59
63
  },
60
64
  "publishConfig": {
@@ -63,49 +67,54 @@
63
67
  },
64
68
  "dependencies": {
65
69
  "@modelcontextprotocol/sdk": "1.32.2",
66
- "ipaddr.js": "2.5.0"
70
+ "ipaddr.js": "2.5.0",
71
+ "zod": "4.6.7"
67
72
  },
68
73
  "devDependencies": {
69
- "@deepseek-ai/cordis": "4.0.5",
70
- "@deepseek-ai/cordis-plugin-include": "1.0.10",
71
- "@deepseek-ai/cordis-plugin-loader": "1.0.6",
72
- "@deepseek-ai/dsh-api-remotes": "0.2.1-rc.3",
73
- "@deepseek-ai/dsh-client-locale": "0.2.1-rc.3",
74
- "@deepseek-ai/dsh-client-store": "0.2.1-rc.3",
75
- "@deepseek-ai/dsh-client-ui-chat": "0.2.1-rc.3",
76
- "@deepseek-ai/dsh-client-ui-conversation": "0.2.1-rc.3",
77
- "@deepseek-ai/dsh-client-ui-layout": "0.2.1-rc.3",
78
- "@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.1-rc.3",
79
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.1-rc.3",
80
- "@deepseek-ai/dsh-client-ui-settings": "0.2.1-rc.3",
81
- "@deepseek-ai/dsh-client-ui-slots": "0.2.1-rc.3",
82
- "@deepseek-ai/dsh-client-ui-tool": "0.2.1-rc.3",
83
- "@deepseek-ai/dsh-host-webserver": "0.2.1-rc.3",
84
- "@deepseek-ai/dsh-http-proxy": "0.2.1-rc.3",
85
- "@deepseek-ai/dsh-jobs": "0.2.1-rc.3",
86
- "@deepseek-ai/dsh-jobs-local": "0.2.1-rc.3",
87
- "@deepseek-ai/dsh-output-retention": "0.2.1-rc.3",
88
- "@deepseek-ai/dsh-package-manifest": "0.2.1-rc.3",
89
- "@deepseek-ai/dsh-ptc-runtime": "0.2.1-rc.3",
90
- "@deepseek-ai/dsh-sandbox": "0.2.1-rc.3",
91
- "@deepseek-ai/dsh-scope": "0.2.1-rc.3",
92
- "@deepseek-ai/dsh-session": "0.2.1-rc.3",
93
- "@deepseek-ai/dsh-settings": "0.2.1-rc.3",
94
- "@deepseek-ai/dsh-shell": "0.2.1-rc.3",
95
- "@deepseek-ai/dsh-subprocess": "0.2.1-rc.3",
96
- "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3",
97
- "@deepseek-ai/dsh-tools": "0.2.1-rc.3",
98
- "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.3",
99
- "@deepseek-ai/dsh-user-approval": "0.2.1-rc.3",
100
- "@deepseek-ai/dsh-web": "0.2.1-rc.3",
101
- "@deepseek-ai/schemastery": "3.18.5",
102
- "@jayyuen66/dsh-plugin-shared": "0.1.9",
103
- "@types/node": "26.6.5",
74
+ "@deepseek-ai/cordis": "4.0.6-alpha.1",
75
+ "@deepseek-ai/cordis-plugin-include": "1.0.11-alpha.1",
76
+ "@deepseek-ai/cordis-plugin-loader": "1.0.7-alpha.1",
77
+ "@deepseek-ai/dsh-api-remotes": "0.2.2-alpha.2",
78
+ "@deepseek-ai/dsh-client-locale": "0.2.2-alpha.2",
79
+ "@deepseek-ai/dsh-client-store": "0.2.2-alpha.2",
80
+ "@deepseek-ai/dsh-client-ui-chat": "0.2.2-alpha.2",
81
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-alpha.2",
82
+ "@deepseek-ai/dsh-client-ui-layout": "0.2.2-alpha.2",
83
+ "@deepseek-ai/dsh-client-ui-plugin-manager": "0.2.2-alpha.2",
84
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-alpha.2",
85
+ "@deepseek-ai/dsh-client-ui-settings": "0.2.2-alpha.2",
86
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-alpha.2",
87
+ "@deepseek-ai/dsh-client-ui-tool": "0.2.2-alpha.2",
88
+ "@deepseek-ai/dsh-host-webserver": "0.2.2-alpha.2",
89
+ "@deepseek-ai/dsh-http-proxy": "0.2.2-alpha.2",
90
+ "@deepseek-ai/dsh-jobs": "0.2.2-alpha.2",
91
+ "@deepseek-ai/dsh-jobs-local": "0.2.2-alpha.2",
92
+ "@deepseek-ai/dsh-output-retention": "0.2.2-alpha.2",
93
+ "@deepseek-ai/dsh-package-manifest": "0.2.2-alpha.2",
94
+ "@deepseek-ai/dsh-ptc-runtime": "0.2.2-alpha.2",
95
+ "@deepseek-ai/dsh-sandbox": "0.2.2-alpha.2",
96
+ "@deepseek-ai/dsh-scope": "0.2.2-alpha.2",
97
+ "@deepseek-ai/dsh-session": "0.2.2-alpha.2",
98
+ "@deepseek-ai/dsh-settings": "0.2.2-alpha.2",
99
+ "@deepseek-ai/dsh-shell": "0.2.2-alpha.2",
100
+ "@deepseek-ai/dsh-subprocess": "0.2.2-alpha.2",
101
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-alpha.2",
102
+ "@deepseek-ai/dsh-tool-executor-native": "0.2.2-alpha.2",
103
+ "@deepseek-ai/dsh-tools": "0.2.2-alpha.2",
104
+ "@deepseek-ai/dsh-typert-protocol": "0.2.2-alpha.2",
105
+ "@deepseek-ai/dsh-user-approval": "0.2.2-alpha.2",
106
+ "@deepseek-ai/dsh-web": "0.2.2-alpha.2",
107
+ "@deepseek-ai/schemastery": "3.18.6-alpha.1",
108
+ "@e18e/eslint-plugin": "0.8.1",
109
+ "@jayyuen66/dsh-plugin-shared": "0.2.1",
110
+ "@types/node": "26.6.6",
104
111
  "@types/react": "19.3.0",
105
112
  "@vitest/coverage-v8": "5.0.5",
113
+ "eslint-plugin-regexp": "3.3.2",
106
114
  "eslint-plugin-sonarjs": "4.2.2",
107
- "oxfmt": "0.74.0",
108
- "oxlint": "1.89.0",
115
+ "eslint-plugin-zod": "5.2.2",
116
+ "oxfmt": "0.75.0",
117
+ "oxlint": "1.90.0",
109
118
  "oxlint-tsgolint": "7.0.2005",
110
119
  "react": "^19.3.0",
111
120
  "rolldown": "1.2.15",
@@ -114,12 +123,12 @@
114
123
  "vitest": "5.0.5"
115
124
  },
116
125
  "peerDependencies": {
117
- "@deepseek-ai/dsh": "^0.2.1-rc.3",
118
- "@deepseek-ai/dsh-output-retention": "0.2.1-rc.3",
119
- "@deepseek-ai/dsh-tools": "0.2.1-rc.3",
120
- "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.3",
121
- "@deepseek-ai/dsh-web": "0.2.1-rc.3",
122
- "@deepseek-ai/schemastery": "3.18.5"
126
+ "@deepseek-ai/dsh": "^0.2.1-rc.3 || ^0.2.2-alpha.2",
127
+ "@deepseek-ai/dsh-output-retention": "^0.2.1-rc.3 || ^0.2.2-alpha.2",
128
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.3 || ^0.2.2-alpha.2",
129
+ "@deepseek-ai/dsh-typert-protocol": "^0.2.1-rc.3 || ^0.2.2-alpha.2",
130
+ "@deepseek-ai/dsh-web": "^0.2.1-rc.3 || ^0.2.2-alpha.2",
131
+ "@deepseek-ai/schemastery": "3.18.6-alpha.1"
123
132
  },
124
133
  "peerDependenciesMeta": {
125
134
  "@deepseek-ai/dsh": {