@hyperttp/core 3.0.5 → 3.0.7
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/Core/HyperCore.d.ts +11 -0
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +1 -1
- package/Core/HyperCore.js.map +3 -3
- package/package.json +2 -2
- package/transports/manager.d.ts +11 -6
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +1 -1
- package/transports/manager.js.map +3 -3
- package/protocols/rest/index.d.ts +0 -10
- package/protocols/rest/index.d.ts.map +0 -1
- package/protocols/rest/index.js +0 -2
- package/protocols/rest/index.js.map +0 -7
- package/protocols/rest/receiver.d.ts +0 -36
- package/protocols/rest/receiver.d.ts.map +0 -1
- package/protocols/rest/receiver.js +0 -2
- package/protocols/rest/receiver.js.map +0 -7
- package/protocols/rest/sender.d.ts +0 -12
- package/protocols/rest/sender.d.ts.map +0 -1
- package/protocols/rest/sender.js +0 -2
- package/protocols/rest/sender.js.map +0 -7
- package/protocols/rest/type.d.ts +0 -113
- package/protocols/rest/type.d.ts.map +0 -1
- package/protocols/rest/type.js +0 -2
- package/protocols/rest/type.js.map +0 -7
- package/protocols/rest/utils.d.ts +0 -3
- package/protocols/rest/utils.d.ts.map +0 -1
- package/protocols/rest/utils.js +0 -2
- package/protocols/rest/utils.js.map +0 -7
- package/rest.d.ts +0 -2
- package/rest.d.ts.map +0 -1
- package/rest.js +0 -2
- package/rest.js.map +0 -7
- package/transports/fetch.d.ts +0 -43
- package/transports/fetch.d.ts.map +0 -1
- package/transports/fetch.js +0 -2
- package/transports/fetch.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/transports/manager.ts"],
|
|
4
|
-
"sourcesContent": ["import type { HyperTransport, LogLevel, HyperProtocolName } from \"@hyperttp/types\";\nimport { FetchTransport, type FetchTransportOptions } from \"./fetch.js\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\n\ndeclare const Bun: unknown;\ndeclare const Deno: unknown;\n\nexport type Runtime = \"bun\" | \"node\" | \"deno\" | \"browser\";\n\n/**\n * @ru Опции разрешения транспорта. `customTransport` имеет приоритет над автовыбором.\n * @en Transport resolution options. `customTransport` takes priority over auto-selection.\n */\nexport interface ResolveTransportOptions {\n customTransport?: HyperTransport;\n /** Stable configuration identity for sharing automatic transports across calls. */\n cacheKey?: object;\n /**\n * @ru Требует серверную роль транспорта. При её отсутствии используется\n * встроенный `FetchTransport`.\n * @en Requires the transport server role. When unavailable, the built-in\n * `FetchTransport` is used.\n */\n requireListen?: boolean;\n logger?: (level: LogLevel, message: string, meta?: unknown) => void;\n verbose?: boolean;\n [key: string]: unknown;\n}\n\nexport const CURRENT_RUNTIME: Runtime = (() => {\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof process !== \"undefined\" && process.versions?.node) return \"node\";\n return \"browser\";\n})();\n\ntype TransportDef = {\n readonly runtime: readonly Runtime[];\n readonly pkg: string;\n readonly export: string;\n /** Protocols that require this transport family. Omitted for generic transports. */\n readonly protocols?: readonly HyperProtocolName[];\n};\n\nconst ALL_RUNTIMES: readonly Runtime[] = [\"bun\", \"node\", \"deno\", \"browser\"];\n\nconst TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"webrtc\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-webrtc\",\n export: \"WebRtcTransport\",\n },\n {\n protocols: [\"ws\", \"websocket\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-websocket\",\n export: \"WebSocketTransport\",\n },\n {\n protocols: [\"mqtt\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-mqtt\",\n export: \"MqttTransport\",\n },\n { runtime: [\"bun\"], pkg: \"@hyperttp/transport-bun\", export: \"BunTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-undici\", export: \"UndiciTransport\" },\n { runtime: [\"deno\"], pkg: \"@hyperttp/transport-deno\", export: \"DenoTransport\" },\n];\n\nfunction getCandidates(protocol: HyperProtocolName): readonly TransportDef[] {\n return TRANSPORT_DEFS.filter(\n (transport) =>\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!transport.protocols || transport.protocols.includes(protocol)),\n );\n}\n\nfunction getTransportInstallHint(protocol: HyperProtocolName): string {\n const packages = new Set(\n getCandidates(protocol)\n .filter((transport) => transport.protocols?.includes(protocol))\n .map((transport) => transport.pkg),\n );\n if (packages.size === 0) return \"\";\n\n return ` Install ${[...packages].map((pkg) => `\"${pkg}\"`).join(\" or \")}.`;\n}\n\ntype TransportCache = {\n client: Map<HyperProtocolName, HyperTransport>;\n listen: Map<HyperProtocolName, HyperTransport>;\n clientResolutions: Map<HyperProtocolName, Promise<HyperTransport>>;\n listenResolutions: Map<HyperProtocolName, Promise<HyperTransport>>;\n};\n\nconst defaultCacheKey = {};\nlet transportCaches = new WeakMap<object, TransportCache>();\nlet transportEntries = new WeakMap<HyperTransport, Set<Map<HyperProtocolName, HyperTransport>>>();\n\nfunction getCache(config?: ResolveTransportOptions): TransportCache {\n const identity = config?.cacheKey ?? config ?? defaultCacheKey;\n let cache = transportCaches.get(identity);\n if (!cache) {\n cache = {\n client: new Map(),\n listen: new Map(),\n clientResolutions: new Map(),\n listenResolutions: new Map(),\n };\n transportCaches.set(identity, cache);\n }\n return cache;\n}\n\nfunction supportsListen(transport: HyperTransport): boolean {\n return typeof transport.listen === \"function\";\n}\n\nfunction supportsProtocol(transport: HyperTransport, protocol: HyperProtocolName): boolean {\n return typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n}\n\nasync function disposeUnusedTransport(transport: HyperTransport): Promise<void> {\n try {\n if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch {\n //\n }\n}\n\nasync function createFetchTransport(\n protocol: HyperProtocolName,\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n // Client config.protocols contains protocol modules, not transport identifiers.\n const fetchTransport = new FetchTransport({\n ...config,\n protocols:\n Array.isArray(config?.protocols) &&\n config.protocols.every((value: unknown) => typeof value === \"string\")\n ? config.protocols\n : undefined,\n } as FetchTransportOptions);\n if (supportsProtocol(fetchTransport, protocol)) return fetchTransport;\n\n await disposeUnusedTransport(fetchTransport);\n throw new Error(\n `[HyperCore] No transport available for protocol \"${protocol}\" in runtime \"${CURRENT_RUNTIME}\".${getTransportInstallHint(protocol)}`,\n );\n}\n\nasync function createTransport(\n protocol: HyperProtocolName,\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const candidates = getCandidates(protocol);\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i]!;\n let mod: Record<string, unknown>;\n try {\n mod = await dynamicImport(t.pkg);\n } catch (err) {\n if (!isModuleNotFoundError(err)) throw err;\n continue;\n }\n const candidate = (mod[t.export] ?? mod.default) as\n | { new (opts?: unknown): HyperTransport }\n | undefined;\n if (typeof candidate !== \"function\") continue;\n\n const instance = new candidate(config ?? {});\n if (\n !supportsProtocol(instance, protocol) ||\n (config?.requireListen && !supportsListen(instance))\n ) {\n await disposeUnusedTransport(instance);\n continue;\n }\n\n return instance;\n }\n\n const fetchTransport = await createFetchTransport(protocol, config);\n const message = `[HyperCore] Packaged transport unavailable or missing listen() for protocol \"${protocol}\" in runtime \"${CURRENT_RUNTIME}\". Falling back to FetchTransport.`;\n try {\n if (config?.logger) {\n config.logger(\"warn\", message);\n } else if (config?.verbose) {\n console.warn(message);\n }\n } catch (err) {\n await disposeUnusedTransport(fetchTransport);\n throw err;\n }\n return fetchTransport;\n}\n\n/**\n * @ru Разрешает оптимальный транспорт для указанного протокола и текущей среды.\n * Кастомный транспорт из конфигурации имеет приоритет над автовыбором.\n * @en Resolves optimal transport for the given protocol and current runtime.\n * A custom transport from the config takes priority over auto-selection.\n */\nexport async function resolveTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsProtocol(config.customTransport, protocol)) {\n throw new Error(`[HyperCore] Custom transport does not support protocol \"${protocol}\".`);\n }\n\n return requireListen && !supportsListen(config.customTransport)\n ? createFetchTransport(protocol, config)\n : config.customTransport;\n }\n\n const cache = getCache(config);\n const transportCache = requireListen ? cache.listen : cache.client;\n const transportResolutions = requireListen ? cache.listenResolutions : cache.clientResolutions;\n const cached = transportCache.get(protocol);\n if (cached) return cached;\n\n const pending = transportResolutions.get(protocol);\n if (pending) return pending;\n\n const resolution = createTransport(protocol, config)\n .then((transport) => {\n transportCache.set(protocol, transport);\n let entries = transportEntries.get(transport);\n if (!entries) {\n entries = new Set();\n transportEntries.set(transport, entries);\n }\n entries.add(transportCache);\n return transport;\n })\n .finally(() => {\n transportResolutions.delete(protocol);\n });\n\n transportResolutions.set(protocol, resolution);\n return resolution;\n}\n\n/**\n * @ru Синхронно возвращает транспорт из кэша без создания Promise.\n * @en Synchronously returns a cached transport without creating a Promise.\n * @param protocol - Протокол, для которого запрашивается транспорт. @en Protocol whose transport is requested.\n * @returns Кэшированный транспорт или `undefined`. @en Cached transport or `undefined`.\n */\nexport function getCachedTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): HyperTransport | undefined {\n const cache = getCache(config);\n return (config?.requireListen ? cache.listen : cache.client).get(protocol);\n}\n\n/**\n * @ru Удаляет все записи кэша, ссылающиеся на указанный транспорт.\n * @en Removes every cache entry that references the given transport.\n * @param transport - Экземпляр транспорта для удаления из кэша. @en Transport instance to evict from the cache.\n */\nexport function evictCachedTransport(transport: HyperTransport): void {\n for (const entries of transportEntries.get(transport) ?? []) {\n for (const [protocol, cached] of entries) {\n if (cached === transport) entries.delete(protocol);\n }\n }\n transportEntries.delete(transport);\n}\n\n/**\n * @ru Очищает кэш транспортов и ожидающих их разрешений. Не закрывает уже\n * созданные экземпляры транспорта.\n * @en Clears cached transports and pending resolutions. It does not close\n * already-created transport instances.\n */\nexport function resetCachedTransport(): void {\n transportCaches = new WeakMap();\n transportEntries = new WeakMap();\n}\n"],
|
|
5
|
-
"mappings": "aACA,OAAS,
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["import type { HyperTransport, LogLevel, HyperProtocolName } from \"@hyperttp/types\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\n\ndeclare const Bun: unknown;\ndeclare const Deno: unknown;\n\nexport type Runtime = \"bun\" | \"node\" | \"deno\" | \"browser\";\n\n/**\n * @ru Опции разрешения транспорта. `customTransport` имеет приоритет над автовыбором.\n * @en Transport resolution options. `customTransport` takes priority over auto-selection.\n */\nexport interface ResolveTransportOptions {\n customTransport?: HyperTransport;\n /** Stable configuration identity for sharing automatic transports across calls. */\n cacheKey?: object;\n /** Requires the transport server role. */\n requireListen?: boolean;\n /** Prefer an HTTP/2 transport for REST and gRPC when one is available. */\n http2?: boolean;\n logger?: (level: LogLevel, message: string, meta?: unknown) => void;\n verbose?: boolean;\n [key: string]: unknown;\n}\n\nexport const CURRENT_RUNTIME: Runtime = (() => {\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof process !== \"undefined\" && process.versions?.node) return \"node\";\n return \"browser\";\n})();\n\ntype TransportDef = {\n readonly runtime: readonly Runtime[];\n readonly pkg: string;\n readonly export: string;\n /** Protocols that require this transport family. Omitted for generic transports. */\n readonly protocols?: readonly HyperProtocolName[];\n};\n\nconst ALL_RUNTIMES: readonly Runtime[] = [\"bun\", \"node\", \"deno\", \"browser\"];\n\nconst HTTP2_TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"rest\"],\n runtime: [\"bun\"],\n pkg: \"@hyperttp/transport-bun\",\n export: \"BunTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"node\"],\n pkg: \"@hyperttp/transport-undici\",\n export: \"UndiciTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"deno\"],\n pkg: \"@hyperttp/transport-deno\",\n export: \"DenoTransport\",\n },\n {\n protocols: [\"rest\", \"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n];\n\nconst TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"webrtc\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-webrtc\",\n export: \"WebRtcTransport\",\n },\n {\n protocols: [\"ws\", \"websocket\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-websocket\",\n export: \"WebSocketTransport\",\n },\n {\n protocols: [\"mqtt\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-mqtt\",\n export: \"MqttTransport\",\n },\n {\n protocols: [\"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n { runtime: [\"bun\"], pkg: \"@hyperttp/transport-bun\", export: \"BunTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-node\", export: \"FetchTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-undici\", export: \"UndiciTransport\" },\n { runtime: [\"deno\"], pkg: \"@hyperttp/transport-deno\", export: \"DenoTransport\" },\n];\n\nfunction getCandidates(protocol: HyperProtocolName): readonly TransportDef[] {\n return TRANSPORT_DEFS.filter(\n (transport) =>\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!transport.protocols || transport.protocols.includes(protocol)),\n );\n}\n\nfunction getCandidatesForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): readonly TransportDef[] {\n const preferred =\n config?.http2 === true\n ? HTTP2_TRANSPORT_DEFS.filter((transport) => {\n const supportedProtocols = transport.protocols;\n return (\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!supportedProtocols ||\n protocols.some((protocol) => supportedProtocols.includes(protocol)))\n );\n })\n : [];\n const lists = protocols.map((protocol) => getCandidates(protocol));\n // Start with the most constrained protocol so a dedicated transport such as\n // GrpcTransport is tried before a generic REST transport.\n lists.sort((a, b) => a.length - b.length);\n\n const defs = new Map<string, TransportDef>();\n for (const transport of [...preferred, ...lists.flat()]) {\n const key = `${transport.pkg}:${transport.export}`;\n if (!defs.has(key)) defs.set(key, transport);\n }\n return [...defs.values()];\n}\n\nfunction getTransportInstallHint(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): string {\n const packages = new Set(\n getCandidatesForProtocols(protocols, config).map((transport) => transport.pkg),\n );\n if (packages.size === 0) return \"\";\n\n return ` Install ${[...packages].map((pkg) => `\"${pkg}\"`).join(\" or \")}.`;\n}\n\ntype TransportCache = {\n client: Map<string, HyperTransport>;\n listen: Map<string, HyperTransport>;\n multi: Map<string, HyperTransport>;\n clientResolutions: Map<string, Promise<HyperTransport>>;\n listenResolutions: Map<string, Promise<HyperTransport>>;\n multiResolutions: Map<string, Promise<HyperTransport>>;\n};\n\nconst defaultCacheKey = {};\nlet transportCaches = new WeakMap<object, TransportCache>();\nlet transportEntries = new WeakMap<HyperTransport, Set<Map<string, HyperTransport>>>();\n\nfunction getCache(config?: ResolveTransportOptions): TransportCache {\n const identity = config?.cacheKey ?? config ?? defaultCacheKey;\n let cache = transportCaches.get(identity);\n if (!cache) {\n cache = {\n client: new Map(),\n listen: new Map(),\n multi: new Map(),\n clientResolutions: new Map(),\n listenResolutions: new Map(),\n multiResolutions: new Map(),\n };\n transportCaches.set(identity, cache);\n }\n return cache;\n}\n\nfunction supportsListen(transport: HyperTransport): boolean {\n return typeof transport.listen === \"function\";\n}\n\nfunction supportsProtocol(transport: HyperTransport, protocol: HyperProtocolName): boolean {\n return typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n}\n\nfunction supportsAll(transport: HyperTransport, protocols: readonly HyperProtocolName[]): boolean {\n return protocols.every((protocol) => supportsProtocol(transport, protocol));\n}\n\nasync function disposeUnusedTransport(transport: HyperTransport): Promise<void> {\n try {\n if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch {\n //\n }\n}\n\nasync function createTransport(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const candidates = getCandidatesForProtocols(protocols, config);\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i]!;\n let mod: Record<string, unknown>;\n try {\n mod = await dynamicImport(t.pkg);\n } catch (err) {\n if (!isModuleNotFoundError(err)) throw err;\n continue;\n }\n const candidate = (mod[t.export] ?? mod.default) as\n | { new (opts?: unknown): HyperTransport }\n | undefined;\n if (typeof candidate !== \"function\") continue;\n\n const instance = new candidate(config ?? {});\n if (!supportsAll(instance, protocols) || (config?.requireListen && !supportsListen(instance))) {\n await disposeUnusedTransport(instance);\n continue;\n }\n\n return instance;\n }\n\n const label = protocols.length === 1 ? \"protocol\" : \"protocols\";\n throw new Error(\n `[HyperCore] No transport available for ${label} ${protocols.map((p) => `\"${p}\"`).join(\", \")} in runtime \"${CURRENT_RUNTIME}\".${getTransportInstallHint(protocols, config)}`,\n );\n}\n\nfunction cacheTransport(\n transport: HyperTransport,\n cache: Map<string, HyperTransport>,\n key: string,\n): HyperTransport {\n cache.set(key, transport);\n let entries = transportEntries.get(transport);\n if (!entries) {\n entries = new Set();\n transportEntries.set(transport, entries);\n }\n entries.add(cache);\n return transport;\n}\n\n/**\n * @ru Разрешает оптимальный транспорт для указанного протокола и текущей среды.\n * Кастомный транспорт из конфигурации имеет приоритет над автовыбором.\n * @en Resolves optimal transport for the given protocol and current runtime.\n * A custom transport from the config takes priority over auto-selection.\n */\nexport async function resolveTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsProtocol(config.customTransport, protocol)) {\n throw new Error(`[HyperCore] Custom transport does not support protocol \"${protocol}\".`);\n }\n\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const transportCache = requireListen ? cache.listen : cache.client;\n const transportResolutions = requireListen ? cache.listenResolutions : cache.clientResolutions;\n const cached = transportCache.get(protocol);\n if (cached) return cached;\n\n const pending = transportResolutions.get(protocol);\n if (pending) return pending;\n\n const resolution = createTransport([protocol], config)\n .then((transport) => cacheTransport(transport, transportCache, protocol))\n .finally(() => {\n transportResolutions.delete(protocol);\n });\n\n transportResolutions.set(protocol, resolution);\n return resolution;\n}\n\n/**\n * @ru Разрешает один транспорт, поддерживающий сразу все указанные протоколы.\n * Используется мультипротокольным `listen({ protocols })`, чтобы не открывать\n * несколько слушателей на одном порту.\n * @en Resolves one transport supporting every requested protocol. Used by the\n * multi-protocol `listen({ protocols })` so one port is not opened multiple times.\n */\nexport async function resolveTransportForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n if (protocols.length === 0) {\n throw new Error(\"[HyperCore] At least one protocol is required to resolve a transport.\");\n }\n if (protocols.length === 1) return resolveTransport(protocols[0], config);\n\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsAll(config.customTransport, protocols)) {\n throw new Error(\n `[HyperCore] Custom transport does not support protocols ${protocols.map((p) => `\"${p}\"`).join(\", \")}.`,\n );\n }\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const key = JSON.stringify([...protocols].sort());\n const cached = cache.multi.get(key);\n if (cached) return cached;\n\n const pending = cache.multiResolutions.get(key);\n if (pending) return pending;\n\n const resolution = createTransport(protocols, config)\n .then((transport) => cacheTransport(transport, cache.multi, key))\n .finally(() => {\n cache.multiResolutions.delete(key);\n });\n\n cache.multiResolutions.set(key, resolution);\n return resolution;\n}\n\n/**\n * @ru Синхронно возвращает транспорт из кэша без создания Promise.\n * @en Synchronously returns a cached transport without creating a Promise.\n * @param protocol - Протокол, для которого запрашивается транспорт. @en Protocol whose transport is requested.\n * @returns Кэшированный транспорт или `undefined`. @en Cached transport or `undefined`.\n */\nexport function getCachedTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): HyperTransport | undefined {\n const cache = getCache(config);\n return (config?.requireListen ? cache.listen : cache.client).get(protocol);\n}\n\n/**\n * @ru Удаляет все записи кэша, ссылающиеся на указанный транспорт.\n * @en Removes every cache entry that references the given transport.\n * @param transport - Экземпляр транспорта для удаления из кэша. @en Transport instance to evict from the cache.\n */\nexport function evictCachedTransport(transport: HyperTransport): void {\n for (const entries of transportEntries.get(transport) ?? []) {\n for (const [key, cached] of entries) {\n if (cached === transport) entries.delete(key);\n }\n }\n transportEntries.delete(transport);\n}\n\n/**\n * @ru Очищает кэш транспортов и ожидающих их разрешений. Не закрывает уже\n * созданные экземпляры транспорта.\n * @en Clears cached transports and pending resolutions. It does not close\n * already-created transport instances.\n */\nexport function resetCachedTransport(): void {\n transportCaches = new WeakMap();\n transportEntries = new WeakMap();\n}\n"],
|
|
5
|
+
"mappings": "aACA,OAAS,iBAAAA,EAAe,yBAAAC,MAA6B,sBAwB9C,aAAM,gBACP,OAAO,IAAQ,IAAoB,MACnC,OAAO,KAAS,IAAoB,OACpC,OAAO,QAAY,KAAe,QAAQ,UAAU,KAAa,OAC9D,UAWT,MAAMC,EAAmC,CAAC,MAAO,OAAQ,OAAQ,SAAS,EAEpEC,EAAgD,CACpD,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,KAAK,EACf,IAAK,0BACL,OAAQ,gBAEV,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,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,EAAE,KAAK,IAAI,CAAC,GAAG,EAG3G,GAAIG,GAAiB,CAAChB,EAAejB,EAAO,eAAe,EACzD,MAAM,IAAI,MAAM,yDAAyD,EAE3E,OAAOA,EAAO,eAChB,CAEA,MAAMgB,EAAQF,EAASd,CAAM,EACvBO,EAAM,KAAK,UAAU,CAAC,GAAGR,CAAS,EAAE,KAAI,CAAE,EAC1CqC,EAASpB,EAAM,MAAM,IAAIT,CAAG,EAClC,GAAI6B,EAAQ,OAAOA,EAEnB,MAAMC,EAAUrB,EAAM,iBAAiB,IAAIT,CAAG,EAC9C,GAAI8B,EAAS,OAAOA,EAEpB,MAAMC,EAAajB,EAAgBtB,EAAWC,CAAM,EACjD,KAAMH,GAAckC,EAAelC,EAAWmB,EAAM,MAAOT,CAAG,CAAC,EAC/D,QAAQ,IAAK,CACZS,EAAM,iBAAiB,OAAOT,CAAG,CACnC,CAAC,EAEH,OAAAS,EAAM,iBAAiB,IAAIT,EAAK+B,CAAU,EACnCA,CACT,CAQM,gBAAU,mBACd1C,EAA8B,OAC9BI,EAAgC,CAEhC,MAAMgB,EAAQF,EAASd,CAAM,EAC7B,OAAQA,GAAQ,cAAgBgB,EAAM,OAASA,EAAM,QAAQ,IAAIpB,CAAQ,CAC3E,CAOM,gBAAU,qBAAqBC,EAAyB,CAC5D,UAAWmC,KAAWnB,EAAiB,IAAIhB,CAAS,GAAK,CAAA,EACvD,SAAW,CAACU,EAAK6B,CAAM,IAAKJ,EACtBI,IAAWvC,GAAWmC,EAAQ,OAAOzB,CAAG,EAGhDM,EAAiB,OAAOhB,CAAS,CACnC,CAQM,gBAAU,sBAAoB,CAClCe,EAAkB,IAAI,QACtBC,EAAmB,IAAI,OACzB",
|
|
6
|
+
"names": ["dynamicImport", "isModuleNotFoundError", "ALL_RUNTIMES", "HTTP2_TRANSPORT_DEFS", "TRANSPORT_DEFS", "getCandidates", "protocol", "transport", "getCandidatesForProtocols", "protocols", "config", "preferred", "supportedProtocols", "lists", "a", "b", "defs", "key", "getTransportInstallHint", "packages", "pkg", "defaultCacheKey", "transportCaches", "transportEntries", "getCache", "identity", "cache", "supportsListen", "supportsProtocol", "supportsAll", "disposeUnusedTransport", "createTransport", "candidates", "i", "t", "mod", "err", "candidate", "instance", "label", "p", "cacheTransport", "entries", "requireListen", "transportCache", "transportResolutions", "cached", "pending", "resolution"]
|
|
7
7
|
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { HyperProtocol } from "@hyperttp/types";
|
|
2
|
-
import type { RestInput, RestServerInput, RestServerResponse } from "./type.js";
|
|
3
|
-
/**
|
|
4
|
-
* @ru Единый REST-модуль протокола, объединяющий клиентский сендер и серверный ресивер.
|
|
5
|
-
* @en Unified REST protocol module combining a client sender and a server receiver.
|
|
6
|
-
*/
|
|
7
|
-
export declare const RestProtocol: HyperProtocol<RestInput, unknown, RestServerInput, RestServerResponse, "rest">;
|
|
8
|
-
export { RestReceiver } from "./receiver.js";
|
|
9
|
-
export { RestSender } from "./sender.js";
|
|
10
|
-
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAIhF;;;GAGG;AACH,eAAO,MAAM,YAAY,EAAE,aAAa,CACtC,SAAS,EACT,OAAO,EACP,eAAe,EACf,kBAAkB,EAClB,MAAM,CAMP,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC"}
|
package/protocols/rest/index.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";import{RestReceiver as e}from"./receiver.js";import{RestSender as r}from"./sender.js";export const RestProtocol={protocol:"rest",name:"RestProtocol",sender:new r,receiver:new e};export{RestReceiver}from"./receiver.js";export{RestSender}from"./sender.js";
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/protocols/rest/index.ts"],
|
|
4
|
-
"sourcesContent": ["import type { HyperProtocol } from \"@hyperttp/types\";\nimport type { RestInput, RestServerInput, RestServerResponse } from \"./type.js\";\nimport { RestReceiver } from \"./receiver.js\";\nimport { RestSender } from \"./sender.js\";\n\n/**\n * @ru Единый REST-модуль протокола, объединяющий клиентский сендер и серверный ресивер.\n * @en Unified REST protocol module combining a client sender and a server receiver.\n */\nexport const RestProtocol: HyperProtocol<\n RestInput,\n unknown,\n RestServerInput,\n RestServerResponse,\n \"rest\"\n> = {\n protocol: \"rest\",\n name: \"RestProtocol\",\n sender: new RestSender(),\n receiver: new RestReceiver(),\n};\n\nexport { RestReceiver } from \"./receiver.js\";\nexport { RestSender } from \"./sender.js\";\n"],
|
|
5
|
-
"mappings": "aAEA,OAAS,gBAAAA,MAAoB,gBAC7B,OAAS,cAAAC,MAAkB,cAMpB,aAAM,aAMT,CACF,SAAU,OACV,KAAM,eACN,OAAQ,IAAIA,EACZ,SAAU,IAAID,CAAAA,EAGhB,OAAS,iBAAoB,gBAC7B,OAAS,eAAkB",
|
|
6
|
-
"names": ["RestReceiver", "RestSender"]
|
|
7
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import type { HyperReceiver, ServerRequestContext, TransportRequest, TransportResponse } from "@hyperttp/types";
|
|
2
|
-
import type { RestServerHandler, RestServerInput, RestServerResponse } from "./type.js";
|
|
3
|
-
/**
|
|
4
|
-
* @ru REST/HTTP серверный адаптер. Зеркальная к `RestSender` реализация
|
|
5
|
-
* трёхфазного цикла receive → handle → respond.
|
|
6
|
-
* @en REST/HTTP server adapter. Mirror implementation of `RestSender` for the
|
|
7
|
-
* three-phase receive → handle → respond cycle.
|
|
8
|
-
*/
|
|
9
|
-
export declare class RestReceiver implements HyperReceiver<RestServerInput, RestServerResponse, TransportRequest, TransportResponse> {
|
|
10
|
-
readonly protocol = "rest";
|
|
11
|
-
protected readonly handler?: RestServerHandler;
|
|
12
|
-
/**
|
|
13
|
-
* @ru Создаёт REST-ресивер с необязательным application handler.
|
|
14
|
-
* @en Creates a REST receiver with an optional application handler.
|
|
15
|
-
* @param options - Настройки ресивера и его обработчик. @en Receiver settings and its handler.
|
|
16
|
-
*/
|
|
17
|
-
constructor(options?: {
|
|
18
|
-
handler?: RestServerHandler;
|
|
19
|
-
});
|
|
20
|
-
/**
|
|
21
|
-
* @ru Фаза приёма: разбирает сырой запрос транспорта в REST-структуру.
|
|
22
|
-
* @en Receive phase: parses raw transport request into REST input structure.
|
|
23
|
-
*/
|
|
24
|
-
receive(raw: TransportRequest, _ctx: ServerRequestContext): RestServerInput;
|
|
25
|
-
/**
|
|
26
|
-
* @ru Фаза обработки: вызывает зарегистрированный handler.
|
|
27
|
-
* @en Handle phase: executes the registered application handler.
|
|
28
|
-
*/
|
|
29
|
-
handle(request: RestServerInput, ctx: ServerRequestContext): RestServerResponse | Promise<RestServerResponse>;
|
|
30
|
-
/**
|
|
31
|
-
* @ru Фаза ответа: сериализует протокольный ответ в транспортный формат.
|
|
32
|
-
* @en Respond phase: serializes protocol response to raw transport format.
|
|
33
|
-
*/
|
|
34
|
-
respond(response: RestServerResponse, _ctx: ServerRequestContext): TransportResponse;
|
|
35
|
-
}
|
|
36
|
-
//# sourceMappingURL=receiver.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"receiver.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/receiver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AA6FxF;;;;;GAKG;AACH,qBAAa,YAAa,YAAW,aAAa,CAChD,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,CAClB;IACC,QAAQ,CAAC,QAAQ,UAAU;IAC3B,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAE/C;;;;OAIG;IACH,YAAY,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,iBAAiB,CAAA;KAAO,EAExD;IAED;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,gBAAgB,EAAE,IAAI,EAAE,oBAAoB,GAAG,eAAe,CAU1E;IAED;;;OAGG;IACH,MAAM,CACJ,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,oBAAoB,GACxB,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAYlD;IAED;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,EAAE,oBAAoB,GAAG,iBAAiB,CA6BnF;CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";import{HyperClientError as h}from"../../utils/errors.js";import{DEFAULT_STATUS_TEXTS as c,getHeaderValue as u}from"./utils.js";const i="application/json",d=new TextDecoder,p=new TextEncoder,f=typeof Buffer<"u";function l(r){return f?Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):d.decode(r)}function b(r){return f?Buffer.from(r).toString("utf8"):d.decode(r)}function w(r){return f?Buffer.from(r):p.encode(r)}function m(r){const e=Object.create(null);for(const[o,n]of new URLSearchParams(r)){const a=e[o];a===void 0?e[o]=n:Array.isArray(a)?a.push(n):e[o]=[a,n]}return e}function s(r,e){if((u(r,"content-type")??"").includes(i))try{return JSON.parse(e)}catch{return e}return e}function A(r){const e=r.body;if(e==null)return;const o=u(r.headers,"content-type")??"",n=o.includes(i)||o.includes("text/")||o.includes("application/xml")||o.includes("application/x-www-form-urlencoded");if(e instanceof Uint8Array)return n?s(r.headers,l(e)):e;if(e instanceof ArrayBuffer)return n?s(r.headers,b(e)):new Uint8Array(e);if(ArrayBuffer.isView(e)){const a=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n?s(r.headers,l(a)):a}return typeof e=="string"?s(r.headers,e):e}export class RestReceiver{protocol="rest";handler;constructor(e={}){this.handler=e.handler}receive(e,o){const n=new URL(e.url,"http://hyperttp.local");return{method:e.method,path:n.pathname,headers:e.headers,query:m(n.search.slice(1)),body:A(e)}}handle(e,o){if(o.signal?.aborted)throw o.signal.reason??new Error("Request aborted");if(!this.handler)throw new h('[RestReceiver] No application handler registered for protocol "rest".');return this.handler(e,o)}respond(e,o){const n={...e.headers},a=e.status??200;let t=e.body;return t!=null&&typeof t=="object"&&(typeof ReadableStream<"u"&&t instanceof ReadableStream||Symbol.asyncIterator in t)?{status:a,statusText:c[a]??"",headers:n,body:t}:(t instanceof ArrayBuffer?t=new Uint8Array(t):ArrayBuffer.isView(t)&&!(t instanceof Uint8Array)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():t!=null&&typeof t=="object"&&!(t instanceof Uint8Array)&&(t=JSON.stringify(t),Object.keys(n).some(y=>y.toLowerCase()==="content-type")||(n["content-type"]=i)),{status:a,statusText:c[a]??"",headers:n,body:t==null?void 0:t instanceof Uint8Array?t:w(String(t))})}}
|
|
2
|
-
//# sourceMappingURL=receiver.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/protocols/rest/receiver.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n HyperReceiver,\n ServerRequestContext,\n TransportRequest,\n TransportResponse,\n} from \"@hyperttp/types\";\nimport type { RestServerHandler, RestServerInput, RestServerResponse } from \"./type.js\";\nimport { HyperClientError } from \"../../utils/errors.js\";\nimport { DEFAULT_STATUS_TEXTS, getHeaderValue } from \"./utils.js\";\n\nconst JSON_TYPE = \"application/json\";\nconst TEXT_DECODER = new TextDecoder();\nconst TEXT_ENCODER = new TextEncoder();\nconst HAS_BUFFER = typeof Buffer !== \"undefined\";\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n if (HAS_BUFFER) {\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(bytes);\n}\n\nfunction decodeArrayBuffer(ab: ArrayBuffer): string {\n if (HAS_BUFFER) {\n return Buffer.from(ab).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(ab);\n}\n\nfunction encodeUtf8(str: string): Uint8Array {\n if (HAS_BUFFER) {\n return Buffer.from(str);\n }\n return TEXT_ENCODER.encode(str);\n}\n\n/**\n * @ru Разбирает query-строку URL в словарь (поддерживает повторные ключи как массивы).\n * @en Parses a URL query string into a dictionary (supports repeated keys as arrays).\n */\nfunction parseQuery(queryString: string): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = Object.create(null);\n\n for (const [key, value] of new URLSearchParams(queryString)) {\n const existing = out[key];\n if (existing === undefined) {\n out[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n out[key] = [existing, value];\n }\n }\n\n return out;\n}\n\n/**\n * @ru Декодирует тело запроса по content-type.\n * @en Decodes the request body based on content-type.\n */\nfunction parseTextBody(\n headers: Readonly<Record<string, string | string[]>>,\n text: string,\n): unknown {\n const contentType = getHeaderValue(headers, \"content-type\") ?? \"\";\n if (contentType.includes(JSON_TYPE)) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction decodeBody(raw: TransportRequest): unknown {\n const body = raw.body;\n if (body == null) return undefined;\n const contentType = getHeaderValue(raw.headers, \"content-type\") ?? \"\";\n const textual =\n contentType.includes(JSON_TYPE) ||\n contentType.includes(\"text/\") ||\n contentType.includes(\"application/xml\") ||\n contentType.includes(\"application/x-www-form-urlencoded\");\n if (body instanceof Uint8Array) {\n return textual ? parseTextBody(raw.headers, decodeUtf8(body)) : body;\n }\n if (body instanceof ArrayBuffer) {\n return textual ? parseTextBody(raw.headers, decodeArrayBuffer(body)) : new Uint8Array(body);\n }\n if (ArrayBuffer.isView(body)) {\n const bytes = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n return textual ? parseTextBody(raw.headers, decodeUtf8(bytes)) : bytes;\n }\n if (typeof body === \"string\") return parseTextBody(raw.headers, body);\n return body;\n}\n\n/**\n * @ru REST/HTTP серверный адаптер. Зеркальная к `RestSender` реализация\n * трёхфазного цикла receive → handle → respond.\n * @en REST/HTTP server adapter. Mirror implementation of `RestSender` for the\n * three-phase receive → handle → respond cycle.\n */\nexport class RestReceiver implements HyperReceiver<\n RestServerInput,\n RestServerResponse,\n TransportRequest,\n TransportResponse\n> {\n readonly protocol = \"rest\";\n protected readonly handler?: RestServerHandler;\n\n /**\n * @ru Создаёт REST-ресивер с необязательным application handler.\n * @en Creates a REST receiver with an optional application handler.\n * @param options - Настройки ресивера и его обработчик. @en Receiver settings and its handler.\n */\n constructor(options: { handler?: RestServerHandler } = {}) {\n this.handler = options.handler;\n }\n\n /**\n * @ru Фаза приёма: разбирает сырой запрос транспорта в REST-структуру.\n * @en Receive phase: parses raw transport request into REST input structure.\n */\n receive(raw: TransportRequest, _ctx: ServerRequestContext): RestServerInput {\n const url = new URL(raw.url, \"http://hyperttp.local\");\n\n return {\n method: raw.method,\n path: url.pathname,\n headers: raw.headers,\n query: parseQuery(url.search.slice(1)),\n body: decodeBody(raw),\n };\n }\n\n /**\n * @ru Фаза обработки: вызывает зарегистрированный handler.\n * @en Handle phase: executes the registered application handler.\n */\n handle(\n request: RestServerInput,\n ctx: ServerRequestContext,\n ): RestServerResponse | Promise<RestServerResponse> {\n if (ctx.signal?.aborted) {\n throw ctx.signal.reason ?? new Error(\"Request aborted\");\n }\n\n if (!this.handler) {\n throw new HyperClientError(\n '[RestReceiver] No application handler registered for protocol \"rest\".',\n );\n }\n\n return this.handler(request, ctx);\n }\n\n /**\n * @ru Фаза ответа: сериализует протокольный ответ в транспортный формат.\n * @en Respond phase: serializes protocol response to raw transport format.\n */\n respond(response: RestServerResponse, _ctx: ServerRequestContext): TransportResponse {\n const headers: Record<string, string> = { ...response.headers };\n const status = response.status ?? 200;\n\n let body: unknown = response.body;\n const streaming =\n body != null &&\n typeof body === \"object\" &&\n ((typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream) ||\n Symbol.asyncIterator in body);\n if (streaming) {\n return { status, statusText: DEFAULT_STATUS_TEXTS[status] ?? \"\", headers, body };\n }\n if (body instanceof ArrayBuffer) {\n body = new Uint8Array(body);\n } else if (ArrayBuffer.isView(body) && !(body instanceof Uint8Array)) {\n body = new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();\n } else if (body != null && typeof body === \"object\" && !(body instanceof Uint8Array)) {\n body = JSON.stringify(body);\n const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === \"content-type\");\n if (!hasContentType) headers[\"content-type\"] = JSON_TYPE;\n }\n\n return {\n status,\n statusText: DEFAULT_STATUS_TEXTS[status] ?? \"\",\n headers,\n body: body == null ? undefined : body instanceof Uint8Array ? body : encodeUtf8(String(body)),\n };\n }\n}\n"],
|
|
5
|
-
"mappings": "aAOA,OAAS,oBAAAA,MAAwB,wBACjC,OAAS,wBAAAC,EAAsB,kBAAAC,MAAsB,aAErD,MAAMC,EAAY,mBACZC,EAAe,IAAI,YACnBC,EAAe,IAAI,YACnBC,EAAa,OAAO,OAAW,IAErC,SAASC,EAAWC,EAAiB,CACnC,OAAIF,EACK,OAAO,KAAKE,EAAM,OAAQA,EAAM,WAAYA,EAAM,UAAU,EAAE,SAAS,MAAM,EAE/EJ,EAAa,OAAOI,CAAK,CAClC,CAEA,SAASC,EAAkBC,EAAe,CACxC,OAAIJ,EACK,OAAO,KAAKI,CAAE,EAAE,SAAS,MAAM,EAEjCN,EAAa,OAAOM,CAAE,CAC/B,CAEA,SAASC,EAAWC,EAAW,CAC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YAAW,IAAO,cAAc,IACrEd,EAAQ,cAAc,EAAIjB,IAG1C,CACL,OAAA8B,EACA,WAAYhC,EAAqBgC,CAAM,GAAK,GAC5C,QAAAb,EACA,KAAMI,GAAQ,KAAO,OAAYA,aAAgB,WAAaA,EAAOb,EAAW,OAAOa,CAAI,CAAC,CAAA,EAEhG,CAAA",
|
|
6
|
-
"names": ["HyperClientError", "DEFAULT_STATUS_TEXTS", "getHeaderValue", "JSON_TYPE", "TEXT_DECODER", "TEXT_ENCODER", "HAS_BUFFER", "decodeUtf8", "bytes", "decodeArrayBuffer", "ab", "encodeUtf8", "str", "parseQuery", "queryString", "out", "key", "value", "existing", "parseTextBody", "headers", "text", "decodeBody", "raw", "body", "contentType", "textual", "options", "_ctx", "url", "request", "ctx", "response", "status", "k"]
|
|
7
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { HyperSender, HyperTransport, RequestContext, SendRequest, TransportRequest, TransportResponse, UniversalResponse } from "@hyperttp/types";
|
|
2
|
-
import type { RestInput } from "./type.js";
|
|
3
|
-
export declare class RestSender implements HyperSender<RestInput, unknown, TransportRequest, TransportResponse> {
|
|
4
|
-
readonly protocol = "rest";
|
|
5
|
-
readonly methods: Readonly<Record<string, (...args: any[]) => any>>;
|
|
6
|
-
prepare(request: SendRequest<RestInput, string>, ctx: RequestContext): TransportRequest;
|
|
7
|
-
send(prepared: TransportRequest, transport: HyperTransport, _ctx: RequestContext): Promise<TransportResponse>;
|
|
8
|
-
parse(raw: TransportResponse, _ctx: RequestContext): UniversalResponse<unknown>;
|
|
9
|
-
private dispatch;
|
|
10
|
-
private buildUrl;
|
|
11
|
-
}
|
|
12
|
-
//# sourceMappingURL=sender.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sender.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/sender.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EAEd,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,SAAS,EAAkC,MAAM,WAAW,CAAC;AAiM3E,qBAAa,UAAW,YAAW,WAAW,CAC5C,SAAS,EACT,OAAO,EACP,gBAAgB,EAChB,iBAAiB,CAClB;IACC,QAAQ,CAAC,QAAQ,UAAU;IAE3B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,CAAC,CAyGjE;IAEF,OAAO,CAAC,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,cAAc,GAAG,gBAAgB,CAqEtF;IAEK,IAAI,CACR,QAAQ,EAAE,gBAAgB,EAC1B,SAAS,EAAE,cAAc,EACzB,IAAI,EAAE,cAAc,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAqC5B;IAED,KAAK,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,CA6B9E;IAED,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,QAAQ;CAsCjB"}
|
package/protocols/rest/sender.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";import{TimeoutError as b}from"../../utils/errors.js";import{applyTimeout as m}from"../../utils/abort.js";import{DEFAULT_STATUS_TEXTS as g,getHeaderValue as w}from"./utils.js";const f="rest:stream",p=new TextEncoder,A=new TextDecoder,h=new WeakMap;function S(l){if(l===null||typeof l!="object")return!1;const t=Object.getPrototypeOf(l);return t===null||t===Object.prototype}async function E(l){if(l instanceof Uint8Array)return l;if(l instanceof ArrayBuffer)return new Uint8Array(l);if(ArrayBuffer.isView(l))return new Uint8Array(l.buffer,l.byteOffset,l.byteLength).slice();if(l&&typeof l=="object"&&"arrayBuffer"in l){const t=l.arrayBuffer;if(typeof t=="function")return new Uint8Array(await t.call(l))}if(typeof ReadableStream<"u"&&l instanceof ReadableStream){const t=l.getReader(),o=[];let e=0;try{for(;;){const{done:i,value:s}=await t.read();if(i)break;const a=s instanceof Uint8Array?s:new Uint8Array(s);o.push(a),e+=a.byteLength}}finally{t.releaseLock()}const r=new Uint8Array(e);let n=0;for(const i of o)r.set(i,n),n+=i.byteLength;return r}return l}function T(l,t,o){const e=l.getReader();let r=!1,n;const i=()=>{r||(r=!0,t?.removeEventListener("abort",a),e.releaseLock(),o())},s=async c=>{try{await e.cancel(c)}finally{i()}},a=()=>{n.error(t?.reason),s(t?.reason).catch(()=>{})};return new ReadableStream({start(c){n=c,t?.addEventListener("abort",a,{once:!0}),t?.aborted&&a()},async pull(){try{const c=await e.read();if(r)return;c.done?(n.close(),i()):n.enqueue(c.value)}catch(c){r||(n.error(c),i())}},cancel:s})}function U(l,t,o){const e=l[Symbol.asyncIterator]();let r=!1,n=!1;const i=()=>{r||(r=!0,t?.removeEventListener("abort",s),o())},s=()=>{n=!0,i(),(async()=>{try{l.destroy?.()}finally{await e.return?.()}})().catch(()=>{})};return t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s(),{[Symbol.asyncIterator](){return this},async next(){if(n)throw t?.reason;if(r)return{done:!0,value:void 0};let a;const c=new Promise((d,u)=>{a=()=>u(t?.reason),t?.addEventListener("abort",a,{once:!0})});try{const d=await Promise.race([e.next(),c]);if(n)throw t?.reason;return d.done&&i(),d}catch(d){throw i(),d}finally{t?.removeEventListener("abort",a)}},async return(a){try{return await e.return?.(a)??{done:!0,value:a}}finally{i()}},async throw(a){try{if(e.throw)return await e.throw(a);throw await e.return?.(),a}finally{i()}}}}export class RestSender{protocol="rest";methods={get:(t,o,e,r)=>this.dispatch(t,{method:"GET",url:o,...e,signal:r??e?.signal}),post:(t,o,e,r,n)=>this.dispatch(t,{method:"POST",url:o,...r,body:e,signal:n??r?.signal}),put:(t,o,e,r,n)=>this.dispatch(t,{method:"PUT",url:o,...r,body:e,signal:n??r?.signal}),patch:(t,o,e,r,n)=>this.dispatch(t,{method:"PATCH",url:o,...r,body:e,signal:n??r?.signal}),delete:(t,o,e,r)=>this.dispatch(t,{method:"DELETE",url:o,...e,signal:r??e?.signal}),head:(t,o,e,r)=>this.dispatch(t,{method:"HEAD",url:o,...e,signal:r??e?.signal}),options:(t,o,e,r)=>this.dispatch(t,{method:"OPTIONS",url:o,...e,signal:r??e?.signal}),query:(t,o,e,r,n)=>this.dispatch(t,{method:"QUERY",url:o,...r,body:e,signal:n??r?.signal}),request:(t,o,e,r,n)=>this.dispatch(t,{method:o,url:e,...r,signal:n??r?.signal}),stream:(t,o,e,r)=>this.dispatch(t,{method:"GET",url:o,...e,stream:!0,signal:r??e?.signal})};prepare(t,o){const{input:e}=t,r=t.signal??e.signal??o.signal,n=e.timeout;let i,s=r;if(n!=null&&n>0){const a={};s=m(r,n,a,()=>new b(e.url,n)),i=a.cleanupSignal}try{const a={};if(e.headers)if(e.headers instanceof Headers)e.headers.forEach((u,y)=>{a[y.toLowerCase()]=u});else if(Array.isArray(e.headers))for(const[u,y]of e.headers)a[u.toLowerCase()]=y;else for(const[u,y]of Object.entries(e.headers))y!=null&&(a[u.toLowerCase()]=String(y));let c=e.body;c!=null&&(S(c)||Array.isArray(c))?(c=p.encode(JSON.stringify(c)),a["content-type"]||(a["content-type"]="application/json; charset=utf-8")):typeof c=="string"&&(c=p.encode(c));const d={method:e.method.toUpperCase(),url:this.buildUrl(e.url,e.query),headers:a,body:c,signal:s,protocol:this.protocol,stream:e.stream,stealth:e.stealth,followRedirects:e.followRedirects,maxRedirects:e.maxRedirects};return i&&h.set(d,i),d}catch(a){throw i?.(),a}}async send(t,o,e){const r=t,n=()=>{const s=h.get(t);h.delete(t),s?.()};let i=!1;try{const s=await o.execute(t);if(r.stream){if(typeof ReadableStream<"u"&&s.body instanceof ReadableStream){const c=T(s.body,t.signal,n);return i=!0,{...s,body:c,[f]:!0}}if(s.body!=null&&typeof s.body=="object"&&typeof s.body[Symbol.asyncIterator]=="function"){const c=U(s.body,t.signal,n);return i=!0,{...s,body:c,[f]:!0}}return{...s,[f]:!0}}const a=await E(s.body);return a===s.body?s:{...s,body:a}}finally{i||n()}}parse(t,o){const e=t.status>=200&&t.status<300;let r=t.body;if(!t[f]&&t.body instanceof Uint8Array){const n=w(t.headers,"content-type")??"",i=A.decode(t.body);if(n.includes("application/json"))try{r=JSON.parse(i)}catch{r=i}else(n.includes("text/")||n.includes("application/xml"))&&(r=i)}return{protocol:this.protocol,ok:e,status:t.status,statusText:t.statusText||g[t.status]||"",headers:t.headers,url:t.url,data:r,raw:t}}dispatch(t,o){return t.send({protocol:"rest",input:o,signal:o.signal})}buildUrl(t,o){if(!o)return t;const e=[];for(const[s,a]of Object.entries(o)){if(a==null)continue;const c=Array.isArray(a)?a:[a];for(const d of c)e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(d))}`)}if(e.length===0)return t;const r=e.join("&"),n=t.indexOf("#");if(n!==-1){const s=t.slice(0,n),a=t.slice(n),c=s.includes("?")?"&":"?";return`${s}${c}${r}${a}`}const i=t.includes("?")?"&":"?";return`${t}${i}${r}`}}
|
|
2
|
-
//# sourceMappingURL=sender.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/protocols/rest/sender.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n HyperSender,\n HyperTransport,\n IHyperCore,\n RequestContext,\n SendRequest,\n TransportRequest,\n TransportResponse,\n UniversalResponse,\n} from \"@hyperttp/types\";\nimport type { RestInput, RestRequestOptions, HttpMethod } from \"./type.js\";\nimport { TimeoutError } from \"../../utils/errors.js\";\nimport { applyTimeout } from \"../../utils/abort.js\";\nimport { DEFAULT_STATUS_TEXTS, getHeaderValue } from \"./utils.js\";\n\nconst STREAM_HINT = \"rest:stream\";\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\nconst REQUEST_CLEANUPS = new WeakMap<TransportRequest, () => void>();\n\ntype RestTransportRequest = TransportRequest & {\n stealth?: boolean;\n};\n\ntype RestTransportResponse = TransportResponse & {\n [STREAM_HINT]?: boolean;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nasync function collectBody(body: unknown): Promise<unknown> {\n if (body instanceof Uint8Array) return body;\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();\n }\n\n if (body && typeof body === \"object\" && \"arrayBuffer\" in body) {\n const arrayBuffer = (body as { arrayBuffer?: unknown }).arrayBuffer;\n if (typeof arrayBuffer === \"function\") {\n return new Uint8Array(await arrayBuffer.call(body));\n }\n }\n\n if (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream) {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const chunk = value instanceof Uint8Array ? value : new Uint8Array(value);\n chunks.push(chunk);\n totalLength += chunk.byteLength;\n }\n } finally {\n reader.releaseLock();\n }\n\n const collected = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n collected.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return collected;\n }\n\n return body;\n}\n\nfunction bindStream(\n body: ReadableStream,\n signal: AbortSignal | undefined,\n cleanup: () => void,\n): ReadableStream {\n const reader = body.getReader();\n let finished = false;\n let controller: ReadableStreamDefaultController;\n const finish = () => {\n if (finished) return;\n finished = true;\n signal?.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n cleanup();\n };\n const cancel = async (reason: unknown) => {\n try {\n await reader.cancel(reason);\n } finally {\n finish();\n }\n };\n const onAbort = () => {\n controller.error(signal?.reason);\n void cancel(signal?.reason).catch(() => {});\n };\n return new ReadableStream({\n start(value) {\n controller = value;\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (signal?.aborted) onAbort();\n },\n async pull() {\n try {\n const result = await reader.read();\n if (finished) return;\n if (result.done) {\n controller.close();\n finish();\n } else {\n controller.enqueue(result.value);\n }\n } catch (error) {\n if (!finished) {\n controller.error(error);\n finish();\n }\n }\n },\n cancel,\n });\n}\n\nfunction bindIterable(\n body: AsyncIterable<unknown> & { destroy?: () => void },\n signal: AbortSignal | undefined,\n cleanup: () => void,\n): AsyncIterableIterator<unknown> {\n const iterator = body[Symbol.asyncIterator]();\n let finished = false;\n let aborted = false;\n const finish = () => {\n if (finished) return;\n finished = true;\n signal?.removeEventListener(\"abort\", onAbort);\n cleanup();\n };\n const onAbort = () => {\n aborted = true;\n finish();\n // Node streams can interrupt a pending read; generic iterators may only queue return().\n void (async () => {\n try {\n body.destroy?.();\n } finally {\n await iterator.return?.();\n }\n })().catch(() => {});\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (signal?.aborted) onAbort();\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n if (aborted) throw signal?.reason;\n if (finished) return { done: true, value: undefined };\n let rejectRead!: () => void;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectRead = () => reject(signal?.reason);\n signal?.addEventListener(\"abort\", rejectRead, { once: true });\n });\n try {\n const result = await Promise.race([iterator.next(), abort]);\n if (aborted) throw signal?.reason;\n if (result.done) finish();\n return result;\n } catch (error) {\n finish();\n throw error;\n } finally {\n signal?.removeEventListener(\"abort\", rejectRead);\n }\n },\n async return(value?: unknown) {\n try {\n return (await iterator.return?.(value)) ?? { done: true, value };\n } finally {\n finish();\n }\n },\n async throw(error?: unknown) {\n try {\n if (iterator.throw) return await iterator.throw(error);\n await iterator.return?.();\n throw error;\n } finally {\n finish();\n }\n },\n };\n}\n\nexport class RestSender implements HyperSender<\n RestInput,\n unknown,\n TransportRequest,\n TransportResponse\n> {\n readonly protocol = \"rest\";\n\n readonly methods: Readonly<Record<string, (...args: any[]) => any>> = {\n get: (core: IHyperCore, url: string, options?: RestRequestOptions, signal?: AbortSignal) =>\n this.dispatch(core, { method: \"GET\", url, ...options, signal: signal ?? options?.signal }),\n\n post: (\n core: IHyperCore,\n url: string,\n body?: unknown,\n options?: Omit<RestRequestOptions, \"body\">,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: \"POST\",\n url,\n ...options,\n body,\n signal: signal ?? options?.signal,\n }),\n\n put: (\n core: IHyperCore,\n url: string,\n body?: unknown,\n options?: Omit<RestRequestOptions, \"body\">,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: \"PUT\",\n url,\n ...options,\n body,\n signal: signal ?? options?.signal,\n }),\n\n patch: (\n core: IHyperCore,\n url: string,\n body?: unknown,\n options?: Omit<RestRequestOptions, \"body\">,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: \"PATCH\",\n url,\n ...options,\n body,\n signal: signal ?? options?.signal,\n }),\n\n delete: (core: IHyperCore, url: string, options?: RestRequestOptions, signal?: AbortSignal) =>\n this.dispatch(core, { method: \"DELETE\", url, ...options, signal: signal ?? options?.signal }),\n\n head: (core: IHyperCore, url: string, options?: RestRequestOptions, signal?: AbortSignal) =>\n this.dispatch(core, { method: \"HEAD\", url, ...options, signal: signal ?? options?.signal }),\n\n options: (core: IHyperCore, url: string, options?: RestRequestOptions, signal?: AbortSignal) =>\n this.dispatch(core, {\n method: \"OPTIONS\",\n url,\n ...options,\n signal: signal ?? options?.signal,\n }),\n\n query: (\n core: IHyperCore,\n url: string,\n body?: unknown,\n options?: Omit<RestRequestOptions, \"body\">,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: \"QUERY\",\n url,\n ...options,\n body,\n signal: signal ?? options?.signal,\n }),\n\n request: (\n core: IHyperCore,\n method: HttpMethod | (string & {}),\n url: string,\n options?: RestRequestOptions,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: method as HttpMethod,\n url,\n ...options,\n signal: signal ?? options?.signal,\n }),\n\n stream: (\n core: IHyperCore,\n url: string,\n options?: Omit<RestRequestOptions, \"stream\">,\n signal?: AbortSignal,\n ) =>\n this.dispatch(core, {\n method: \"GET\",\n url,\n ...options,\n stream: true,\n signal: signal ?? options?.signal,\n }),\n };\n\n prepare(request: SendRequest<RestInput, string>, ctx: RequestContext): TransportRequest {\n const { input } = request;\n const inputSignal = request.signal ?? input.signal ?? ctx.signal;\n const timeout = input.timeout;\n let cleanupSignal: (() => void) | undefined;\n let signal = inputSignal;\n\n if (timeout != null && timeout > 0) {\n const timeoutMeta: { cleanupSignal?: () => void } = {};\n signal = applyTimeout(\n inputSignal,\n timeout,\n timeoutMeta,\n () => new TimeoutError(input.url, timeout),\n );\n cleanupSignal = timeoutMeta.cleanupSignal;\n }\n\n try {\n const headers: Record<string, string> = {};\n\n if (input.headers) {\n if (input.headers instanceof Headers) {\n input.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n } else if (Array.isArray(input.headers)) {\n for (const [key, value] of input.headers) {\n headers[key.toLowerCase()] = value;\n }\n } else {\n for (const [key, value] of Object.entries(input.headers)) {\n if (value != null) {\n headers[key.toLowerCase()] = String(value);\n }\n }\n }\n }\n\n let body = input.body;\n\n if (body !== undefined && body !== null && (isPlainObject(body) || Array.isArray(body))) {\n body = TEXT_ENCODER.encode(JSON.stringify(body));\n if (!headers[\"content-type\"]) {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n } else if (typeof body === \"string\") {\n body = TEXT_ENCODER.encode(body);\n }\n\n const prepared = {\n method: input.method.toUpperCase(),\n url: this.buildUrl(input.url, input.query),\n headers,\n body,\n signal,\n protocol: this.protocol,\n stream: input.stream,\n stealth: input.stealth,\n followRedirects: input.followRedirects,\n maxRedirects: input.maxRedirects,\n } as RestTransportRequest;\n\n if (cleanupSignal) REQUEST_CLEANUPS.set(prepared, cleanupSignal);\n return prepared;\n } catch (error) {\n cleanupSignal?.();\n throw error;\n }\n }\n\n async send(\n prepared: TransportRequest,\n transport: HyperTransport,\n _ctx: RequestContext,\n ): Promise<TransportResponse> {\n const restRequest = prepared as RestTransportRequest;\n const cleanup = () => {\n const release = REQUEST_CLEANUPS.get(prepared);\n REQUEST_CLEANUPS.delete(prepared);\n release?.();\n };\n let streaming = false;\n try {\n const response = await transport.execute(prepared);\n if (restRequest.stream) {\n if (typeof ReadableStream !== \"undefined\" && response.body instanceof ReadableStream) {\n const body = bindStream(response.body, prepared.signal, cleanup);\n streaming = true;\n return { ...response, body, [STREAM_HINT]: true } as RestTransportResponse;\n }\n if (\n response.body != null &&\n typeof response.body === \"object\" &&\n typeof (response.body as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n ) {\n const body = bindIterable(\n response.body as AsyncIterable<unknown>,\n prepared.signal,\n cleanup,\n );\n streaming = true;\n return { ...response, body, [STREAM_HINT]: true } as RestTransportResponse;\n }\n return { ...response, [STREAM_HINT]: true } as RestTransportResponse;\n }\n\n const body = await collectBody(response.body);\n return body === response.body ? response : { ...response, body };\n } finally {\n if (!streaming) cleanup();\n }\n }\n\n parse(raw: TransportResponse, _ctx: RequestContext): UniversalResponse<unknown> {\n const ok = raw.status >= 200 && raw.status < 300;\n let parsedData: unknown = raw.body;\n\n if (!(raw as RestTransportResponse)[STREAM_HINT] && raw.body instanceof Uint8Array) {\n const contentType = getHeaderValue(raw.headers, \"content-type\") ?? \"\";\n const text = TEXT_DECODER.decode(raw.body);\n\n if (contentType.includes(\"application/json\")) {\n try {\n parsedData = JSON.parse(text);\n } catch {\n parsedData = text;\n }\n } else if (contentType.includes(\"text/\") || contentType.includes(\"application/xml\")) {\n parsedData = text;\n }\n }\n\n return {\n protocol: this.protocol,\n ok,\n status: raw.status,\n statusText: raw.statusText || DEFAULT_STATUS_TEXTS[raw.status] || \"\",\n headers: raw.headers,\n url: raw.url,\n data: parsedData,\n raw,\n };\n }\n\n private dispatch(core: IHyperCore, input: RestInput): Promise<UniversalResponse<unknown>> {\n return core.send<RestInput, unknown, \"rest\">({\n protocol: \"rest\",\n input,\n signal: input.signal,\n });\n }\n\n private buildUrl(baseUrl: string, query?: RestInput[\"query\"]): string {\n if (!query) {\n return baseUrl;\n }\n\n const parts: string[] = [];\n\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n const values = Array.isArray(value) ? value : [value];\n\n for (const v of values) {\n parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);\n }\n }\n\n if (parts.length === 0) {\n return baseUrl;\n }\n\n const queryString = parts.join(\"&\");\n const hashIndex = baseUrl.indexOf(\"#\");\n\n if (hashIndex !== -1) {\n const urlBeforeHash = baseUrl.slice(0, hashIndex);\n const hashPart = baseUrl.slice(hashIndex);\n const separator = urlBeforeHash.includes(\"?\") ? \"&\" : \"?\";\n\n return `${urlBeforeHash}${separator}${queryString}${hashPart}`;\n }\n\n const separator = baseUrl.includes(\"?\") ? \"&\" : \"?\";\n\n return `${baseUrl}${separator}${queryString}`;\n }\n}\n"],
|
|
5
|
-
"mappings": "aAWA,OAAS,gBAAAA,MAAoB,wBAC7B,OAAS,gBAAAC,MAAoB,uBAC7B,OAAS,wBAAAC,EAAsB,kBAAAC,MAAsB,aAErD,MAAMC,EAAc,cACdC,EAAe,IAAI,YACnBC,EAAe,IAAI,YACnBC,EAAmB,IAAI,QAU7B,SAASC,EAAcC,EAAc,CACnC,GAAIA,IAAU,MAAQ,OAAOA,GAAU,SACrC,MAAO,GAET,MAAMC,EAAQ,OAAO,eAAeD,CAAK,EACzC,OAAOC,IAAU,MAAQA,IAAU,OAAO,SAC5C,CAEA,eAAeC,EAAYC,EAAa,CACtC,GAAIA,aAAgB,WAAY,OAAOA,EACvC,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EACzB,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,W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TEXT_ENCODER", "TEXT_DECODER", "REQUEST_CLEANUPS", "isPlainObject", "value", "proto", "collectBody", "body", "arrayBuffer", "reader", "chunks", "totalLength", "done", "chunk", "collected", "offset", "bindStream", "signal", "cleanup", "finished", "controller", "finish", "onAbort", "cancel", "reason", "result", "error", "bindIterable", "iterator", "aborted", "rejectRead", "abort", "_resolve", "reject", "core", "url", "options", "method", "request", "ctx", "input", "inputSignal", "timeout", "cleanupSignal", "timeoutMeta", "headers", "key", "prepared", "transport", "_ctx", "restRequest", "release", "streaming", "response", "raw", "ok", "parsedData", "contentType", "text", "baseUrl", "query", "parts", "values", "v", "queryString", "hashIndex", "urlBeforeHash", "hashPart", "separator"]
|
|
7
|
-
}
|
package/protocols/rest/type.d.ts
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import type { ServerRequestContext, UniversalResponse } from "@hyperttp/types";
|
|
2
|
-
/**
|
|
3
|
-
* @ru Поддерживаемый HTTP-метод REST-запроса. `QUERY` предназначен для совместимых
|
|
4
|
-
* с ним серверов и прокси.
|
|
5
|
-
* @en Supported HTTP method for a REST request. `QUERY` is intended for servers
|
|
6
|
-
* and proxies that support it.
|
|
7
|
-
*/
|
|
8
|
-
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "QUERY";
|
|
9
|
-
export type RestHeaders = Headers | Record<string, string | number | boolean> | ReadonlyArray<readonly [string, string]>;
|
|
10
|
-
/**
|
|
11
|
-
* @ru Входные данные REST-запроса, используемые `core.send()` и методами `core.rest`.
|
|
12
|
-
* @en REST request input used by `core.send()` and `core.rest` methods.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* core.send({
|
|
16
|
-
* protocol: "rest",
|
|
17
|
-
* input: { method: "POST", url: "https://api.example.test/items", body: { name: "item" } },
|
|
18
|
-
* });
|
|
19
|
-
*
|
|
20
|
-
* @template TBody - Тип тела запроса до сериализации.
|
|
21
|
-
*/
|
|
22
|
-
export interface RestInput<TBody = unknown> {
|
|
23
|
-
/** @ru HTTP-метод запроса. @en HTTP method for the request. */
|
|
24
|
-
method: HttpMethod;
|
|
25
|
-
/** @ru Абсолютный или относительный URL. @en Absolute or relative URL. */
|
|
26
|
-
url: string;
|
|
27
|
-
/** @ru Заголовки запроса. @en Request headers. */
|
|
28
|
-
headers?: RestHeaders;
|
|
29
|
-
/** @ru Query-параметры, добавляемые к URL. @en Query parameters appended to the URL. */
|
|
30
|
-
query?: Record<string, string | number | boolean | (string | number | boolean)[]>;
|
|
31
|
-
/** @ru Тело запроса; plain object и массив сериализуются в JSON. @en Request body; plain objects and arrays are serialized as JSON. */
|
|
32
|
-
body?: TBody;
|
|
33
|
-
/** @ru Таймаут в миллисекундах. @en Timeout in milliseconds. */
|
|
34
|
-
timeout?: number;
|
|
35
|
-
/** @ru Не буферизовать тело ответа и вернуть поток транспорта. @en Do not buffer the response body and return the transport stream. */
|
|
36
|
-
stream?: boolean;
|
|
37
|
-
/** @ru Отключает автоматические redirect-ы транспорта. @en Disables automatic transport redirects. */
|
|
38
|
-
followRedirects?: boolean;
|
|
39
|
-
/** @ru Максимальное число redirect-ов, если транспорт поддерживает настройку. @en Maximum redirect count when supported by the transport. */
|
|
40
|
-
maxRedirects?: number;
|
|
41
|
-
/** @ru Опция транспорта для stealth-режима. @en Transport-specific stealth mode. */
|
|
42
|
-
stealth?: boolean;
|
|
43
|
-
/** @ru Сигнал отмены запроса. @en Request cancellation signal. */
|
|
44
|
-
signal?: AbortSignal;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* @ru Опции shortcut-методов REST без `method` и `url`.
|
|
48
|
-
* @en REST shortcut-method options excluding `method` and `url`.
|
|
49
|
-
*/
|
|
50
|
-
export type RestRequestOptions = Omit<RestInput, "method" | "url">;
|
|
51
|
-
/**
|
|
52
|
-
* @ru Разобранный серверный REST-запрос, получаемый ресивером из сырого транспорта.
|
|
53
|
-
* @en Parsed server-side REST request produced by the receiver from raw transport input.
|
|
54
|
-
*/
|
|
55
|
-
export interface RestServerInput {
|
|
56
|
-
readonly method: HttpMethod | (string & {});
|
|
57
|
-
readonly path: string;
|
|
58
|
-
readonly headers: Readonly<Record<string, string | string[]>>;
|
|
59
|
-
readonly query: Readonly<Record<string, string | string[]>>;
|
|
60
|
-
readonly body?: unknown;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* @ru Ответ серверного REST-обработчика, сериализуемый ресивером в транспортный формат.
|
|
64
|
-
* @en Server-side REST handler response, serialized by the receiver into the transport format.
|
|
65
|
-
*/
|
|
66
|
-
export interface RestServerResponse {
|
|
67
|
-
readonly status?: number;
|
|
68
|
-
readonly headers?: Record<string, string>;
|
|
69
|
-
readonly body?: unknown;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* @ru Серверный обработчик REST-протокола.
|
|
73
|
-
* @en Server-side REST protocol handler.
|
|
74
|
-
* @param request - The parsed server request.
|
|
75
|
-
* @param ctx - The server request context.
|
|
76
|
-
* @returns The response to serialize.
|
|
77
|
-
*/
|
|
78
|
-
export type RestServerHandler = (request: RestServerInput, ctx: ServerRequestContext) => RestServerResponse | Promise<RestServerResponse>;
|
|
79
|
-
/**
|
|
80
|
-
* @ru Типизированная поверхность shortcut-методов REST, доступная как `core.rest`.
|
|
81
|
-
* @en Typed REST shortcut-method surface available as `core.rest`.
|
|
82
|
-
*
|
|
83
|
-
* @example
|
|
84
|
-
* const response = await core.rest.get<{ id: string }>("https://api.example.test/items/1");
|
|
85
|
-
*/
|
|
86
|
-
export interface RestClientMethods {
|
|
87
|
-
/** @ru Выполняет GET-запрос. @en Performs a GET request. */
|
|
88
|
-
get<T = unknown>(url: string, options?: RestRequestOptions, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
89
|
-
post<T = unknown>(url: string, body?: unknown, options?: Omit<RestRequestOptions, "body">, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
90
|
-
put<T = unknown>(url: string, body?: unknown, options?: Omit<RestRequestOptions, "body">, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
91
|
-
patch<T = unknown>(url: string, body?: unknown, options?: Omit<RestRequestOptions, "body">, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
92
|
-
delete<T = unknown>(url: string, options?: RestRequestOptions, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
93
|
-
head<T = unknown>(url: string, options?: RestRequestOptions, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
94
|
-
options<T = unknown>(url: string, options?: RestRequestOptions, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
95
|
-
query<T = unknown>(url: string, body?: unknown, options?: Omit<RestRequestOptions, "body">, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
96
|
-
request<T = unknown>(method: HttpMethod | (string & {}), url: string, options?: RestRequestOptions, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
97
|
-
stream<T = unknown>(url: string, options?: Omit<RestRequestOptions, "stream">, signal?: AbortSignal): Promise<UniversalResponse<T>>;
|
|
98
|
-
}
|
|
99
|
-
declare module "@hyperttp/types" {
|
|
100
|
-
interface ProtocolInputMap {
|
|
101
|
-
rest: RestInput;
|
|
102
|
-
}
|
|
103
|
-
interface ProtocolServerRequestMap {
|
|
104
|
-
rest: RestServerInput;
|
|
105
|
-
}
|
|
106
|
-
interface ProtocolServerResponseMap {
|
|
107
|
-
rest: RestServerResponse;
|
|
108
|
-
}
|
|
109
|
-
interface HyperProtocols {
|
|
110
|
-
readonly rest: RestClientMethods;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
//# sourceMappingURL=type.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE/E;;;;;GAKG;AACH,MAAM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,EACjB,MAAM,EAAE,UAAU,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,EAClC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,kBAAkB,EAC5B,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,MAAM,CAAC,CAAC,GAAG,OAAO,EAChB,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,IAAI,CAAC,kBAAkB,EAAE,QAAQ,CAAC,EAC5C,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;CAClC;AAED,OAAO,QAAQ,iBAAiB,CAAC;IAC/B,UAAU,gBAAgB;QACxB,IAAI,EAAE,SAAS,CAAC;KACjB;IAED,UAAU,wBAAwB;QAChC,IAAI,EAAE,eAAe,CAAC;KACvB;IAED,UAAU,yBAAyB;QACjC,IAAI,EAAE,kBAAkB,CAAC;KAC1B;IAED,UAAU,cAAc;QACtB,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;KAClC;CACF"}
|
package/protocols/rest/type.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/utils.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CASjE,CAAC;AAEF,wBAAgB,cAAc,CAC5B,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC,EACpD,IAAI,EAAE,MAAM,GACX,MAAM,GAAG,SAAS,CAWpB"}
|
package/protocols/rest/utils.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";export const DEFAULT_STATUS_TEXTS={200:"OK",201:"Created",204:"No Content",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"};export function getHeaderValue(r,e){const t=r[e]??r[e.toLowerCase()];if(t!==void 0)return Array.isArray(t)?t[0]:t;const a=e.toLowerCase();for(const n in r)if(n.toLowerCase()===a){const o=r[n];return Array.isArray(o)?o[0]:o}}
|
|
2
|
-
//# sourceMappingURL=utils.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/protocols/rest/utils.ts"],
|
|
4
|
-
"sourcesContent": ["export const DEFAULT_STATUS_TEXTS: Readonly<Record<number, string>> = {\n 200: \"OK\",\n 201: \"Created\",\n 204: \"No Content\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 500: \"Internal Server Error\",\n};\n\nexport function getHeaderValue(\n headers: Readonly<Record<string, string | string[]>>,\n name: string,\n): string | undefined {\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (direct !== undefined) return Array.isArray(direct) ? direct[0] : direct;\n\n const target = name.toLowerCase();\n for (const key in headers) {\n if (key.toLowerCase() === target) {\n const value = headers[key];\n return Array.isArray(value) ? value[0] : value;\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "aAAO,aAAM,qBAAyD,CACpE,IAAK,KACL,IAAK,UACL,IAAK,aACL,IAAK,cACL,IAAK,eACL,IAAK,YACL,IAAK,YACL,IAAK,uBAAA,EAGD,gBAAU,eACdA,EACAC,EAAY,CAEZ,MAAMC,EAASF,EAAQC,CAAI,GAAKD,EAAQC,EAAK,YAAW,CAAE,EAC1D,GAAIC,IAAW,OAAW,OAAO,MAAM,QAAQA,CAAM,EAAIA,EAAO,CAAC,EAAIA,EAErE,MAAMC,EAASF,EAAK,YAAW,EAC/B,UAAWG,KAAOJ,EAChB,GAAII,EAAI,YAAW,IAAOD,EAAQ,CAChC,MAAME,EAAQL,EAAQI,CAAG,EACzB,OAAO,MAAM,QAAQC,CAAK,EAAIA,EAAM,CAAC,EAAIA,CAC3C,CAEJ",
|
|
6
|
-
"names": ["headers", "name", "direct", "target", "key", "value"]
|
|
7
|
-
}
|
package/rest.d.ts
DELETED
package/rest.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../src/rest.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,UAAU,EACV,WAAW,EACX,SAAS,EACT,kBAAkB,EAClB,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,0BAA0B,CAAC"}
|
package/rest.js
DELETED
package/rest.js.map
DELETED
package/transports/fetch.d.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import type { HyperTransport, LogLevel, HyperProtocolName, TransportListenOptions, TransportRequest, TransportResponse, TransportServer } from "@hyperttp/types";
|
|
2
|
-
export interface FetchTransportOptions {
|
|
3
|
-
/**
|
|
4
|
-
* @ru Кастомный список поддерживаемых протоколов.
|
|
5
|
-
* @en Custom list of supported protocols.
|
|
6
|
-
*/
|
|
7
|
-
protocols?: HyperProtocolName[];
|
|
8
|
-
/**
|
|
9
|
-
* @ru Максимальный размер входящего серверного тела в байтах. Превышение
|
|
10
|
-
* возвращает HTTP 413 до передачи тела обработчику.
|
|
11
|
-
* @en Maximum incoming server request body size in bytes. Exceeding it returns
|
|
12
|
-
* HTTP 413 before the body reaches the handler.
|
|
13
|
-
*/
|
|
14
|
-
maxBodyBytes?: number;
|
|
15
|
-
/**
|
|
16
|
-
* @ru Обработчик ошибок входящих серверных запросов.
|
|
17
|
-
* @en Error hook for incoming server requests.
|
|
18
|
-
*/
|
|
19
|
-
onError?: (error: unknown, request: TransportRequest) => void;
|
|
20
|
-
logger?: (level: LogLevel, message: string, meta?: unknown) => void;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* @ru Минимальный транспорт на базе нативного fetch. Гарантированный fallback,
|
|
24
|
-
* когда ни один пакетный транспорт (@hyperttp/transport-undici/bun) не установлен.
|
|
25
|
-
* @en Minimal native fetch-based transport. A guaranteed fallback used when no
|
|
26
|
-
* packaged transport (@hyperttp/transport-undici/bun) is installed.
|
|
27
|
-
*/
|
|
28
|
-
export declare class FetchTransport implements HyperTransport {
|
|
29
|
-
readonly protocols: readonly HyperProtocolName[];
|
|
30
|
-
private readonly maxBodyBytes;
|
|
31
|
-
private readonly onError?;
|
|
32
|
-
private readonly logger?;
|
|
33
|
-
/**
|
|
34
|
-
* @ru Создаёт fallback-транспорт на базе глобального `fetch`.
|
|
35
|
-
* @en Creates a fallback transport based on global `fetch`.
|
|
36
|
-
* @param options - Поддерживаемые протоколы и серверный лимит тела. @en Supported protocols and server body limit.
|
|
37
|
-
*/
|
|
38
|
-
constructor(options?: FetchTransportOptions);
|
|
39
|
-
execute(req: TransportRequest): Promise<TransportResponse>;
|
|
40
|
-
listen(options: TransportListenOptions): Promise<TransportServer>;
|
|
41
|
-
close(): Promise<void>;
|
|
42
|
-
}
|
|
43
|
-
//# sourceMappingURL=fetch.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/transports/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,cAAc,EACd,QAAQ,EACR,iBAAiB,EACjB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EAChB,MAAM,iBAAiB,CAAC;AAIzB,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAChC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC9D,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;CACrE;AA+CD;;;;;GAKG;AACH,qBAAa,cAAe,YAAW,cAAc;IACnD,SAAgB,SAAS,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACxD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAmC;IAC5D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAkC;IAE1D;;;;OAIG;IACH,YAAY,OAAO,GAAE,qBAA0B,EAQ9C;IAEY,OAAO,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA4CtE;IAEY,MAAM,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,eAAe,CAAC,CAsM7E;IAEY,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAG;CACvC"}
|
package/transports/fetch.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";import{dynamicImport as B}from"../utils/modules.js";const H=10*1024*1024;async function I(){if(typeof process>"u"||!process.versions?.node)throw new Error("[FetchTransport] listen() is only available in Node.js.");return B("node:http")}async function*j(T,o){const c=T.getReader();let h=!1;const t=()=>{c.cancel(o.reason).catch(()=>{})};o.addEventListener("abort",t,{once:!0}),o.aborted&&t();try{for(;;){const y=await c.read();if(y.done){h=!0;return}yield y.value}}finally{o.removeEventListener("abort",t);try{h||await c.cancel()}finally{c.releaseLock()}}}export class FetchTransport{protocols;maxBodyBytes;onError;logger;constructor(o={}){if(this.protocols=Object.freeze(o.protocols??["rest"]),this.maxBodyBytes=o.maxBodyBytes??H,!Number.isSafeInteger(this.maxBodyBytes)||this.maxBodyBytes<0)throw new RangeError("[FetchTransport] maxBodyBytes must be a non-negative safe integer.");this.onError=o.onError,this.logger=o.logger}async execute(o){const c=o,h=o.method!=="GET"&&o.method!=="HEAD",t=await fetch(o.url,{method:o.method,headers:o.headers,body:h?o.body??null:null,signal:o.signal,redirect:c.followRedirects===!1?"manual":"follow"}),y=c.stream?t.body:new Uint8Array(await t.arrayBuffer()),d={};if(typeof t.headers.getSetCookie=="function"){const s=t.headers.getSetCookie();s.length>0&&(d["set-cookie"]=s)}return t.headers.forEach((s,b)=>{const a=b.toLowerCase();if(!(a==="set-cookie"&&d["set-cookie"]))if(d[a]){const l=d[a];d[a]=Array.isArray(l)?[...l,s]:[l,s]}else d[a]=s}),{status:t.status,statusText:t.statusText,headers:d,url:t.url,body:y}}async listen(o){const{host:c,port:h,signal:t,onRequest:y}=o;if(t?.aborted)throw t.reason??new DOMException("The operation was aborted","AbortError");const{createServer:d}=await I(),s=d(async(r,e)=>{const n=new AbortController,m=()=>{n.signal.aborted||n.abort(new DOMException("Client disconnected","AbortError"))},x=()=>{r.complete||m()},R=()=>{e.writableEnded||m()};r.once("aborted",m),r.once("close",x),e.once("close",R);try{const E=Number(r.headers["content-length"]??0);if(Number.isFinite(E)&&E>this.maxBodyBytes){e.writeHead(413),e.end("Payload Too Large");return}const v=[];let L=0;for await(const f of r){if(L+=f.byteLength,L>this.maxBodyBytes){e.writeHead(413),e.end("Payload Too Large");return}v.push(f)}const k=v.length>0?Buffer.concat(v):void 0,S={};for(const[f,p]of Object.entries(r.headers))p!==void 0&&(S[f]=p);const N={method:r.method??"GET",url:r.url??"/",headers:S,body:k,signal:n.signal,protocol:this.protocols[0]??"rest"};if(!y){e.writeHead(501),e.end("Not Implemented");return}const i=await y(N),A={};for(const[f,p]of Object.entries(i.headers))A[f]=p;e.writeHead(i.status,i.statusText??"",A);const u=i.body;if(u!=null&&typeof u=="object"&&(typeof ReadableStream<"u"&&u instanceof ReadableStream||Symbol.asyncIterator in u)){const[{Readable:f},{pipeline:p}]=await Promise.all([B("node:stream"),B("node:stream/promises")]),O=u instanceof ReadableStream?j(u,n.signal):u;await p(f.from(O,{objectMode:!1}),e,{signal:n.signal})}else i.body!=null?i.body instanceof Uint8Array||typeof i.body=="string"?e.end(i.body):e.end(JSON.stringify(i.body)):e.end()}catch(E){try{this.onError?.(E,{method:r.method??"GET",url:r.url??"/",headers:r.headers,signal:n.signal,protocol:this.protocols[0]??"rest"})}catch{}e.headersSent?e.destroy():(e.writeHead(500),e.end("Internal Server Error"))}finally{r.removeListener("aborted",m),r.removeListener("close",x),e.removeListener("close",R)}});let b;const a=()=>b||(t?.removeEventListener("abort",w),b=new Promise((r,e)=>{s.close(n=>{s.removeListener("error",g),n&&n.code!=="ERR_SERVER_NOT_RUNNING"?e(n):r()})}),b);let l;const w=()=>{l?l():a().catch(g)},g=r=>{const e="[FetchTransport] HTTP server error";try{this.logger?this.logger("error",e,r):console.error(`${e}:`,r)}catch{}};if(t?.aborted)throw t.reason??new DOMException("The operation was aborted","AbortError");return t?.addEventListener("abort",w,{once:!0}),new Promise((r,e)=>{const n=m=>{l=void 0,t?.removeEventListener("abort",w),s.removeListener("error",n),e(m)};l=()=>{n(t?.reason??new DOMException("The operation was aborted","AbortError")),a().catch(g)},s.once("error",n),s.listen({host:c,port:h,signal:t},()=>{if(t?.aborted){a().catch(g);return}l=void 0,s.removeListener("error",n),s.on("error",g),r({close:a})}),t?.aborted&&w()})}async close(){}}
|
|
2
|
-
//# sourceMappingURL=fetch.js.map
|