@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.
Files changed (248) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +90 -451
  3. package/THIRD-PARTY-NOTICES +906 -14
  4. package/android/build.gradle +6 -1
  5. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +126 -0
  6. package/android/src/main/AndroidManifest.xml +0 -5
  7. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +106 -0
  8. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +217 -0
  9. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +48 -824
  10. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +68 -0
  11. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  12. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +64 -41
  13. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +64 -0
  14. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  15. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  16. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +44 -0
  17. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  18. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  19. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  20. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  21. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  22. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +10 -8
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +55 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  33. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  34. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +116 -0
  35. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  36. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  37. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  38. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  39. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +108 -0
  40. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +8 -2
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +31 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +25 -1
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +121 -103
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +89 -103
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +20 -360
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +136 -0
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +23 -0
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +26 -21
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +715 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +9 -322
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +16 -28
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +294 -37
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +127 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +73 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +88 -24
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +5723 -3088
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +96 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +30 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +127 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +70 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +64 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  82. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  83. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +60 -0
  84. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  85. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  86. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +43 -0
  87. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  88. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  89. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  90. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  91. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +100 -0
  92. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  93. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  94. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  95. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  96. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  97. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  98. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  99. package/croche-react-native.podspec +1 -0
  100. package/dist/package.json +1 -0
  101. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  102. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  103. package/dist/react-native/src/core-native.d.ts +6 -0
  104. package/dist/react-native/src/core-native.js +316 -0
  105. package/dist/react-native/src/core-wire.d.ts +55 -0
  106. package/dist/react-native/src/core-wire.js +1 -0
  107. package/dist/react-native/src/native-module.d.ts +8 -0
  108. package/dist/react-native/src/native-module.js +53 -0
  109. package/dist/rn-shared-build.json +16 -0
  110. package/dist/runtime/src/adapters.d.ts +8 -0
  111. package/dist/runtime/src/adapters.js +29 -0
  112. package/dist/runtime/src/agent.d.ts +91 -0
  113. package/dist/runtime/src/agent.js +137 -0
  114. package/dist/runtime/src/app-api.d.ts +572 -0
  115. package/dist/runtime/src/app-api.js +1 -0
  116. package/dist/runtime/src/cancel.d.ts +9 -0
  117. package/dist/runtime/src/cancel.js +27 -0
  118. package/dist/runtime/src/core/foreground.d.ts +3 -0
  119. package/dist/runtime/src/core/foreground.js +40 -0
  120. package/dist/runtime/src/core/port.d.ts +247 -0
  121. package/dist/runtime/src/core/port.js +1 -0
  122. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  123. package/dist/runtime/src/core/wasm-owner.js +237 -0
  124. package/dist/runtime/src/core/wasm.d.ts +1 -0
  125. package/dist/runtime/src/core/wasm.js +2 -0
  126. package/dist/runtime/src/croche.d.ts +97 -0
  127. package/dist/runtime/src/croche.js +172 -0
  128. package/dist/runtime/src/errors.d.ts +33 -0
  129. package/dist/runtime/src/errors.js +63 -0
  130. package/dist/runtime/src/events.d.ts +5 -0
  131. package/dist/runtime/src/events.js +31 -0
  132. package/dist/runtime/src/generated/app-stream.d.ts +328 -0
  133. package/dist/runtime/src/generated/app-stream.js +127 -0
  134. package/dist/runtime/src/image-input.d.ts +5 -0
  135. package/dist/runtime/src/image-input.js +60 -0
  136. package/dist/runtime/src/index.d.ts +6 -0
  137. package/dist/runtime/src/index.js +5 -0
  138. package/dist/runtime/src/index.native.d.ts +1 -0
  139. package/dist/runtime/src/index.native.js +2 -0
  140. package/dist/runtime/src/json.d.ts +13 -0
  141. package/dist/runtime/src/json.js +120 -0
  142. package/dist/runtime/src/native-adapter.d.ts +3 -0
  143. package/dist/runtime/src/native-adapter.js +30 -0
  144. package/dist/runtime/src/pal/host.d.ts +5 -0
  145. package/dist/runtime/src/pal/host.js +60 -0
  146. package/dist/runtime/src/pal/platform.d.ts +21 -0
  147. package/dist/runtime/src/pal/platform.js +7 -0
  148. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  149. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  150. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  151. package/dist/runtime/src/pal/state-store.js +1 -0
  152. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  153. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  154. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  155. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  156. package/dist/runtime/src/rn-entry.d.ts +1 -0
  157. package/dist/runtime/src/rn-entry.js +4 -0
  158. package/dist/runtime/src/run-tool.d.ts +33 -0
  159. package/dist/runtime/src/run-tool.js +7 -0
  160. package/dist/runtime/src/tools.d.ts +35 -0
  161. package/dist/runtime/src/tools.js +94 -0
  162. package/ios/CoreAgentTransport.swift +14 -0
  163. package/ios/CoreDeliveryTransport.swift +58 -0
  164. package/ios/CoreNativePal.swift +98 -0
  165. package/ios/CorePlatformTransport.swift +44 -0
  166. package/ios/CoreWireDispatch.swift +122 -0
  167. package/ios/CoreWireSupport.swift +286 -0
  168. package/ios/CrocheRuntimeBridge.swift +34 -994
  169. package/ios/ProjectPal.swift +49 -0
  170. package/ios/RNCrocheRuntime.mm +18 -201
  171. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  172. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  173. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +60 -0
  174. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  175. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  176. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  177. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +26 -157
  178. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +672 -0
  179. package/ios/vendor/CrocheRuntimeSDK/Host.swift +34 -371
  180. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  181. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  182. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  183. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +30 -14
  184. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  185. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +1 -155
  186. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +33 -59
  187. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +289 -0
  188. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +302 -0
  189. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  190. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +281 -0
  191. package/ios/vendor/CrocheRuntimeSDK/Project.swift +4 -269
  192. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +24 -461
  193. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  194. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  195. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +248 -0
  196. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  197. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  198. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +170 -0
  199. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +313 -0
  200. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  201. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +37 -0
  202. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  203. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +346 -0
  204. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +89 -0
  205. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +165 -0
  206. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +100 -0
  207. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +278 -0
  208. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  209. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  210. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  211. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +23 -269
  212. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +163 -116
  213. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  214. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +4712 -2469
  215. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +899 -608
  216. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  217. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +899 -608
  218. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  219. package/package.json +18 -8
  220. package/scripts/README.md +11 -0
  221. package/scripts/build-shared.mjs +46 -0
  222. package/scripts/build.mjs +11 -0
  223. package/scripts/check-swift-vendor-modules.sh +15 -0
  224. package/scripts/vendor-native.sh +8 -6
  225. package/src/NativeCrocheRuntime.ts +12 -159
  226. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  227. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  228. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  229. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  230. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  231. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -110
  232. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  233. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -173
  234. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  235. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  236. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  237. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  238. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  239. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -227
  240. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  241. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  242. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -453
  243. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -38
  244. package/src/index.ts +0 -664
  245. package/src/project-types.ts +0 -35
  246. package/src/project.ts +0 -434
  247. package/src/protocol.ts +0 -28
  248. package/src/types.ts +0 -9
