@h1r-ai/croche-react-native 0.5.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +90 -451
- package/THIRD-PARTY-NOTICES +906 -14
- package/android/build.gradle +6 -1
- package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
- package/android/src/main/AndroidManifest.xml +0 -5
- package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
- package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
- package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
- package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
- package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
- package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
- package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
- package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
- package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
- package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
- package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +1 -0
- package/dist/package.json +1 -0
- package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
- package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
- package/dist/react-native/src/core-native.d.ts +6 -0
- package/dist/react-native/src/core-native.js +316 -0
- package/dist/react-native/src/core-wire.d.ts +55 -0
- package/dist/react-native/src/core-wire.js +1 -0
- package/dist/react-native/src/native-module.d.ts +8 -0
- package/dist/react-native/src/native-module.js +53 -0
- package/dist/rn-shared-build.json +16 -0
- package/dist/runtime/src/adapters.d.ts +8 -0
- package/dist/runtime/src/adapters.js +29 -0
- package/dist/runtime/src/agent.d.ts +91 -0
- package/dist/runtime/src/agent.js +137 -0
- package/dist/runtime/src/app-api.d.ts +572 -0
- package/dist/runtime/src/app-api.js +1 -0
- package/dist/runtime/src/cancel.d.ts +9 -0
- package/dist/runtime/src/cancel.js +27 -0
- package/dist/runtime/src/core/foreground.d.ts +3 -0
- package/dist/runtime/src/core/foreground.js +40 -0
- package/dist/runtime/src/core/port.d.ts +247 -0
- package/dist/runtime/src/core/port.js +1 -0
- package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
- package/dist/runtime/src/core/wasm-owner.js +237 -0
- package/dist/runtime/src/core/wasm.d.ts +1 -0
- package/dist/runtime/src/core/wasm.js +2 -0
- package/dist/runtime/src/croche.d.ts +97 -0
- package/dist/runtime/src/croche.js +172 -0
- package/dist/runtime/src/errors.d.ts +33 -0
- package/dist/runtime/src/errors.js +63 -0
- package/dist/runtime/src/events.d.ts +5 -0
- package/dist/runtime/src/events.js +31 -0
- package/dist/runtime/src/generated/app-stream.d.ts +328 -0
- package/dist/runtime/src/generated/app-stream.js +127 -0
- package/dist/runtime/src/image-input.d.ts +5 -0
- package/dist/runtime/src/image-input.js +60 -0
- package/dist/runtime/src/index.d.ts +6 -0
- package/dist/runtime/src/index.js +5 -0
- package/dist/runtime/src/index.native.d.ts +1 -0
- package/dist/runtime/src/index.native.js +2 -0
- package/dist/runtime/src/json.d.ts +13 -0
- package/dist/runtime/src/json.js +120 -0
- package/dist/runtime/src/native-adapter.d.ts +3 -0
- package/dist/runtime/src/native-adapter.js +30 -0
- package/dist/runtime/src/pal/host.d.ts +5 -0
- package/dist/runtime/src/pal/host.js +60 -0
- package/dist/runtime/src/pal/platform.d.ts +21 -0
- package/dist/runtime/src/pal/platform.js +7 -0
- package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
- package/dist/runtime/src/pal/state-store-lock.js +2 -0
- package/dist/runtime/src/pal/state-store.d.ts +66 -0
- package/dist/runtime/src/pal/state-store.js +1 -0
- package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
- package/dist/runtime/src/pal/storage-version-contract.js +68 -0
- package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
- package/dist/runtime/src/pal/transactional-storage.js +124 -0
- package/dist/runtime/src/rn-entry.d.ts +1 -0
- package/dist/runtime/src/rn-entry.js +4 -0
- package/dist/runtime/src/run-tool.d.ts +33 -0
- package/dist/runtime/src/run-tool.js +7 -0
- package/dist/runtime/src/tools.d.ts +35 -0
- package/dist/runtime/src/tools.js +94 -0
- package/ios/CoreAgentTransport.swift +14 -0
- package/ios/CoreDeliveryTransport.swift +58 -0
- package/ios/CoreNativePal.swift +98 -0
- package/ios/CorePlatformTransport.swift +44 -0
- package/ios/CoreWireDispatch.swift +122 -0
- package/ios/CoreWireSupport.swift +286 -0
- package/ios/CrocheRuntimeBridge.swift +34 -994
- package/ios/ProjectPal.swift +49 -0
- package/ios/RNCrocheRuntime.mm +18 -201
- package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
- package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
- package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
- package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
- package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
- package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
- package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
- package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
- package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
- package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
- package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
- package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
- package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
- package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
- package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
- package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +18 -8
- package/scripts/README.md +11 -0
- package/scripts/build-shared.mjs +46 -0
- package/scripts/build.mjs +11 -0
- package/scripts/check-swift-vendor-modules.sh +15 -0
- package/scripts/vendor-native.sh +8 -6
- package/src/NativeCrocheRuntime.ts +12 -159
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
- package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
- package/src/index.ts +0 -664
- package/src/project-types.ts +0 -35
- package/src/project.ts +0 -434
- package/src/protocol.ts +0 -28
- package/src/types.ts +0 -9
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(Network)
|
|
3
|
+
import Network
|
|
4
|
+
import Security
|
|
5
|
+
|
|
6
|
+
/// One direct HTTP/1.1 exchange to Core's pinned address (parity with Android's DirectHttpPal):
|
|
7
|
+
/// Network.framework to `connectTo`, TLS server name AND peer verification = the URL host, ALPN
|
|
8
|
+
/// http/1.1 only, no redirects, proxy, pool, cookies or cache. Core supplies policy and the
|
|
9
|
+
/// deadline; this supplies bytes. Shared cases: vectors/http-pal-direct.json.
|
|
10
|
+
final class DirectHTTP: @unchecked Sendable {
|
|
11
|
+
/// Test anchors only (the vector harness's throwaway certificate); nil = the system trust store.
|
|
12
|
+
private let anchors: [SecCertificate]?
|
|
13
|
+
init(anchors: [SecCertificate]? = nil) { self.anchors = anchors }
|
|
14
|
+
|
|
15
|
+
private static let lineLimit = 8192, headLimit = 65536, interimLimit = 16
|
|
16
|
+
|
|
17
|
+
func http(_ request: PalHttpRequest, pin: String, sink: any HttpSinkProtocol, cancel: CancelToken) throws {
|
|
18
|
+
guard let url = URLComponents(string: request.url), let rawHost = url.host, !rawHost.isEmpty,
|
|
19
|
+
let scheme = url.scheme, scheme == "https" || scheme == "http" else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP URL") }
|
|
20
|
+
guard url.user == nil, url.password == nil else { throw LegacyCrocheError("invalid_abi", "HTTP user info is unsupported") }
|
|
21
|
+
let host = rawHost.hasPrefix("[") ? String(rawHost.dropFirst().dropLast()) : rawHost
|
|
22
|
+
let address = try Self.numeric(pin)
|
|
23
|
+
let tls = scheme == "https"
|
|
24
|
+
let port = url.port ?? (tls ? 443 : 80)
|
|
25
|
+
guard let endpointPort = NWEndpoint.Port(rawValue: UInt16(clamping: port)) else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP port") }
|
|
26
|
+
let head = try Self.requestHead(request, url: url)
|
|
27
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
28
|
+
|
|
29
|
+
let connection = NWConnection(host: address, port: endpointPort, using: parameters(tls: tls, host: host))
|
|
30
|
+
let wire = Wire(connection)
|
|
31
|
+
cancel.onCancel(callback: Closer(wire, reason: "cancelled"))
|
|
32
|
+
let deadline = DispatchWorkItem { wire.close(reason: "deadline") }
|
|
33
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(Int(clamping: max(1, request.timeoutMs))), execute: deadline)
|
|
34
|
+
defer { deadline.cancel(); wire.close(reason: nil) }
|
|
35
|
+
do {
|
|
36
|
+
try wire.start()
|
|
37
|
+
try wire.send(head + Data((request.body ?? "").utf8))
|
|
38
|
+
try Self.readResponse(wire, request, sink, cancel)
|
|
39
|
+
} catch {
|
|
40
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
41
|
+
if let error = error as? LegacyCrocheError, error.code != "network_error" { throw error }
|
|
42
|
+
throw LegacyCrocheError("network_error", "HTTP transport failed")
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private func parameters(tls: Bool, host: String) -> NWParameters {
|
|
47
|
+
let tcp = NWProtocolTCP.Options()
|
|
48
|
+
guard tls else { let p = NWParameters(tls: nil, tcp: tcp); p.preferNoProxies = true; return p }
|
|
49
|
+
let options = NWProtocolTLS.Options(), sec = options.securityProtocolOptions
|
|
50
|
+
sec_protocol_options_set_tls_server_name(sec, host)
|
|
51
|
+
sec_protocol_options_add_tls_application_protocol(sec, "http/1.1")
|
|
52
|
+
let anchors = self.anchors
|
|
53
|
+
// The name verified is the URL host, never the pinned address.
|
|
54
|
+
sec_protocol_options_set_verify_block(sec, { _, trustRef, complete in
|
|
55
|
+
let trust = sec_trust_copy_ref(trustRef).takeRetainedValue()
|
|
56
|
+
SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, host as CFString))
|
|
57
|
+
if let anchors { SecTrustSetAnchorCertificates(trust, anchors as CFArray); SecTrustSetAnchorCertificatesOnly(trust, true) }
|
|
58
|
+
complete(SecTrustEvaluateWithError(trust, nil))
|
|
59
|
+
}, DispatchQueue.global())
|
|
60
|
+
let p = NWParameters(tls: options, tcp: tcp); p.preferNoProxies = true
|
|
61
|
+
return p
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// A malformed pin never reaches a resolver or an unpinned fallback.
|
|
65
|
+
static func numeric(_ pin: String) throws -> NWEndpoint.Host {
|
|
66
|
+
if let v4 = IPv4Address(pin), pin.split(separator: ".").count == 4, pin.allSatisfy({ $0.isNumber || $0 == "." }) { return .ipv4(v4) }
|
|
67
|
+
if pin.contains(":"), pin.allSatisfy({ $0.isHexDigit || $0 == ":" || $0 == "." }), let v6 = IPv6Address(pin) { return .ipv6(v6) }
|
|
68
|
+
throw LegacyCrocheError("invalid_abi", "Invalid HTTP connectTo")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static func requestHead(_ request: PalHttpRequest, url: URLComponents) throws -> Data {
|
|
72
|
+
let target = (url.percentEncodedPath.isEmpty ? "/" : url.percentEncodedPath) + (url.percentEncodedQuery.map { "?" + $0 } ?? "")
|
|
73
|
+
let authority = (url.percentEncodedHost ?? "") + (url.port.map { ":\($0)" } ?? "")
|
|
74
|
+
func line(_ value: String) throws -> String {
|
|
75
|
+
// Bytes, not Characters: "\r\n" is one grapheme, so contains("\r") would miss it.
|
|
76
|
+
guard !value.utf8.contains(13), !value.utf8.contains(10) else { throw LegacyCrocheError("invalid_abi", "Invalid HTTP request line") }
|
|
77
|
+
return value
|
|
78
|
+
}
|
|
79
|
+
var text = "\(try line(request.method)) \(try line(target)) HTTP/1.1\r\nHost: \(authority)\r\nConnection: close\r\n"
|
|
80
|
+
for header in request.headers where !["host", "connection", "content-length", "transfer-encoding"].contains(header.name.lowercased()) {
|
|
81
|
+
text += "\(try line(header.name)): \(try line(header.value))\r\n"
|
|
82
|
+
}
|
|
83
|
+
if let body = request.body { text += "Content-Length: \(body.utf8.count)\r\n" }
|
|
84
|
+
return Data((text + "\r\n").utf8)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private static func bad(_ what: String) -> LegacyCrocheError { LegacyCrocheError("network_error", what) }
|
|
88
|
+
|
|
89
|
+
static func readResponse(_ wire: Wire, _ request: PalHttpRequest, _ sink: any HttpSinkProtocol, _ cancel: CancelToken) throws {
|
|
90
|
+
var status = 0, headers: [PalHeader] = [], interims = 0
|
|
91
|
+
repeat {
|
|
92
|
+
let statusLine = try wire.line(limit: lineLimit)
|
|
93
|
+
let parts = statusLine.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: false)
|
|
94
|
+
guard statusLine.hasPrefix("HTTP/1."), parts.count >= 2, let code = Int(parts[1]), (100...599).contains(code) else { throw bad("Invalid HTTP status") }
|
|
95
|
+
status = code; headers = []
|
|
96
|
+
var bytes = statusLine.utf8.count
|
|
97
|
+
while true {
|
|
98
|
+
let field = try wire.line(limit: lineLimit)
|
|
99
|
+
bytes += field.utf8.count + 2
|
|
100
|
+
guard bytes <= headLimit else { throw bad("HTTP headers exceed bound") }
|
|
101
|
+
if field.isEmpty { break }
|
|
102
|
+
guard let colon = field.firstIndex(of: ":"), colon != field.startIndex, !(field.first?.isWhitespace ?? true) else { throw bad("Invalid HTTP header") }
|
|
103
|
+
headers.append(PalHeader(name: String(field[..<colon]), value: field[field.index(after: colon)...].trimmingCharacters(in: .whitespaces)))
|
|
104
|
+
}
|
|
105
|
+
interims += 1
|
|
106
|
+
guard interims <= interimLimit else { throw bad("Too many interim responses") }
|
|
107
|
+
} while (100...199).contains(status) && status != 101
|
|
108
|
+
sink.head(status: UInt16(status), headers: headers)
|
|
109
|
+
if request.method == "HEAD" || (100...199).contains(status) || status == 204 || status == 304 { return }
|
|
110
|
+
let lengths = Set(headers.filter { $0.name.lowercased() == "content-length" }.map(\.value))
|
|
111
|
+
guard lengths.count <= 1 else { throw bad("Conflicting HTTP lengths") }
|
|
112
|
+
let codings = headers.filter { $0.name.lowercased() == "transfer-encoding" }.map { $0.value.lowercased() }
|
|
113
|
+
guard codings.isEmpty || codings == ["chunked"] else { throw bad("Unsupported HTTP transfer coding") }
|
|
114
|
+
var received: UInt64 = 0
|
|
115
|
+
/// false = the sink wants no more.
|
|
116
|
+
func copy(_ count: Int?) throws -> Bool {
|
|
117
|
+
var remaining = count
|
|
118
|
+
while remaining.map({ $0 > 0 }) ?? true {
|
|
119
|
+
if cancel.isCancelled() { throw LegacyCrocheError("cancelled", "The request was cancelled.") }
|
|
120
|
+
guard let piece = try wire.read(max: min(remaining ?? 65536, 65536)) else {
|
|
121
|
+
if remaining != nil { throw bad("HTTP body ended early") }
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
received += UInt64(piece.count)
|
|
125
|
+
guard received <= request.maxResponseBytes else { throw LegacyCrocheError("invalid_response", "HTTP response exceeds bound") }
|
|
126
|
+
if !sink.chunk(bytes: piece) { return false }
|
|
127
|
+
remaining = remaining.map { $0 - piece.count }
|
|
128
|
+
}
|
|
129
|
+
return true
|
|
130
|
+
}
|
|
131
|
+
if !codings.isEmpty {
|
|
132
|
+
while true {
|
|
133
|
+
let sizeLine = try wire.line(limit: lineLimit)
|
|
134
|
+
let digits = sizeLine.split(separator: ";", maxSplits: 1, omittingEmptySubsequences: false).first?.trimmingCharacters(in: .whitespaces) ?? ""
|
|
135
|
+
guard !digits.isEmpty, digits.allSatisfy(\.isHexDigit), let size = Int(digits, radix: 16) else { throw bad("Invalid HTTP chunk") }
|
|
136
|
+
if size == 0 {
|
|
137
|
+
var trailerBytes = 0
|
|
138
|
+
while true {
|
|
139
|
+
let trailer = try wire.line(limit: lineLimit)
|
|
140
|
+
trailerBytes += trailer.utf8.count + 2
|
|
141
|
+
guard trailerBytes <= headLimit else { throw bad("HTTP trailers exceed bound") }
|
|
142
|
+
if trailer.isEmpty { return }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if try !copy(size) { return }
|
|
146
|
+
guard try wire.line(limit: lineLimit).isEmpty else { throw bad("Invalid chunk terminator") }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if let text = lengths.first {
|
|
150
|
+
guard text.allSatisfy(\.isNumber), let length = Int(text) else { throw bad("Invalid HTTP length") }
|
|
151
|
+
_ = try copy(length)
|
|
152
|
+
} else { _ = try copy(nil) }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/// A blocking view of one connection for the PAL's worker thread: start, send, and buffered reads.
|
|
157
|
+
final class Wire: @unchecked Sendable {
|
|
158
|
+
private let connection: NWConnection
|
|
159
|
+
private let queue = DispatchQueue(label: "ai.croche.direct-http")
|
|
160
|
+
private var buffer = Data()
|
|
161
|
+
private var ended = false
|
|
162
|
+
private let lock = NSLock()
|
|
163
|
+
private var closedReason: String?
|
|
164
|
+
init(_ connection: NWConnection) { self.connection = connection }
|
|
165
|
+
|
|
166
|
+
func close(reason: String?) {
|
|
167
|
+
lock.withLock { if closedReason == nil { closedReason = reason ?? "closed" } }
|
|
168
|
+
connection.cancel()
|
|
169
|
+
}
|
|
170
|
+
private func failIfClosed() throws {
|
|
171
|
+
if let reason = lock.withLock({ closedReason }) { throw LegacyCrocheError(reason == "cancelled" ? "cancelled" : "network_error", "HTTP transport \(reason)") }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
func start() throws {
|
|
175
|
+
let ready = DispatchSemaphore(value: 0)
|
|
176
|
+
let outcome = Box<Bool>()
|
|
177
|
+
connection.stateUpdateHandler = { state in
|
|
178
|
+
switch state {
|
|
179
|
+
case .ready: outcome.once(true) { ready.signal() }
|
|
180
|
+
case .failed, .cancelled, .waiting: outcome.once(false) { ready.signal() }
|
|
181
|
+
default: break
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
connection.start(queue: queue)
|
|
185
|
+
ready.wait()
|
|
186
|
+
try failIfClosed()
|
|
187
|
+
guard outcome.value == true else { throw LegacyCrocheError("network_error", "HTTP connection failed") }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
func send(_ data: Data) throws {
|
|
191
|
+
let done = DispatchSemaphore(value: 0), failed = Box<Bool>()
|
|
192
|
+
connection.send(content: data, completion: .contentProcessed { error in failed.once(error != nil) { done.signal() } })
|
|
193
|
+
done.wait()
|
|
194
|
+
try failIfClosed()
|
|
195
|
+
if failed.value == true { throw LegacyCrocheError("network_error", "HTTP send failed") }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/// Fills the buffer once. false = the peer ended the stream.
|
|
199
|
+
private func fill() throws -> Bool {
|
|
200
|
+
if ended { return false }
|
|
201
|
+
let done = DispatchSemaphore(value: 0)
|
|
202
|
+
let result = Box<(Data?, Bool, Bool)>()
|
|
203
|
+
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { data, _, complete, error in
|
|
204
|
+
result.once((data, complete, error != nil)) { done.signal() }
|
|
205
|
+
}
|
|
206
|
+
done.wait()
|
|
207
|
+
try failIfClosed()
|
|
208
|
+
guard let (data, complete, failed) = result.value, !failed else { throw LegacyCrocheError("network_error", "HTTP receive failed") }
|
|
209
|
+
if let data { buffer.append(data) }
|
|
210
|
+
if complete { ended = true }
|
|
211
|
+
return !(data?.isEmpty ?? true) || !complete
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// One CRLF-terminated line, without it. A bare LF, an over-long line or EOF fails.
|
|
215
|
+
func line(limit: Int) throws -> String {
|
|
216
|
+
while true {
|
|
217
|
+
if let cr = buffer.firstIndex(of: 13) {
|
|
218
|
+
guard cr - buffer.startIndex <= limit else { throw LegacyCrocheError("network_error", "HTTP line exceeds bound") }
|
|
219
|
+
guard buffer.index(after: cr) < buffer.endIndex else { if try !fill() { throw LegacyCrocheError("network_error", "HTTP stream ended") }; continue }
|
|
220
|
+
guard buffer[buffer.index(after: cr)] == 10 else { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
221
|
+
if buffer[buffer.startIndex..<cr].contains(10) { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
222
|
+
let text = String(decoding: buffer[buffer.startIndex..<cr], as: UTF8.self)
|
|
223
|
+
buffer.removeSubrange(buffer.startIndex...buffer.index(after: cr))
|
|
224
|
+
return text
|
|
225
|
+
}
|
|
226
|
+
if buffer.contains(10) { throw LegacyCrocheError("network_error", "Invalid HTTP line ending") }
|
|
227
|
+
guard buffer.count <= limit else { throw LegacyCrocheError("network_error", "HTTP line exceeds bound") }
|
|
228
|
+
if try !fill() { throw LegacyCrocheError("network_error", "HTTP stream ended") }
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/// Up to `max` bytes; nil at the end of the stream.
|
|
233
|
+
func read(max: Int) throws -> Data? {
|
|
234
|
+
if buffer.isEmpty, try !fill(), buffer.isEmpty { return nil }
|
|
235
|
+
if buffer.isEmpty { return try read(max: max) }
|
|
236
|
+
let piece = buffer.prefix(max)
|
|
237
|
+
buffer.removeFirst(piece.count)
|
|
238
|
+
return Data(piece)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private final class Box<T>: @unchecked Sendable {
|
|
243
|
+
private let lock = NSLock()
|
|
244
|
+
private var stored: T?
|
|
245
|
+
var value: T? { lock.withLock { stored } }
|
|
246
|
+
func once(_ value: T, _ then: () -> Void) {
|
|
247
|
+
let first = lock.withLock { () -> Bool in guard stored == nil else { return false }; stored = value; return true }
|
|
248
|
+
if first { then() }
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
private final class Closer: CancelCallback, @unchecked Sendable {
|
|
253
|
+
private weak var wire: Wire?
|
|
254
|
+
private let reason: String
|
|
255
|
+
init(_ wire: Wire, reason: String) { self.wire = wire; self.reason = reason }
|
|
256
|
+
func cancelled() { wire?.close(reason: reason) }
|
|
257
|
+
}
|
|
258
|
+
#endif
|
|
@@ -4,16 +4,16 @@ import FoundationNetworking
|
|
|
4
4
|
#endif
|
|
5
5
|
|
|
6
6
|
/// Cooperative tool cancellation. A cancelled invocation is never automatically replayed.
|
|
7
|
-
|
|
7
|
+
final class RuntimeCancellation: @unchecked Sendable {
|
|
8
8
|
private let lock = NSLock()
|
|
9
9
|
private var stopped = false
|
|
10
10
|
private var listeners: [UUID: @Sendable () -> Void] = [:]
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if isCancelled { throw
|
|
11
|
+
init() {}
|
|
12
|
+
var isCancelled: Bool { lock.withLock { stopped } }
|
|
13
|
+
func check() throws {
|
|
14
|
+
if isCancelled { throw LegacyCrocheError("cancelled", "The operation was cancelled") }
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
func cancel() {
|
|
17
17
|
let callbacks = lock.withLock { () -> [@Sendable () -> Void] in
|
|
18
18
|
guard !stopped else { return [] }; stopped = true
|
|
19
19
|
let values = Array(listeners.values); listeners.removeAll(); return values
|
|
@@ -62,7 +62,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
62
62
|
return try await withCheckedThrowingContinuation { continuation in
|
|
63
63
|
let race = EffectRace<T>(continuation)
|
|
64
64
|
let listener = cancellation.observe {
|
|
65
|
-
local.cancel(); race.finish(.failure(
|
|
65
|
+
local.cancel(); race.finish(.failure(LegacyCrocheError("cancelled", "The operation was cancelled")))
|
|
66
66
|
}
|
|
67
67
|
race.add(Task {
|
|
68
68
|
do { try local.check(); let value = try await body(local); try local.check(); race.finish(.success(value)) }
|
|
@@ -73,7 +73,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
73
73
|
race.add(Task {
|
|
74
74
|
do {
|
|
75
75
|
try await Task.sleep(nanoseconds: UInt64(max(1, milliseconds) * 1_000_000))
|
|
76
|
-
race.finish(.failure(
|
|
76
|
+
race.finish(.failure(LegacyCrocheError("timeout", "The effect deadline expired"))); local.cancel()
|
|
77
77
|
cancellation.remove(listener)
|
|
78
78
|
} catch {}
|
|
79
79
|
})
|
|
@@ -82,7 +82,7 @@ func bounded<T: Sendable>(milliseconds: Double?, cancellation: RuntimeCancellati
|
|
|
82
82
|
|
|
83
83
|
/// `onDelta` receives each server-sent event's data while a streamed response arrives, in
|
|
84
84
|
/// order; the Rust Core assembles them. A transport that cannot stream never calls it.
|
|
85
|
-
|
|
85
|
+
typealias RuntimeHTTP = @Sendable (_ effect: JSON, _ cancellation: RuntimeCancellation,
|
|
86
86
|
_ onDelta: @escaping @Sendable (String) async -> Void) async throws -> JSON
|
|
87
87
|
|
|
88
88
|
private let maxResponseBytes = 2 * 1024 * 1024
|
|
@@ -91,12 +91,12 @@ private let maxStreamBytes = 3 * maxResponseBytes
|
|
|
91
91
|
|
|
92
92
|
/// Ephemeral URLSession transport: no cookies/cache, no redirects, 2MiB response bound.
|
|
93
93
|
/// A `text/event-stream` answer is read incrementally and its deltas are handed on.
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
enum RuntimeURLSession {
|
|
95
|
+
static func send(_ effect: JSON, cancellation: RuntimeCancellation,
|
|
96
96
|
onDelta: @escaping @Sendable (String) async -> Void = { _ in }) async throws -> JSON {
|
|
97
97
|
try cancellation.check()
|
|
98
98
|
guard let address = effect["url"].string, let url = URL(string: address) else {
|
|
99
|
-
throw
|
|
99
|
+
throw LegacyCrocheError("network_error", "Invalid HTTP effect URL")
|
|
100
100
|
}
|
|
101
101
|
var request = URLRequest(url: url)
|
|
102
102
|
request.httpMethod = effect["method"].string
|
|
@@ -136,15 +136,15 @@ public enum RuntimeURLSession {
|
|
|
136
136
|
// event stream is read incrementally.
|
|
137
137
|
streaming = (200..<300).contains(code) && type.lowercased().hasPrefix("text/event-stream")
|
|
138
138
|
if !streaming && expected > Int64(maxResponseBytes) {
|
|
139
|
-
throw
|
|
139
|
+
throw LegacyCrocheError("invalid_response", "HTTP response exceeds 2MiB")
|
|
140
140
|
}
|
|
141
141
|
case .body(let data):
|
|
142
142
|
size += data.count
|
|
143
143
|
if !streaming {
|
|
144
|
-
guard size <= maxResponseBytes else { throw
|
|
144
|
+
guard size <= maxResponseBytes else { throw LegacyCrocheError("invalid_response", "HTTP response exceeds 2MiB") }
|
|
145
145
|
body.append(data); continue
|
|
146
146
|
}
|
|
147
|
-
guard size <= maxStreamBytes else { throw
|
|
147
|
+
guard size <= maxStreamBytes else { throw LegacyCrocheError("invalid_provider_response", "The gateway stream exceeds its bound") }
|
|
148
148
|
for event in parser.push([UInt8](data)) where !event.data.isEmpty { await onDelta(event.data) }
|
|
149
149
|
}
|
|
150
150
|
}
|
|
@@ -177,7 +177,7 @@ private final class HTTPDelegate: NSObject, URLSessionDataDelegate, @unchecked S
|
|
|
177
177
|
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
|
|
178
178
|
didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
|
|
179
179
|
guard let http = response as? HTTPURLResponse else {
|
|
180
|
-
sink.finish(throwing:
|
|
180
|
+
sink.finish(throwing: LegacyCrocheError("network_error", "No HTTP response")); completionHandler(.cancel); return
|
|
181
181
|
}
|
|
182
182
|
var headers: [String: JSON] = [:]
|
|
183
183
|
for (key, value) in http.allHeaderFields { headers[String(describing: key)] = .string(String(describing: value)) }
|
|
@@ -188,7 +188,7 @@ private final class HTTPDelegate: NSObject, URLSessionDataDelegate, @unchecked S
|
|
|
188
188
|
sink.yield(.body(chunk))
|
|
189
189
|
}
|
|
190
190
|
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
191
|
-
if error != nil { sink.finish(throwing:
|
|
191
|
+
if error != nil { sink.finish(throwing: LegacyCrocheError("network_error", "HTTP transport failed")) }
|
|
192
192
|
else { sink.finish() }
|
|
193
193
|
}
|
|
194
194
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
// Platform-private pixel handles; the Core ABI carries encoded files only.
|
|
4
|
+
struct DecodedImage { let handle: String; let width: UInt32; let height: UInt32; let hasAlpha: Bool? }
|
|
5
|
+
struct ImageDecodeOptions { let frame: UInt32; let applyOrientation: Bool }
|
|
6
|
+
enum ImageFormat { case png, jpeg }
|
|
7
|
+
struct ImageRenderRequest {
|
|
8
|
+
let handle: String; let width: UInt32; let height: UInt32
|
|
9
|
+
let format: ImageFormat; let quality: Double?
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
extension NativeImagePal {
|
|
13
|
+
var support: ImageSupport? {
|
|
14
|
+
guard codecAvailable else { return nil }
|
|
15
|
+
return ImageSupport(inputMediaTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"],
|
|
16
|
+
outputMediaTypes: ["image/png", "image/jpeg"], maxInputPixels: 50_000_000)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Both metadata and resizing decode the upright first frame, including EXIF orientation.
|
|
20
|
+
func operation(_ operation: String, _ bytes: Data, _ options: String, _ cancel: CancelToken) throws -> PalImageReply {
|
|
21
|
+
guard operation == "info" || operation == "resize" else { throw imageOperationUnsupported() }
|
|
22
|
+
let image = try decode(bytes, ImageDecodeOptions(frame: 0, applyOrientation: true), cancel)
|
|
23
|
+
defer { releaseDecoded(image.handle) }
|
|
24
|
+
if operation == "info" {
|
|
25
|
+
guard let mediaType = Self.mime(bytes) else { throw imageOperationUnsupported() }
|
|
26
|
+
let info = ImageInfo(mediaType: mediaType, width: Int(image.width), height: Int(image.height), hasAlpha: image.hasAlpha)
|
|
27
|
+
return PalImageReply(metadataJson: text(info.json), bytes: Data())
|
|
28
|
+
}
|
|
29
|
+
let limits = try ImageResizeLimits(JSON(options))
|
|
30
|
+
let scale = limits.maxSide.map { min(1, Double($0) / Double(max(image.width, image.height))) } ?? 1
|
|
31
|
+
var width = max(1, Int((Double(image.width) * scale).rounded()))
|
|
32
|
+
var height = max(1, Int((Double(image.height) * scale).rounded()))
|
|
33
|
+
for attempt in 0..<8 {
|
|
34
|
+
try Self.check(cancel)
|
|
35
|
+
var candidates: [Data] = []
|
|
36
|
+
if limits.outputMediaTypes.contains("image/png") {
|
|
37
|
+
candidates.append(try render(ImageRenderRequest(handle: image.handle, width: UInt32(width), height: UInt32(height), format: .png, quality: nil), cancel))
|
|
38
|
+
}
|
|
39
|
+
if limits.outputMediaTypes.contains("image/jpeg"), image.hasAlpha == false {
|
|
40
|
+
candidates.append(try render(ImageRenderRequest(handle: image.handle, width: UInt32(width), height: UInt32(height), format: .jpeg, quality: 0.7), cancel))
|
|
41
|
+
}
|
|
42
|
+
guard let best = candidates.min(by: { $0.count < $1.count }) else { throw imageOperationUnsupported() }
|
|
43
|
+
if best.count <= limits.maxBytes { return PalImageReply(metadataJson: "{}", bytes: best) }
|
|
44
|
+
if width == 1 && height == 1 { break }
|
|
45
|
+
let shrink = min(0.8, max(0.1, sqrt(Double(limits.maxBytes) / Double(best.count)) * 0.9))
|
|
46
|
+
width = attempt == 6 ? 1 : max(1, Int(Double(width) * shrink))
|
|
47
|
+
height = attempt == 6 ? 1 : max(1, Int(Double(height) * shrink))
|
|
48
|
+
}
|
|
49
|
+
throw imageOperationUnsupported()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private func imageOperationUnsupported() -> CorePalError {
|
|
54
|
+
.Failure(code: "image_unsupported", detail: "The image operation is not supported.")
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Core's synchronous effect waits for the app's async adapter. Task cancellation is AbortSignal.
|
|
58
|
+
func runImageAdapterOperation(_ image: any ImageAdapter, _ operation: String, _ bytes: Data,
|
|
59
|
+
_ options: String, _ cancel: CancelToken) throws -> PalImageReply {
|
|
60
|
+
try NativeImagePal.check(cancel)
|
|
61
|
+
let done = DispatchSemaphore(value: 0), box = ResultBox<PalImageReply>()
|
|
62
|
+
let task = appTask {
|
|
63
|
+
do {
|
|
64
|
+
try NativeImagePal.check(cancel)
|
|
65
|
+
try Task.checkCancellation()
|
|
66
|
+
let reply: PalImageReply
|
|
67
|
+
switch operation {
|
|
68
|
+
case "info": reply = PalImageReply(metadataJson: text(try await image.info(bytes).json), bytes: Data())
|
|
69
|
+
case "resize": reply = PalImageReply(metadataJson: "{}", bytes: try await image.resize(bytes, limits: ImageResizeLimits(JSON(options))))
|
|
70
|
+
default: throw imageOperationUnsupported()
|
|
71
|
+
}
|
|
72
|
+
box.set(.success(reply))
|
|
73
|
+
} catch { box.set(.failure(error)) }
|
|
74
|
+
done.signal()
|
|
75
|
+
}
|
|
76
|
+
cancel.onCancel(callback: ImageTaskCancel(task))
|
|
77
|
+
if cancel.isCancelled() { task.cancel() }
|
|
78
|
+
done.wait()
|
|
79
|
+
return try box.get()
|
|
80
|
+
}
|
|
81
|
+
private final class ImageTaskCancel: CancelCallback, @unchecked Sendable {
|
|
82
|
+
let task: Task<Void, Never>
|
|
83
|
+
init(_ task: Task<Void, Never>) { self.task = task }
|
|
84
|
+
func cancelled() { task.cancel() }
|
|
85
|
+
}
|