@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,68 @@
1
+ function record(value) {
2
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
3
+ throw new TypeError('Invalid storage callback result');
4
+ }
5
+ return value;
6
+ }
7
+ function nullableString(value) {
8
+ if (value !== null && typeof value !== 'string')
9
+ throw new TypeError('Expected a string or null');
10
+ return value;
11
+ }
12
+ function version(value) {
13
+ const token = nullableString(value);
14
+ if (token !== null && (token.length === 0 || token.length > 128 || /[^\x21-\x7e]/.test(token)))
15
+ throw new TypeError('Invalid storage version');
16
+ return token;
17
+ }
18
+ export function decodeVersionedValue(result) {
19
+ const fields = record(result);
20
+ const value = nullableString(fields.value);
21
+ const token = version(fields.version);
22
+ if ((value === null) !== (token === null))
23
+ throw new TypeError('Unpaired storage value and version');
24
+ return { value, version: token };
25
+ }
26
+ // The ASCII grammar makes JS length equal to the portable UTF-8 byte count.
27
+ // Keep ordinary legacy storage's separate 200-byte bound unchanged.
28
+ function versionedKey(key) {
29
+ if (typeof key !== 'string' || key.length === 0 || /[^A-Za-z0-9._/-]/.test(key)) {
30
+ throw new TypeError('Invalid versioned storage key');
31
+ }
32
+ if (key.length > 196)
33
+ throw new TypeError('Versioned storage key exceeds sibling budget');
34
+ const components = key.split('/');
35
+ if (components.includes('secret-index'))
36
+ throw new TypeError('Secret inventory cannot be versioned');
37
+ if (key.replace(/\/+$/, '').split('/').at(-1) === '.p1')
38
+ throw new TypeError('Reserved storage sibling');
39
+ return key;
40
+ }
41
+ /** Capture the logical read key before a callback is invoked. */
42
+ export function captureReadVersioned(key) {
43
+ const logicalKey = versionedKey(key);
44
+ return Object.freeze({ key: logicalKey, decode: decodeVersionedValue });
45
+ }
46
+ /** Validate before handoff and close over THIS request's primitive values. */
47
+ export function captureWriteIf(key, value, expect) {
48
+ const logicalKey = versionedKey(key);
49
+ const requestedValue = nullableString(value);
50
+ const expectedVersion = version(expect);
51
+ return Object.freeze({
52
+ key: logicalKey, value: requestedValue, expect: expectedVersion,
53
+ decode(result) {
54
+ const fields = record(result);
55
+ const type = fields.type;
56
+ const token = version(fields.version);
57
+ if (type !== 'written' && type !== 'conflict')
58
+ throw new TypeError('Invalid storage outcome');
59
+ if (type === 'written') {
60
+ if ((requestedValue === null) !== (token === null))
61
+ throw new TypeError('Written version does not match request');
62
+ if (token === 'legacy')
63
+ throw new TypeError('Written must return a new storage version');
64
+ }
65
+ return { type, version: token };
66
+ },
67
+ });
68
+ }
@@ -0,0 +1,3 @@
1
+ import type { CoreStoragePal } from '../core/port.js';
2
+ import type { StateStore } from './state-store.js';
3
+ export declare function transactionalStorage(store: StateStore, secrets?: CoreStoragePal['secrets']): CoreStoragePal;
@@ -0,0 +1,124 @@
1
+ import { CrocheError, HostError, thrownFacts } from '../errors.js';
2
+ import { builtinStateLocks } from './state-store-lock.js';
3
+ const owners = new WeakMap();
4
+ const MAX_PURGE_WALKS = 8;
5
+ async function* pages(store, prefix) {
6
+ const cursors = new Set();
7
+ let cursor;
8
+ let previous;
9
+ do {
10
+ const page = await store.list(prefix, cursor === undefined ? undefined : { cursor });
11
+ for (const entry of page.entries) {
12
+ // Storage keys use the portable ASCII grammar, so comparison is byte order.
13
+ if (!entry.key.startsWith(prefix) || (previous !== undefined && entry.key <= previous)) {
14
+ throw Error('Invalid StateStore list key order or prefix');
15
+ }
16
+ previous = entry.key;
17
+ }
18
+ yield page.entries;
19
+ cursor = page.nextCursor;
20
+ if (cursor !== undefined) {
21
+ if (cursors.has(cursor))
22
+ throw Error('StateStore cursor did not advance');
23
+ cursors.add(cursor);
24
+ }
25
+ } while (cursor !== undefined);
26
+ }
27
+ function operation(key, value) {
28
+ return value === null ? { type: 'delete', key } : { type: 'put', key, value };
29
+ }
30
+ export function transactionalStorage(store, secrets) {
31
+ if (['get', 'list', 'commit'].some(name => typeof store[name] !== 'function')) {
32
+ throw new CrocheError('invalid_configuration', 'StateStore requires get, list, and commit.', 'setup');
33
+ }
34
+ let locks = owners.get(store);
35
+ if (!locks) {
36
+ locks = new Set();
37
+ owners.set(store, locks);
38
+ }
39
+ const held = locks;
40
+ const custody = builtinStateLocks.get(store);
41
+ async function mutate(key, value) {
42
+ let current;
43
+ try {
44
+ current = await store.get(key);
45
+ }
46
+ catch (cause) {
47
+ // This private bridge call can fail in either StateStore operation.
48
+ const detail = thrownFacts(cause).message ?? 'StateStore version read failed.';
49
+ throw new HostError('state_get_failed', detail, { cause });
50
+ }
51
+ const version = current?.version ?? null;
52
+ const result = await store.commit([operation(key, value)], { key, version });
53
+ if (result.type === 'conflict')
54
+ throw Error('StateStore key changed before commit');
55
+ }
56
+ return {
57
+ commit: (ops, condition) => store.commit(ops, condition),
58
+ // The Core storage seam is the app interface: the page and its cursor pass through as they are.
59
+ listState: (prefix, options) => store.list(prefix, options),
60
+ async read(key) { return (await store.get(key))?.value ?? null; },
61
+ async readVersioned(key) { return (await store.get(key)) ?? { value: null, version: null }; },
62
+ async writeIf(key, value, version) {
63
+ const result = await store.commit([operation(key, value)], { key, version });
64
+ return result.type === 'committed'
65
+ ? { type: 'written', version: result.version }
66
+ : { type: 'conflict', version: null };
67
+ },
68
+ write: mutate,
69
+ remove: key => mutate(key, null),
70
+ async list(prefix) {
71
+ const keys = [];
72
+ for await (const entries of pages(store, prefix))
73
+ keys.push(...entries.map(entry => entry.key));
74
+ return keys;
75
+ },
76
+ async purgeInstance(prefix, credentialKey) {
77
+ if (prefix.length > 200 || !/^(?:[A-Za-z0-9._-]+\/)+$/.test(prefix)) {
78
+ throw new HostError('invalid_input', 'Invalid StateStore purge prefix.');
79
+ }
80
+ await custody?.verify?.(prefix);
81
+ if (credentialKey !== undefined) {
82
+ if (secrets)
83
+ await secrets.remove(credentialKey);
84
+ else
85
+ await mutate(credentialKey, null);
86
+ }
87
+ for (let walk = 0; walk < MAX_PURGE_WALKS; walk++) {
88
+ let found = false;
89
+ for await (const entries of pages(store, prefix)) {
90
+ if (!entries.length)
91
+ continue;
92
+ found = true;
93
+ const key = entries[0].key;
94
+ const version = (await store.get(key))?.version ?? null;
95
+ const result = await store.commit(entries.map(({ key }) => ({ type: 'delete', key })), { key, version });
96
+ if (result.type === 'conflict')
97
+ throw Error('StateStore prefix changed before deletion');
98
+ }
99
+ if (!found)
100
+ return;
101
+ }
102
+ throw Error('StateStore prefix did not empty');
103
+ },
104
+ async lock(name) {
105
+ if (custody)
106
+ return custody.lock(name);
107
+ if (held.has(name))
108
+ return 'held';
109
+ held.add(name);
110
+ return 'acquired';
111
+ },
112
+ async unlock(name) {
113
+ if (custody)
114
+ await custody.unlock(name);
115
+ else
116
+ held.delete(name);
117
+ },
118
+ secrets: secrets ?? {
119
+ async read() { throw Error('No platform credential store'); },
120
+ async write() { throw Error('No platform credential store'); },
121
+ async remove() { throw Error('No platform credential store'); },
122
+ },
123
+ };
124
+ }
@@ -0,0 +1 @@
1
+ export * from './index.native.js';
@@ -0,0 +1,4 @@
1
+ export * from './index.native.js';
2
+ import { usePlatform } from './pal/platform.js';
3
+ import { nativePlatform } from './native-adapter.js';
4
+ usePlatform(nativePlatform);
@@ -0,0 +1,33 @@
1
+ import type { Json } from './app-api.js';
2
+ import type { ErrorCategory } from './errors.js';
3
+ import type { Attachment } from './generated/app-stream.js';
4
+ /** One envelope for every opened Core plugin; output is the plugin's JSON. */
5
+ export type RunToolResult = {
6
+ id: string;
7
+ status: 'ok';
8
+ output: Json;
9
+ attachments: Attachment[];
10
+ cost: number | null;
11
+ costStatus: 'reported' | 'unknown' | 'none' | (string & {});
12
+ } | {
13
+ id: string;
14
+ status: 'failed';
15
+ code: string;
16
+ category: ErrorCategory;
17
+ message: string;
18
+ cost: number | null;
19
+ costStatus: 'reported' | 'unknown' | 'none' | (string & {});
20
+ } | {
21
+ id: string;
22
+ status: 'lost';
23
+ code: 'outcome_unknown';
24
+ category: 'closed';
25
+ message: string;
26
+ } | {
27
+ id: string;
28
+ status: 'unknown';
29
+ originalStatus: string;
30
+ fields: Json;
31
+ };
32
+ /** Readers preserve a future status and its complete payload, as AgentEvent does. */
33
+ export declare function runToolResult(json: string): RunToolResult;
@@ -0,0 +1,7 @@
1
+ /** Readers preserve a future status and its complete payload, as AgentEvent does. */
2
+ export function runToolResult(json) {
3
+ const value = JSON.parse(json);
4
+ return ['ok', 'failed', 'lost'].includes(value.status)
5
+ ? value
6
+ : { id: value.id, status: 'unknown', originalStatus: value.status, fields: value };
7
+ }
@@ -0,0 +1,35 @@
1
+ import type { Json, ToolManifest, ToolContent, ToolDefinition, ToolExecute, ToolResult } from './app-api.js';
2
+ import type { CoreExecute, CoreToolDefinition } from './core/port.js';
3
+ /**
4
+ * Give the agent a useful explanation when an app action cannot proceed.
5
+ *
6
+ * Its message reaches the model verbatim.
7
+ */
8
+ export declare class ToolError extends Error {
9
+ /** Create an error whose message describes why the app action could not proceed. */
10
+ constructor(message?: string, options?: ErrorOptions);
11
+ }
12
+ /**
13
+ * Return content the agent can use, such as a caption and a photo from the app.
14
+ *
15
+ * The ONLY way to make a ToolResult: any other object a tool returns is Json, even one with `json` or `content`.
16
+ */
17
+ export declare function toolResult(value: string | Json | ToolContent[]): ToolResult;
18
+ /** Core's handle for a definition made by defineTool/tools, or undefined for anything else. */
19
+ export declare function coreDefinition(value: unknown): CoreToolDefinition | undefined;
20
+ /**
21
+ * Let the agent use app-owned features such as looking up an order.
22
+ *
23
+ * `manifest` is typed as ToolManifest (a JSON module import or a const with mixed commands fits it); the SDK still
24
+ * serializes it unchanged (undefined throws, json.ts) and Core validates it.
25
+ */
26
+ export declare function defineTool(manifest: ToolManifest, execute: ToolExecute): ToolDefinition;
27
+ /** Croche tools: they run in Core through Egress and are billed. */
28
+ export declare const tools: {
29
+ /** Definition for the built-in web search tool. */
30
+ readonly webSearch: ToolDefinition;
31
+ /** Definition for the built-in image tool. */
32
+ readonly image: ToolDefinition;
33
+ };
34
+ /** The callback Core holds for one definition. */
35
+ export declare function bridge(execute: ToolExecute): CoreExecute;
@@ -0,0 +1,94 @@
1
+ import { signalFor } from './cancel.js';
2
+ import { coreModule } from './core/wasm.js';
3
+ import { encodable, jsonText } from './json.js';
4
+ import { thrownError, coreFailure } from './errors.js';
5
+ /**
6
+ * Give the agent a useful explanation when an app action cannot proceed.
7
+ *
8
+ * Its message reaches the model verbatim.
9
+ */
10
+ export class ToolError extends Error {
11
+ /** Create an error whose message describes why the app action could not proceed. */
12
+ constructor(message, options) {
13
+ super(message, options);
14
+ this.name = 'ToolError';
15
+ }
16
+ }
17
+ const BRAND = Symbol('croche.toolResult');
18
+ /**
19
+ * Return content the agent can use, such as a caption and a photo from the app.
20
+ *
21
+ * The ONLY way to make a ToolResult: any other object a tool returns is Json, even one with `json` or `content`.
22
+ */
23
+ export function toolResult(value) {
24
+ return Object.freeze({ [BRAND]: value });
25
+ }
26
+ function branded(value) {
27
+ return typeof value === 'object' && value !== null && Object.hasOwn(value, BRAND);
28
+ }
29
+ // Definitions made here, mapped to Core's handle. A WeakMap, not a property: the app's object stays `{name}`.
30
+ const handles = new WeakMap();
31
+ function wrap(handle) {
32
+ const definition = Object.freeze({ get name() { return handle.name; } });
33
+ handles.set(definition, handle);
34
+ return definition;
35
+ }
36
+ /** Core's handle for a definition made by defineTool/tools, or undefined for anything else. */
37
+ export function coreDefinition(value) {
38
+ return typeof value === 'object' && value !== null ? handles.get(value) : undefined;
39
+ }
40
+ /**
41
+ * Let the agent use app-owned features such as looking up an order.
42
+ *
43
+ * `manifest` is typed as ToolManifest (a JSON module import or a const with mixed commands fits it); the SDK still
44
+ * serializes it unchanged (undefined throws, json.ts) and Core validates it.
45
+ */
46
+ export function defineTool(manifest, execute) {
47
+ const core = coreModule();
48
+ return wrap(core.defineTool(jsonText(manifest), bridge(execute)));
49
+ }
50
+ let webSearch;
51
+ let image;
52
+ /** Croche tools: they run in Core through Egress and are billed. */
53
+ export const tools = Object.freeze({
54
+ get webSearch() { return webSearch ??= wrap(coreModule().webSearch()); },
55
+ get image() { return image ??= wrap(coreModule().image()); },
56
+ });
57
+ // A ToolCompletion as JSON text. The app's value is spliced in as the strict serializer wrote it, never re-encoded.
58
+ const fact = (completion) => JSON.stringify(completion);
59
+ function completion(value) {
60
+ // A value with no JSON form is the invalid_result fact; Core gives it its code (invalid_tool_result).
61
+ if (value === undefined)
62
+ return fact({ type: 'empty' });
63
+ const brand = branded(value);
64
+ const json = encodable(brand ? value[BRAND] : value);
65
+ if (json === undefined)
66
+ return fact({ type: 'invalid_result' });
67
+ return brand ? `{"type":"result","content":${json}}` : `{"type":"json","value":${json}}`;
68
+ }
69
+ /** The callback Core holds for one definition. */
70
+ export function bridge(execute) {
71
+ return async (callJson, contextJson, cancel, attachments) => {
72
+ const signal = signalFor(cancel);
73
+ const ctx = { ...JSON.parse(contextJson), signal,
74
+ async attachment(id) {
75
+ try {
76
+ return JSON.parse(await attachments.attachment(id));
77
+ }
78
+ catch (error) {
79
+ throw coreFailure(error);
80
+ }
81
+ },
82
+ };
83
+ let outcome;
84
+ try {
85
+ outcome = completion(await execute(JSON.parse(callJson), ctx));
86
+ }
87
+ catch (error) {
88
+ outcome = fact(error instanceof ToolError
89
+ ? { type: 'tool_error', message: error.message }
90
+ : { type: 'handler_error', error: thrownError(error) });
91
+ }
92
+ return cancel.isCancelled() ? fact({ type: 'cancelled' }) : outcome;
93
+ };
94
+ }
@@ -0,0 +1,14 @@
1
+ import Foundation
2
+
3
+ /// Owned bytes travel BESIDE input JSON. No image is serialized/base64-encoded,
4
+ /// sniffed or resized by the RN bridge. Core owns every acquisition decision.
5
+ struct RNCoreAgentTransport: Sendable {
6
+ let core: any CoreAgentProtocol
7
+
8
+ func send(inputJson: String, images: [CoreAttachmentInput], optionsJson: String?, cancel: CancelToken?) throws -> String {
9
+ try core.send(inputJson: inputJson, images: images, optionsJson: optionsJson, cancel: cancel)
10
+ }
11
+ func request(inputJson: String, images: [CoreAttachmentInput], optionsJson: String?, cancel: CancelToken?) throws -> String {
12
+ try core.request(inputJson: inputJson, images: images, optionsJson: optionsJson, cancel: cancel)
13
+ }
14
+ }
@@ -0,0 +1,58 @@
1
+ import Foundation
2
+
3
+ /// Owns only the native references needed to cross the RN event emitter. Core
4
+ /// decides entry, ordering and duplicate completion; this keeps no event queue.
5
+ final class RNCoreDeliveries: @unchecked Sendable {
6
+ private let lock = NSLock()
7
+ private var entries: [String: any CoreDeliveryProtocol] = [:]
8
+
9
+ func hold(_ delivery: any CoreDeliveryProtocol) -> String {
10
+ let handle = UUID().uuidString
11
+ lock.withLock { entries[handle] = delivery }
12
+ return handle
13
+ }
14
+ /// Called synchronously by the JS native binding ON the invocation stack.
15
+ /// nil means an unknown transport handle, not an SDK decision about entry.
16
+ func tryEnter(_ handle: String) -> Bool? {
17
+ guard let delivery = lock.withLock({ entries[handle] }) else { return nil }
18
+ let entered = delivery.tryEnter()
19
+ if !entered { lock.withLock { _ = entries.removeValue(forKey: handle) } }
20
+ return entered
21
+ }
22
+ @discardableResult func complete(_ handle: String, _ outcomeJson: String) -> Bool {
23
+ guard let delivery = lock.withLock({ entries.removeValue(forKey: handle) }) else { return false }
24
+ delivery.complete(outcomeJson: outcomeJson)
25
+ return true
26
+ }
27
+ }
28
+
29
+ /// The emitter only posts to JavaScript. It MUST NOT enter the delivery here:
30
+ /// the JS shared event sink calls tryEnter synchronously just before app code.
31
+ final class RNCoreEventSink: CoreEventSink, @unchecked Sendable {
32
+ typealias Emit = @Sendable (String) throws -> Void
33
+ private let sink: String
34
+ private let deliveries: RNCoreDeliveries
35
+ private let emit: Emit
36
+ init(sink: String, deliveries: RNCoreDeliveries, emit: @escaping Emit) {
37
+ self.sink = sink; self.deliveries = deliveries; self.emit = emit
38
+ }
39
+ deinit {
40
+ if let json = try? rnJSON(["type":"retired", "sinks":[sink], "hosts":[], "storages":[], "executors":[], "tokens":[]]) { try? emit(json) }
41
+ }
42
+ func deliver(deliveryId: String, eventJson: String, delivery: CoreDelivery) throws {
43
+ try post(deliveryId: deliveryId, eventJson: eventJson, delivery: delivery)
44
+ }
45
+ // The generated protocol lets the same transport run against a no-FFI double.
46
+ func post(deliveryId: String, eventJson: String, delivery: any CoreDeliveryProtocol) throws {
47
+ let handle = deliveries.hold(delivery)
48
+ do {
49
+ let packet: [String: String] = ["type": "event", "sink": sink, "id": deliveryId,
50
+ "eventJson": eventJson, "delivery": handle]
51
+ let data = try JSONSerialization.data(withJSONObject: packet, options: [.sortedKeys])
52
+ try emit(String(decoding: data, as: UTF8.self))
53
+ } catch {
54
+ deliveries.complete(handle, #"{"outcome":"unavailable"}"#)
55
+ throw error
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,98 @@
1
+ import Foundation
2
+
3
+ // RN's default primitives are the same iOS PAL as the public Swift SDK.
4
+ // No key rewriting, URL policy, retry loop or storage error code map.
5
+ final class RNDefaultPal: @unchecked Sendable {
6
+ private let guardLock = NSLock()
7
+ private var cached: PlatformPal?
8
+ private var httpTokens: [String: CancelToken] = [:]
9
+ private var cancelledBeforeStart: Set<String> = []
10
+ var emit: (@Sendable (String) -> Void)?
11
+ func host() throws -> PlatformPal {
12
+ guardLock.lock(); defer { guardLock.unlock() }
13
+ if let cached { return cached }
14
+ let host = try PlatformPal.standard(); host.streamPlatformFact = .reactNative
15
+ cached = host; return host
16
+ }
17
+ func call(_ method: String, _ args: [Any]) throws -> Any {
18
+ let host = try host()
19
+ let storage = PlatformStorageAdapter(host)
20
+ switch method {
21
+ case "listState", "commit":
22
+ return try rnStateStorageCall(storage, method, args)
23
+ case "readVersioned":
24
+ let pair = try storage.readVersioned(key: rnString(args, 0))
25
+ return ["value": pair.value as Any? ?? NSNull(), "version": pair.version as Any? ?? NSNull()]
26
+ case "writeIf":
27
+ guard args.count == 3 else { throw RNWireError.badPacket }
28
+ let outcome = try storage.writeIf(key: rnString(args, 0), value: rnStorageString(args[1]), expect: rnStorageString(args[2]))
29
+ switch outcome {
30
+ case let .written(version): return ["type": "written", "version": version as Any? ?? NSNull()]
31
+ case let .conflict(version): return ["type": "conflict", "version": version as Any? ?? NSNull()]
32
+ }
33
+ case "read": return try storage.read(key: rnString(args, 0)) as Any? ?? NSNull()
34
+ case "write": try storage.write(key: rnString(args, 0), value: rnString(args, 1)); return NSNull()
35
+ case "remove": try storage.remove(key: rnString(args, 0)); return NSNull()
36
+ case "list": return try storage.list(prefix: rnString(args, 0))
37
+ case "lock": return try storage.lock(name: rnString(args, 0)) == .acquired ? "acquired" : "held"
38
+ case "unlock": try storage.unlock(name: rnString(args, 0)); return NSNull()
39
+ case "readSecret": return try storage.readSecret(key: rnString(args, 0)) as Any? ?? NSNull()
40
+ case "writeSecret": try storage.writeSecret(key: rnString(args, 0), value: rnString(args, 1)); return NSNull()
41
+ case "removeSecret": try storage.removeSecret(key: rnString(args, 0)); return NSNull()
42
+ case "purgeInstance":
43
+ let secretKey = args.count > 1 ? try rnStorageString(args[1]) : nil
44
+ try storage.purgeInstance(prefix: rnString(args, 0), secretKey: secretKey)
45
+ return NSNull()
46
+ case "platformFacts":
47
+ let facts = host.platformFacts(); var json: [String: Any] = [:]
48
+ switch facts.targetKind {
49
+ case .iosDevice: json["targetKind"] = "ios-device"
50
+ case .iosSimulator: json["targetKind"] = "ios-simulator"
51
+ case .android: json["targetKind"] = "android"
52
+ case .other: json["targetKind"] = "other"
53
+ }
54
+ if let value = facts.debuggable { json["debuggable"] = value }
55
+ if let value = facts.locale { json["locale"] = value }
56
+ if let value = facts.attestationPlatform { json["attestationPlatform"] = value }
57
+ return json
58
+ case "readAsset": return try host.readAsset(path: rnString(args, 0)).map { Array($0) } as Any? ?? NSNull()
59
+ case "resolve": return try host.resolve(host: rnString(args, 0), cancel: CancelToken())
60
+ case "readImage":
61
+ let max = (args[1] as! NSNumber).uint64Value
62
+ return Array(try host.readImage(request: PalImageReadRequest(source: .local(uri: rnString(args, 0)), maxBytes: max), cancel: CancelToken()))
63
+ case "cancelHttp":
64
+ let id = try rnString(args, 0)
65
+ guardLock.lock(); let token = httpTokens[id]; if token == nil { cancelledBeforeStart.insert(id) }; guardLock.unlock()
66
+ token?.cancel(); return NSNull()
67
+ case "http":
68
+ let id = try rnString(args, 0), p = args[1] as! [String: Any]
69
+ let token = CancelToken()
70
+ guardLock.lock(); httpTokens[id] = token; let cancelled = cancelledBeforeStart.remove(id) != nil; guardLock.unlock()
71
+ if cancelled { token.cancel() }
72
+ defer { guardLock.lock(); httpTokens.removeValue(forKey: id); guardLock.unlock() }
73
+ let headers = (p["headers"] as! [[String]]).map { PalHeader(name: $0[0], value: $0[1]) }
74
+ let request = PalHttpRequest(connectTo: p["connectTo"] as? String, url: p["url"] as! String, method: p["method"] as! String,
75
+ headers: headers, body: p["body"] as? String, timeoutMs: (p["timeoutMs"] as! NSNumber).uint64Value,
76
+ responseMode: p["responseMode"] as! String, maxResponseBytes: (p["maxResponseBytes"] as! NSNumber).uint64Value)
77
+ let sink = RNHttpSink(id, self)
78
+ try effect {
79
+ if try PlatformHTTP.direct(request, sink: sink, cancel: token) { return }
80
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: token) { signal -> Bool in
81
+ try await host.session.stream(request, into: sink, cancellation: signal)
82
+ return true
83
+ }
84
+ }
85
+ return NSNull()
86
+ default: throw RNWireError.badPacket
87
+ }
88
+ }
89
+ fileprivate func post(_ packet: [String: Any]) {
90
+ if let json = try? rnJSON(packet) { emit?(json) }
91
+ }
92
+ }
93
+ private final class RNHttpSink: HttpSinkProtocol, @unchecked Sendable {
94
+ let id: String; let pal: RNDefaultPal
95
+ init(_ id: String, _ pal: RNDefaultPal) { self.id = id; self.pal = pal }
96
+ func head(status: UInt16, headers: [PalHeader]) { pal.post(["id":id, "type":"head", "status":status, "headers":headers.map { [$0.name, $0.value] }]) }
97
+ func chunk(bytes: Data) -> Bool { pal.post(["id":id, "type":"chunk", "bytes":Array(bytes)]); return true }
98
+ }
@@ -0,0 +1,44 @@
1
+ import Foundation
2
+
3
+ /// Native capabilities travel separately from app JSON. The factory selects the
4
+ /// app storage OR platform default first; this carrier can never hold nil.
5
+ struct RNCorePlatform: @unchecked Sendable {
6
+ let host: any HostPal
7
+ let storage: any CoreStoragePal
8
+ let platformStorage: any CoreStoragePal
9
+
10
+ init(host: PlatformPal, storage: any CoreStoragePal, image: RNImageCallback? = nil, blobs: RNBlobCallback? = nil) {
11
+ host.streamPlatformFact = .reactNative
12
+ self.host = RNProjectPal(host, image: image, blobs: blobs); self.storage = storage
13
+ self.platformStorage = PlatformStorageAdapter(host)
14
+ }
15
+
16
+ static func standard(storage: any CoreStoragePal, image: RNImageCallback? = nil, blobs: RNBlobCallback? = nil) throws -> RNCorePlatform {
17
+ RNCorePlatform(host: try PlatformPal.standard(), storage: storage, image: image, blobs: blobs)
18
+ }
19
+
20
+ /// The bridge's own binding facts: sdk "react-native" (BindingFacts, from the SDK sources it builds).
21
+ static let bindingFacts = BindingFacts.json(sdk: "react-native")
22
+ func open(_ json: String, registrations: [CoreToolRegistration], recoveryJson: String? = nil,
23
+ invoke: (String, [CoreToolRegistration], (any CoreStoragePal)?, any HostPal, String, String?) throws -> CoreCroche = CoreCroche.open) throws -> CoreCroche {
24
+ try invoke(json, registrations, storage, host, Self.bindingFacts, recoveryJson)
25
+ }
26
+ func registerBackground(_ json: String, sink: (any CoreEventSink)?, platformStorage: (any CoreStoragePal)?,
27
+ invoke: (String, (any CoreEventSink)?, (any CoreStoragePal)?, (any CoreStoragePal)?, any HostPal, String) throws -> Void = coreRegisterBackground) throws {
28
+ try invoke(json, sink, storage, platformStorage, host, Self.bindingFacts)
29
+ }
30
+ }
31
+
32
+ /// A native Core error envelope: detail is Core's message. No regex, fallback
33
+ /// code, category inference, or SDK policy is applied to a CoreApiError.
34
+ func rnCoreErrorEnvelope(_ error: CoreApiError) throws -> String {
35
+ let fields: [String: Any]
36
+ switch error {
37
+ case let .Failure(code, detail, category, path, retryAfter):
38
+ var value: [String: Any] = ["code": code, "message": detail, "category": category]
39
+ if let path { value["path"] = path }
40
+ if let retryAfter { value["retryAfter"] = retryAfter }
41
+ fields = value
42
+ }
43
+ return String(decoding: try JSONSerialization.data(withJSONObject: ["error": fields], options: [.sortedKeys]), as: UTF8.self)
44
+ }