@@ -0,0 +1,302 @@
1
+ import Foundation
2
+ #if canImport(Darwin)
3
+ import Darwin
4
+ #elseif canImport(Glibc)
5
+ import Glibc
6
+ #endif
7
+
8
+ /// The 0.6 iOS platform PAL (ARCHITECTURE §2a, Vale's #820 seam): keyed storage with Keychain
9
+ /// secrets, app assets, resolver facts and HTTP. Core owns names, policy and every deadline.
10
+ /// The legacy hooks Core still declares during its keyed cutover (tool, archive, wake) are
11
+ /// refused or inert here: tools reach Core through `CoreToolDefinition`, and the cutover deletes them.
12
+ final class PlatformPal: HostPal, @unchecked Sendable {
13
+ private let storage: PlatformStorage
14
+ private let blobs: BlobFiles
15
+ let secrets: any PlatformSecrets
16
+ private let directory: URL
17
+ private let bundle: Bundle
18
+ let session = RuntimeSession()
19
+ let images = NativeImagePal()
20
+ let imageAdapter: (any ImageAdapter)?
21
+ /// Where this host runs (a fact Core reads); a React Native host sets `.reactNative`.
22
+ var streamPlatformFact = HostStreamPlatform.other
23
+
24
+ /// The background wake's timer and OS request (APP-API: registerBackground).
25
+ let schedules: PlatformSchedule
26
+ /// The OS launch handler Core installs once (APP-API: registerBackground).
27
+ let registration: PlatformRegistration
28
+ /// App Attest where this device can attest; nil elsewhere (Core then reports `attestation_unavailable`).
29
+ let attestor: (any PlatformAttestor)?
30
+ /// What the factory declares to Core as the attestation platform: nil = this host cannot attest.
31
+ var attestationPlatform: String? { attestor?.platform }
32
+ /// The device's preferred languages, read at each `platformFacts` (the app may change them).
33
+ let preferredLanguages: @Sendable () -> [String]
34
+
35
+ init(directory: URL, secrets: (any PlatformSecrets)? = nil, bundle: Bundle = .main,
36
+ backgroundRequests: (any BackgroundRequests)? = PlatformPal.osBackgroundRequests(),
37
+ backgroundLaunches: (any BackgroundLaunches)? = PlatformPal.osBackgroundLaunches(),
38
+ attestor: (any PlatformAttestor)? = PlatformPal.osAttestor(),
39
+ preferredLanguages: @escaping @Sendable () -> [String] = { Locale.preferredLanguages },
40
+ imageAdapter: (any ImageAdapter)? = nil) {
41
+ self.imageAdapter = imageAdapter
42
+ self.preferredLanguages = preferredLanguages
43
+ let storage = PlatformStorage(directory: directory)
44
+ self.blobs = BlobFiles(directory: directory)
45
+ self.storage = storage; self.directory = directory; self.bundle = bundle
46
+ self.schedules = PlatformSchedule(requests: backgroundRequests); self.attestor = attestor
47
+ self.registration = PlatformRegistration(launches: backgroundLaunches, requests: backgroundRequests)
48
+ #if canImport(Security) && !os(Linux)
49
+ self.secrets = secrets ?? KeychainSecrets()
50
+ #else
51
+ self.secrets = secrets ?? FileSecrets(storage: storage)
52
+ #endif
53
+ }
54
+
55
+ static func osBackgroundRequests() -> (any BackgroundRequests)? {
56
+ #if canImport(BackgroundTasks) && os(iOS)
57
+ return AppRefreshRequests()
58
+ #else
59
+ return nil
60
+ #endif
61
+ }
62
+ static func osBackgroundLaunches() -> (any BackgroundLaunches)? {
63
+ #if canImport(BackgroundTasks) && os(iOS)
64
+ return AppRefreshLaunches()
65
+ #else
66
+ return nil
67
+ #endif
68
+ }
69
+ static func osAttestor() -> (any PlatformAttestor)? {
70
+ #if canImport(DeviceCheck) && os(iOS)
71
+ return AppAttest.supported ? AppAttest() : nil
72
+ #else
73
+ return nil
74
+ #endif
75
+ }
76
+
77
+ /// The platform default store: Application Support/croche, excluded from backup.
78
+ static func standard() throws -> PlatformPal {
79
+ let directory = try NativeProjectFiles.directory(projectDirectory: nil)
80
+ return PlatformPal(directory: directory, secrets: testingSecrets(directory))
81
+ }
82
+ /// Tests keep secrets in files, out of the developer's Keychain (Keel, #861 6537337677).
83
+ static func testingSecrets(_ directory: URL) -> (any PlatformSecrets)? {
84
+ NativeProjectFiles.testing.map { _ in FileSecrets(storage: PlatformStorage(directory: directory)) }
85
+ }
86
+
87
+ private func host<T>(_ body: () throws -> T) throws -> T {
88
+ do { return try body() } catch { throw LegacyCrocheError(error).ffi }
89
+ }
90
+
91
+ func blobOperation(operation: String, key: String, cursor: String?, bytes: Data?) throws -> PalBlobReply {
92
+ try host {
93
+ switch operation {
94
+ case "get":
95
+ return PalBlobReply(bytes: try blobs.get(key), entries: [], nextCursor: nil)
96
+ case "put":
97
+ guard let bytes else { throw CocoaError(.fileWriteUnknown) }
98
+ try blobs.put(key, bytes)
99
+ case "delete":
100
+ try blobs.delete(key)
101
+ case "list":
102
+ let page = try blobs.list(key, cursor: cursor)
103
+ return PalBlobReply(bytes: nil, entries: page.entries.map { PalBlobEntry(key: $0.key, size: $0.size) }, nextCursor: page.nextCursor)
104
+ case "purgeStaging":
105
+ try blobs.purgeStaging(key)
106
+ default:
107
+ throw CocoaError(.fileWriteUnknown)
108
+ }
109
+ return PalBlobReply(bytes: nil, entries: [], nextCursor: nil)
110
+ }
111
+ }
112
+
113
+ // MARK: Storage
114
+ func commitState(ops: [StateOp], condition: StateCondition) throws -> StateCommitResult {
115
+ try storage.commitState(ops, condition)
116
+ }
117
+ func listState(prefix: String, options: StateListOptions) throws -> StatePage {
118
+ try storage.listState(prefix, options)
119
+ }
120
+ func readVersioned(key: String) throws -> CoreVersionedValue { try storage.readVersioned(key).core() }
121
+ func writeIf(key: String, value: String?, expect: String?) throws -> CoreWriteOutcome { try storage.writeIf(key, value, expect).core(for: value) }
122
+ func read(key: String) throws -> String? { try host { try storage.read("state", key) } }
123
+ func write(key: String, value: String) throws { try host { try storage.write("state", key, value) } }
124
+ func remove(key: String) throws { try host { try storage.remove("state", key) } }
125
+ func list(prefix: String) throws -> [String] { try host { try storage.list("state", prefix) } }
126
+ /// Contention is the fact `.held`, never an error (ARCHITECTURE §2a).
127
+ @discardableResult func lock(key: String) throws -> PalLockOutcome { try host { try storage.lock(key) } }
128
+ func unlock(key: String) { storage.unlock(key) }
129
+ func readSecret(key: String) throws -> String? { try host { try secrets.read(key) } }
130
+ func writeSecret(key: String, value: String) throws { try host { try secrets.write(key, value) } }
131
+ func removeSecret(key: String) throws { try host { try secrets.remove(key) } }
132
+ func purgeInstance(prefix: String) throws {
133
+ try host { try purgeStorage(prefix: prefix, localState: true, localSecret: true) }
134
+ }
135
+ func purgeStorage(prefix: String, localState: Bool, localSecret: Bool,
136
+ deleteSecret: () throws -> Void = {}, deleteState: () throws -> Void = {}) throws {
137
+ guard PlatformStorage.valid(prefix), prefix.count > 1, prefix.hasSuffix("/") else {
138
+ throw LegacyCrocheError("storage_error", "Invalid purge prefix.")
139
+ }
140
+ let values = localState ? try storage.instancePurgePlan("state", prefix) : nil
141
+ let secret = localSecret ? try secrets.instancePurgePlan(prefix) : nil
142
+ try eraseInstancePayloads(values: values, secrets: secret, deleteSecret: deleteSecret, deleteState: deleteState)
143
+ }
144
+ func storeIdentity() -> String { directory.standardizedFileURL.path }
145
+
146
+ // MARK: Assets, resolver, facts
147
+ func readAsset(path: String) throws -> Data? { try effect { try PlatformAssets.read(path, bundle: bundle) } }
148
+ func resolve(host name: String, cancel: CancelToken) throws -> [String] { try effect { try PlatformResolver.resolve(name) } }
149
+ /// `debuggable` and `targetKind` come from `AppBuildFacts`, never the SDK's own build macro
150
+ /// (Keel's S2 ruling, pin 4).
151
+ /// Facts only; Core applies them (Keel 23:55Z/00:27Z). `locale`: the device's first preferred
152
+ /// language, which Core uses for an omitted `language`. `attestationPlatform`: set only when this
153
+ /// host has an attestor.
154
+ func platformFacts() -> PalPlatformFacts {
155
+ PalPlatformFacts(targetKind: AppBuildFacts.targetKind, debuggable: AppBuildFacts.debuggable, locale: preferredLanguages().first, attestationPlatform: attestationPlatform)
156
+ }
157
+
158
+ // MARK: HTTP
159
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
160
+ try effect {
161
+ if try PlatformHTTP.direct(request, sink: sink, cancel: cancel) { return }
162
+ let session = session
163
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
164
+ try await session.stream(request, into: sink, cancellation: signal); return true
165
+ }
166
+ }
167
+ }
168
+
169
+ // MARK: Images
170
+ func imageSupport() -> String? { (imageAdapter?.support ?? images.support).map { text($0.json) } }
171
+ func imageOperation(operation: String, bytes: Data, optionsJson: String, cancel: CancelToken) throws -> PalImageReply {
172
+ try effect {
173
+ if let imageAdapter { return try runImageAdapterOperation(imageAdapter, operation, bytes, optionsJson, cancel) }
174
+ return try images.operation(operation, bytes, optionsJson, cancel)
175
+ }
176
+ }
177
+ func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data {
178
+ try effect { try images.read(request, cancel) }
179
+ }
180
+ func releaseImage(capture: String) { images.release(capture) }
181
+ /// A fact about the host, never a batching choice. A React Native host reports .reactNative.
182
+ func streamPlatform() -> HostStreamPlatform { streamPlatformFact }
183
+
184
+ // MARK: Clock, randomness
185
+ func nowMs() -> Double { Date().timeIntervalSince1970 * 1000 }
186
+ func utcOffsetMinutes(atMs: Double) -> Int64 {
187
+ Int64(TimeZone.current.secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
188
+ }
189
+ func random() -> String { UUID().uuidString }
190
+
191
+ // MARK: Attestation, background
192
+ func attest(request: String, timeoutMs: UInt64) throws -> String {
193
+ try PlatformAttestation.run(attestor, request: request, timeoutMs: timeoutMs)
194
+ }
195
+ /// The pending set changed or the store opened: the timer and the OS request follow it.
196
+ func schedule(entries: String) throws { try schedules.apply(entries) }
197
+ /// Core's OS install: the launch handler for `identifier`, then the first request.
198
+ func registerBackground(identifier: String, wake: CoreBackgroundWake) throws {
199
+ try registration.register(identifier, wake)
200
+ }
201
+
202
+ // MARK: Legacy hooks during Core's keyed cutover
203
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
204
+ throw FfiError.Failure(code: "tool_not_dispatched", message: "Tools reach Core through their definitions.")
205
+ }
206
+ func wake(atMs: Double?) {}
207
+ }
208
+
209
+ /// App asset references, resolved unchanged (APP-API: iOS = a main-bundle resource or a
210
+ /// `file://` URL). Missing = nil (Core reports `invalid_wiki`); any other failure = asset_read_failed.
211
+ enum PlatformAssets {
212
+ static func read(_ reference: String, bundle: Bundle) throws -> Data? {
213
+ let file: URL
214
+ if reference.hasPrefix("file://") {
215
+ guard let url = URL(string: reference), url.isFileURL else { throw LegacyCrocheError("asset_read_failed", "The asset URL is malformed.") }
216
+ file = url
217
+ } else {
218
+ guard let url = bundle.url(forResource: reference, withExtension: nil) else { return nil }
219
+ file = url
220
+ }
221
+ var directory: ObjCBool = false
222
+ guard FileManager.default.fileExists(atPath: file.path, isDirectory: &directory) else { return nil }
223
+ guard !directory.boolValue else { throw LegacyCrocheError("asset_read_failed", "The asset is a directory.") }
224
+ do { return try Data(contentsOf: file) } catch { throw LegacyCrocheError("asset_read_failed", "The asset could not be read.") }
225
+ }
226
+ }
227
+
228
+ /// Resolver facts only: every address the system resolver gives, unfiltered. Core owns policy.
229
+ enum PlatformResolver {
230
+ static func resolve(_ name: String) throws -> [String] {
231
+ var hints = addrinfo()
232
+ hints.ai_family = AF_UNSPEC
233
+ #if canImport(Glibc)
234
+ hints.ai_socktype = Int32(SOCK_STREAM.rawValue) // Glibc imports __socket_type as an enum
235
+ #else
236
+ hints.ai_socktype = Int32(SOCK_STREAM)
237
+ #endif
238
+ var list: UnsafeMutablePointer<addrinfo>?
239
+ let status = getaddrinfo(name, nil, &hints, &list)
240
+ guard status == 0, let first = list else { throw LegacyCrocheError("network_error", "The host name did not resolve.") }
241
+ defer { freeaddrinfo(first) }
242
+ var addresses: [String] = []
243
+ for info in sequence(first: first, next: { $0.pointee.ai_next }) {
244
+ var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
245
+ guard getnameinfo(info.pointee.ai_addr, info.pointee.ai_addrlen, &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST) == 0 else { continue }
246
+ let address = String(cString: buffer)
247
+ if !addresses.contains(address) { addresses.append(address) }
248
+ }
249
+ return addresses
250
+ }
251
+ }
252
+
253
+ /// URLSession cannot dial a pinned address while keeping the URL host's Host/SNI. It serves a pin
254
+ /// only where the pin holds trivially (the URL host is that IP literal); any other pin goes to the
255
+ /// direct client, and where there is none it is `capability_unsupported`, never an unpinned success.
256
+ enum PlatformHTTP {
257
+ /// Whether this platform dials a pin that is not the URL's own IP literal. iOS does not in 0.6
258
+ /// (APP-API:42, Keel 15:43Z): a hostname image or debugger URL is `capability_unsupported`
259
+ /// there; IP literals and loopback are unchanged. macOS keeps the pinned dial. Linux has no
260
+ /// direct client (it needs Network.framework), so it does not dial named pins either.
261
+ #if os(iOS) || !canImport(Network)
262
+ static let dialsNamedPins = false
263
+ #else
264
+ static let dialsNamedPins = true
265
+ #endif
266
+
267
+ /// A pinned request goes through the direct client (true = done); an unpinned one, or an
268
+ /// IP-literal pin equal to the URL host, is URLSession's (false). Where the platform does not
269
+ /// dial named pins, any other pin is `capability_unsupported` before a connection.
270
+ static func direct(_ request: PalHttpRequest, sink: any HttpSinkProtocol, cancel: CancelToken,
271
+ dialsNamedPins: Bool = PlatformHTTP.dialsNamedPins) throws -> Bool {
272
+ guard let pin = request.connectTo, (try? check(request)) == nil else { return false }
273
+ if !dialsNamedPins { try check(request) }
274
+ #if canImport(Network)
275
+ try DirectHTTP().http(request, pin: pin, sink: sink, cancel: cancel)
276
+ return true
277
+ #else
278
+ try check(request)
279
+ return false
280
+ #endif
281
+ }
282
+ static func check(_ request: PalHttpRequest) throws {
283
+ guard let pin = request.connectTo else { return }
284
+ guard let host = URLComponents(string: request.url)?.host, isIPLiteral(host), canonical(host) == canonical(pin) else {
285
+ throw LegacyCrocheError("capability_unsupported", "This platform cannot pin a connection to a resolved address.")
286
+ }
287
+ }
288
+ static func isIPLiteral(_ host: String) -> Bool {
289
+ let bare = host.hasPrefix("[") && host.hasSuffix("]") ? String(host.dropFirst().dropLast()) : host
290
+ var v4 = in_addr(), v6 = in6_addr()
291
+ return inet_pton(AF_INET, bare, &v4) == 1 || inet_pton(AF_INET6, bare, &v6) == 1
292
+ }
293
+ /// One spelling per address, so `[::1]` and `::1` (or `0:0::1`) compare equal.
294
+ static func canonical(_ text: String) -> String {
295
+ let bare = text.hasPrefix("[") && text.hasSuffix("]") ? String(text.dropFirst().dropLast()) : text
296
+ var v4 = in_addr(), v6 = in6_addr()
297
+ var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
298
+ if inet_pton(AF_INET, bare, &v4) == 1, inet_ntop(AF_INET, &v4, &buffer, socklen_t(buffer.count)) != nil { return String(cString: buffer) }
299
+ if inet_pton(AF_INET6, bare, &v6) == 1, inet_ntop(AF_INET6, &v6, &buffer, socklen_t(buffer.count)) != nil { return String(cString: buffer) }
300
+ return bare.lowercased()
301
+ }
302
+ }
@@ -0,0 +1,253 @@
1
+ import Foundation
2
+ #if os(Linux)
3
+ import CSQLite
4
+ import Glibc
5
+ #else
6
+ import Darwin
7
+ import SQLite3
8
+ #endif
9
+
10
+ /// The default platform database. The lock protects the connection; SQLite
11
+ /// serializes writers opened by other handles or processes.
12
+ final class PlatformStateStore: @unchecked Sendable {
13
+ private let path: URL
14
+ private let gate = NSLock()
15
+ private var connection: OpaquePointer?
16
+ var beforeCommit: (() throws -> Void)?
17
+
18
+ init(path: URL) { self.path = path }
19
+
20
+ #if DEBUG
21
+ /// SQLite's own step count for the latest `list`: how much of the table that page visited.
22
+ /// Debug builds only, for the range-read test (HLD storage, "Range reads").
23
+ private(set) var lastListSteps: Int32 = 0
24
+ #endif
25
+
26
+ deinit {
27
+ if let connection { sqlite3_close(connection) }
28
+ }
29
+
30
+ private func database(create: Bool) throws -> OpaquePointer? {
31
+ if let connection { return connection }
32
+ let parent = path.deletingLastPathComponent()
33
+ let manager = FileManager.default
34
+ if create {
35
+ try manager.createDirectory(at: parent, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
36
+ }
37
+ do {
38
+ let root = try manager.attributesOfItem(atPath: parent.path)
39
+ guard root[.type] as? FileAttributeType == .typeDirectory else { throw Self.failure(SQLITE_CANTOPEN) }
40
+ let current = try manager.attributesOfItem(atPath: path.path)
41
+ guard current[.type] as? FileAttributeType == .typeRegular else { throw Self.failure(SQLITE_CANTOPEN) }
42
+ } catch let error as CocoaError where error.code == .fileNoSuchFile || error.code == .fileReadNoSuchFile {
43
+ if !create { return nil }
44
+ }
45
+ // SQLite's NOFOLLOW also rejects ancestors such as Darwin's /var.
46
+ // Resolve only the parent so SQLite still checks the database file itself.
47
+ guard let resolved = parent.path.withCString({ realpath($0, nil) }) else {
48
+ throw Self.failure(SQLITE_CANTOPEN)
49
+ }
50
+ defer { free(resolved) }
51
+ let databasePath = String(cString: resolved) + "/" + path.lastPathComponent
52
+ var handle: OpaquePointer?
53
+ let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_NOFOLLOW | (create ? SQLITE_OPEN_CREATE : 0)
54
+ let status = sqlite3_open_v2(databasePath, &handle, flags, nil)
55
+ guard status == SQLITE_OK, let db = handle else {
56
+ if let handle { sqlite3_close(handle) }
57
+ throw Self.failure(status)
58
+ }
59
+ do {
60
+ try Self.check(sqlite3_busy_timeout(db, 5_000), SQLITE_OK)
61
+ if create {
62
+ try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: databasePath)
63
+ }
64
+ try execute(db, "PRAGMA journal_mode = WAL")
65
+ try execute(db, "PRAGMA synchronous = NORMAL")
66
+ try execute(db, "CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL, version TEXT NOT NULL)")
67
+ } catch {
68
+ sqlite3_close(db)
69
+ throw error
70
+ }
71
+ connection = db
72
+ return db
73
+ }
74
+
75
+ private static func failure(_ code: Int32) -> LegacyCrocheError {
76
+ LegacyCrocheError("storage_error", "SQLite state operation failed (\(code)).")
77
+ }
78
+
79
+ private static func check(_ status: Int32, _ expected: Int32) throws {
80
+ guard status == expected else { throw failure(status) }
81
+ }
82
+
83
+ private func execute(_ db: OpaquePointer, _ query: String) throws {
84
+ try Self.check(sqlite3_exec(db, query, nil, nil, nil), SQLITE_OK)
85
+ }
86
+
87
+ private func statement<T>(_ db: OpaquePointer, _ query: String, _ bindings: [String],
88
+ _ body: (OpaquePointer) throws -> T) throws -> T {
89
+ var handle: OpaquePointer?
90
+ try Self.check(sqlite3_prepare_v2(db, query, -1, &handle, nil), SQLITE_OK)
91
+ guard let statement = handle else { throw Self.failure(SQLITE_ERROR) }
92
+ defer { sqlite3_finalize(statement) }
93
+ for (index, value) in bindings.enumerated() {
94
+ let size = Int32(exactly: value.utf8.count)
95
+ guard let size else { throw Self.failure(SQLITE_TOOBIG) }
96
+ let status = value.utf8CString.withUnsafeBufferPointer { bytes in
97
+ sqlite3_bind_text(statement, Int32(index + 1), bytes.baseAddress, size,
98
+ unsafeBitCast(-1, to: sqlite3_destructor_type.self))
99
+ }
100
+ try Self.check(status, SQLITE_OK)
101
+ }
102
+ return try body(statement)
103
+ }
104
+
105
+ private func execute(_ db: OpaquePointer, _ query: String, _ bindings: [String]) throws {
106
+ try statement(db, query, bindings) { try Self.check(sqlite3_step($0), SQLITE_DONE) }
107
+ }
108
+
109
+ private func text(_ row: OpaquePointer, _ column: Int32) throws -> String {
110
+ guard let pointer = sqlite3_column_text(row, column) else { throw Self.failure(SQLITE_ERROR) }
111
+ let bytes = UnsafeBufferPointer(start: pointer, count: Int(sqlite3_column_bytes(row, column)))
112
+ guard let value = String(bytes: bytes, encoding: .utf8) else { throw Self.failure(SQLITE_CORRUPT) }
113
+ return value
114
+ }
115
+
116
+ private func entry(_ db: OpaquePointer, _ key: String) throws -> VersionedValue {
117
+ try statement(db, "SELECT value, version FROM state WHERE key = ?", [key]) { row in
118
+ let status = sqlite3_step(row)
119
+ if status == SQLITE_DONE { return VersionedValue(value: nil, version: nil) }
120
+ try Self.check(status, SQLITE_ROW)
121
+ return VersionedValue(value: try text(row, 0), version: try text(row, 1))
122
+ }
123
+ }
124
+
125
+ func get(_ key: String) throws -> VersionedValue {
126
+ try validateStateKey(key)
127
+ return try gate.withLock {
128
+ guard let db = try database(create: false) else { return VersionedValue(value: nil, version: nil) }
129
+ return try entry(db, key)
130
+ }
131
+ }
132
+
133
+ func list(_ prefix: String, _ options: StateListOptions) throws -> StatePage {
134
+ let range = try StateRange(prefix: prefix, options: options)
135
+ return try gate.withLock {
136
+ guard let db = try database(create: false) else { return StatePage(entries: []) }
137
+ let rows = try statement(
138
+ db, range.statement(table: "state"), [range.from, range.to, String(range.limit + 1)]
139
+ ) { row in
140
+ var entries: [StateEntry] = []
141
+ while true {
142
+ let status = sqlite3_step(row)
143
+ #if DEBUG
144
+ if status == SQLITE_DONE { lastListSteps = sqlite3_stmt_status(row, SQLITE_STMTSTATUS_VM_STEP, 0) }
145
+ #endif
146
+ if status == SQLITE_DONE { return entries }
147
+ try Self.check(status, SQLITE_ROW)
148
+ entries.append(StateEntry(key: try text(row, 0), value: try text(row, 1)))
149
+ }
150
+ }
151
+ return try range.page(rows)
152
+ }
153
+ }
154
+
155
+ private func version(_ db: OpaquePointer, _ key: String) throws -> String? {
156
+ try statement(db, "SELECT version FROM state WHERE key = ?", [key]) { row in
157
+ let status = sqlite3_step(row)
158
+ if status == SQLITE_DONE { return nil }
159
+ try Self.check(status, SQLITE_ROW)
160
+ return try text(row, 0)
161
+ }
162
+ }
163
+
164
+ private func apply(_ db: OpaquePointer, _ op: StateOp) throws -> String? {
165
+ switch op {
166
+ case .put(let key, let value):
167
+ let version = UUID().uuidString.lowercased()
168
+ try execute(db, "INSERT OR REPLACE INTO state(key, value, version) VALUES (?, ?, ?)", [key, value, version])
169
+ return version
170
+ case .delete(let key):
171
+ try execute(db, "DELETE FROM state WHERE key = ?", [key])
172
+ return nil
173
+ }
174
+ }
175
+
176
+ private func transaction<T>(_ db: OpaquePointer, _ body: () throws -> T) throws -> T {
177
+ try execute(db, "BEGIN IMMEDIATE")
178
+ do {
179
+ let result = try body()
180
+ try execute(db, "COMMIT")
181
+ return result
182
+ } catch {
183
+ if sqlite3_get_autocommit(db) == 0 {
184
+ do {
185
+ try execute(db, "ROLLBACK")
186
+ } catch {
187
+ // Do not let the next operation use a connection with an open batch.
188
+ sqlite3_close_v2(db)
189
+ connection = nil
190
+ }
191
+ }
192
+ throw error
193
+ }
194
+ }
195
+
196
+ func commit(_ ops: [StateOp], _ condition: StateCondition) throws -> StateCommitResult {
197
+ try validateStateBatch(ops, condition)
198
+ return try gate.withLock {
199
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
200
+ return try transaction(db) {
201
+ var version = try version(db, condition.key)
202
+ guard version == condition.version else { return .conflict }
203
+ for op in ops {
204
+ let written = try apply(db, op)
205
+ if op.key == condition.key { version = written }
206
+ }
207
+ try beforeCommit?()
208
+ return .committed(version: version)
209
+ }
210
+ }
211
+ }
212
+
213
+ func write(_ key: String, _ value: String) throws {
214
+ try validateStateKey(key)
215
+ try gate.withLock {
216
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
217
+ _ = try apply(db, .put(key: key, value: value))
218
+ }
219
+ }
220
+
221
+ func remove(_ key: String) throws {
222
+ try validateStateKey(key)
223
+ try gate.withLock {
224
+ if let db = try database(create: false) { _ = try apply(db, .delete(key: key)) }
225
+ }
226
+ }
227
+
228
+ func writeIf(_ key: String, _ value: String?, _ expect: String?) throws -> WriteOutcome {
229
+ try validateStateKey(key)
230
+ _ = try storageVersion(expect)
231
+ return try gate.withLock {
232
+ guard let db = try database(create: true) else { throw Self.failure(SQLITE_CANTOPEN) }
233
+ return try transaction(db) {
234
+ let current = try version(db, key)
235
+ guard current == expect else { return .conflict(version: current) }
236
+ let operation: StateOp = value.map { .put(key: key, value: $0) } ?? .delete(key: key)
237
+ let version = try apply(db, operation)
238
+ try beforeCommit?()
239
+ return .written(version: version)
240
+ }
241
+ }
242
+ }
243
+
244
+ func purge(_ prefix: String) throws {
245
+ guard prefix.count > 1, prefix.hasSuffix("/") else { throw CocoaError(.fileWriteInvalidFileName) }
246
+ let range = try StateRange(prefix: prefix, options: StateListOptions())
247
+ try gate.withLock {
248
+ if let db = try database(create: false) {
249
+ try execute(db, "DELETE FROM state WHERE key >= ? AND key < ?", [range.lower, range.upper])
250
+ }
251
+ }
252
+ }
253
+ }