@h1r-ai/croche-react-native 0.5.5 → 0.6.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 (196) hide show
  1. package/README.md +69 -458
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/android/build.gradle +6 -1
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +125 -0
  5. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +81 -0
  6. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +83 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +45 -824
  8. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +51 -0
  9. package/android/src/main/java/dev/croche/reactnative/RNHostPal.kt +9 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +42 -41
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +71 -0
  12. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +29 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +19 -32
  14. package/android/src/test/java/dev/croche/reactnative/ProjectHandlerStagesTest.kt +32 -0
  15. package/android/src/test/java/dev/croche/reactnative/ProjectRecoveryTest.kt +12 -0
  16. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +11 -15
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidEventSink.kt +27 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +6 -6
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundRegistration.kt +16 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +51 -0
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +162 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageInput.kt +15 -0
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapOrientation.kt +40 -0
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapPalCodec.kt +66 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +8 -8
  26. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidAssetPal.kt +30 -0
  27. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreFactory.kt +35 -0
  28. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +121 -0
  29. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidMainDispatcher.kt +17 -0
  30. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +17 -0
  31. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidS2Pal.kt +14 -0
  32. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +73 -0
  33. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +5 -2
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +29 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +45 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +16 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +60 -105
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +47 -107
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +41 -40
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +67 -0
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +20 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +18 -20
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +322 -0
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +71 -34
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ImagePal.kt +183 -0
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +9 -7
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +47 -19
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +5 -5
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +1 -1
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +9 -9
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +108 -37
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +44 -0
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ReaderValues.kt +73 -0
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +40 -0
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +23 -21
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +8 -8
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +18 -0
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +50 -25
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +22 -22
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8285 -2159
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppEventSink.kt +34 -0
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +25 -0
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundOsRegistration.kt +35 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/BackgroundSink.kt +37 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreDefinitionCalls.kt +35 -0
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +31 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +41 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +35 -0
  70. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +128 -0
  71. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +72 -0
  72. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +34 -0
  73. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/LifecycleBinding.kt +18 -0
  74. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +45 -0
  75. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PalCallbacks.kt +27 -0
  76. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PlainToolJson.kt +56 -0
  77. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +34 -0
  78. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ScopeJson.kt +29 -0
  79. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ToolCompletionEncoding.kt +29 -0
  80. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +79 -0
  81. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/DirectHttpPal.kt +223 -0
  82. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  83. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  84. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  85. package/dist/package.json +1 -0
  86. package/dist/react-native/src/NativeCrocheRuntime.d.ts +16 -0
  87. package/dist/react-native/src/NativeCrocheRuntime.js +2 -0
  88. package/dist/react-native/src/core-native.d.ts +3 -0
  89. package/dist/react-native/src/core-native.js +193 -0
  90. package/dist/react-native/src/core-wire.d.ts +38 -0
  91. package/dist/react-native/src/core-wire.js +1 -0
  92. package/dist/react-native/src/native-module.d.ts +8 -0
  93. package/dist/react-native/src/native-module.js +53 -0
  94. package/dist/rn-shared-build.json +16 -0
  95. package/dist/runtime/src/agent.d.ts +43 -0
  96. package/dist/runtime/src/agent.js +75 -0
  97. package/dist/runtime/src/app-api.d.ts +284 -0
  98. package/dist/runtime/src/app-api.js +1 -0
  99. package/dist/runtime/src/cancel.d.ts +9 -0
  100. package/dist/runtime/src/cancel.js +24 -0
  101. package/dist/runtime/src/core/port.d.ts +234 -0
  102. package/dist/runtime/src/core/port.js +1 -0
  103. package/dist/runtime/src/core/wasm.d.ts +1 -0
  104. package/dist/runtime/src/core/wasm.js +2 -0
  105. package/dist/runtime/src/croche.d.ts +42 -0
  106. package/dist/runtime/src/croche.js +111 -0
  107. package/dist/runtime/src/errors.d.ts +26 -0
  108. package/dist/runtime/src/errors.js +49 -0
  109. package/dist/runtime/src/events.d.ts +5 -0
  110. package/dist/runtime/src/events.js +31 -0
  111. package/dist/runtime/src/generated/app-stream.d.ts +174 -0
  112. package/dist/runtime/src/generated/app-stream.js +124 -0
  113. package/dist/runtime/src/index.native.d.ts +21 -0
  114. package/dist/runtime/src/index.native.js +8 -0
  115. package/dist/runtime/src/json.d.ts +13 -0
  116. package/dist/runtime/src/json.js +120 -0
  117. package/dist/runtime/src/native-adapter.d.ts +3 -0
  118. package/dist/runtime/src/native-adapter.js +24 -0
  119. package/dist/runtime/src/pal/codec.d.ts +15 -0
  120. package/dist/runtime/src/pal/codec.js +52 -0
  121. package/dist/runtime/src/pal/host.d.ts +5 -0
  122. package/dist/runtime/src/pal/host.js +35 -0
  123. package/dist/runtime/src/pal/platform.d.ts +16 -0
  124. package/dist/runtime/src/pal/platform.js +7 -0
  125. package/dist/runtime/src/rn-entry.d.ts +1 -0
  126. package/dist/runtime/src/rn-entry.js +4 -0
  127. package/dist/runtime/src/run-tool.d.ts +33 -0
  128. package/dist/runtime/src/run-tool.js +7 -0
  129. package/dist/runtime/src/tools.d.ts +19 -0
  130. package/dist/runtime/src/tools.js +70 -0
  131. package/ios/CoreAgentTransport.swift +14 -0
  132. package/ios/CoreDeliveryTransport.swift +58 -0
  133. package/ios/CoreNativePal.swift +93 -0
  134. package/ios/CorePlatformTransport.swift +44 -0
  135. package/ios/CoreWireDispatch.swift +92 -0
  136. package/ios/CoreWireSupport.swift +111 -0
  137. package/ios/CrocheRuntimeBridge.swift +34 -994
  138. package/ios/ProjectPal.swift +46 -0
  139. package/ios/RNCrocheRuntime.mm +18 -201
  140. package/ios/vendor/CrocheRuntimeSDK/AppBuildFacts.swift +112 -0
  141. package/ios/vendor/CrocheRuntimeSDK/Background.swift +11 -11
  142. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +64 -0
  143. package/ios/vendor/CrocheRuntimeSDK/DirectHTTP.swift +258 -0
  144. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +17 -17
  145. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +85 -43
  146. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +443 -0
  147. package/ios/vendor/CrocheRuntimeSDK/Host.swift +122 -61
  148. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +410 -0
  149. package/ios/vendor/CrocheRuntimeSDK/Images.swift +10 -9
  150. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +4 -4
  151. package/ios/vendor/CrocheRuntimeSDK/Offload.swift +24 -0
  152. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +37 -36
  153. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +35 -35
  154. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +285 -0
  155. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +266 -0
  156. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +195 -0
  157. package/ios/vendor/CrocheRuntimeSDK/Project.swift +209 -95
  158. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +97 -123
  159. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +195 -0
  160. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +33 -0
  161. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +161 -0
  162. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +234 -0
  163. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +28 -0
  164. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +177 -0
  165. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +61 -0
  166. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +95 -0
  167. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +105 -0
  168. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +209 -0
  169. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +52 -52
  170. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +180 -137
  171. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +16 -10
  172. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +131 -116
  173. package/ios/vendor/CrocheRuntimeSDK/Truncate.swift +12 -0
  174. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +7209 -2803
  175. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +1342 -218
  176. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  177. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +1342 -218
  178. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  179. package/package.json +18 -8
  180. package/scripts/README.md +11 -0
  181. package/scripts/build-shared.mjs +46 -0
  182. package/scripts/build.mjs +11 -0
  183. package/scripts/vendor-native.sh +5 -4
  184. package/src/NativeCrocheRuntime.ts +12 -159
  185. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +0 -25
  186. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +0 -17
  187. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +0 -14
  188. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +0 -178
  189. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +0 -79
  190. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +0 -46
  191. package/ios/vendor/CrocheRuntimeSDK/Control.swift +0 -192
  192. package/src/index.ts +0 -664
  193. package/src/project-types.ts +0 -35
  194. package/src/project.ts +0 -434
  195. package/src/protocol.ts +0 -28
  196. package/src/types.ts +0 -9
@@ -0,0 +1,266 @@
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
+ let secrets: any PlatformSecrets
15
+ private let directory: URL
16
+ private let bundle: Bundle
17
+ let session = RuntimeSession()
18
+ let images = NativeImagePal()
19
+ /// Where this host runs (a fact Core reads); a React Native host sets `.reactNative`.
20
+ var streamPlatformFact = HostStreamPlatform.other
21
+
22
+ /// The background wake's timer and OS request (APP-API: registerBackground).
23
+ let schedules: PlatformSchedule
24
+ /// The OS launch handler Core installs once (APP-API: registerBackground).
25
+ let registration: PlatformRegistration
26
+ /// App Attest where this device can attest; nil elsewhere (Core then reports `attestation_unavailable`).
27
+ let attestor: (any PlatformAttestor)?
28
+ /// What the factory declares to Core as the attestation platform: nil = this host cannot attest.
29
+ var attestationPlatform: String? { attestor?.platform }
30
+ /// The device's preferred languages, read at each `platformFacts` (the app may change them).
31
+ let preferredLanguages: @Sendable () -> [String]
32
+
33
+ init(directory: URL, secrets: (any PlatformSecrets)? = nil, bundle: Bundle = .main,
34
+ backgroundRequests: (any BackgroundRequests)? = PlatformPal.osBackgroundRequests(),
35
+ backgroundLaunches: (any BackgroundLaunches)? = PlatformPal.osBackgroundLaunches(),
36
+ attestor: (any PlatformAttestor)? = PlatformPal.osAttestor(),
37
+ preferredLanguages: @escaping @Sendable () -> [String] = { Locale.preferredLanguages }) {
38
+ self.preferredLanguages = preferredLanguages
39
+ let storage = PlatformStorage(directory: directory)
40
+ self.storage = storage; self.directory = directory; self.bundle = bundle
41
+ self.schedules = PlatformSchedule(requests: backgroundRequests); self.attestor = attestor
42
+ self.registration = PlatformRegistration(launches: backgroundLaunches, requests: backgroundRequests)
43
+ #if canImport(Security) && !os(Linux)
44
+ self.secrets = secrets ?? KeychainSecrets()
45
+ #else
46
+ self.secrets = secrets ?? FileSecrets(storage: storage)
47
+ #endif
48
+ }
49
+
50
+ static func osBackgroundRequests() -> (any BackgroundRequests)? {
51
+ #if canImport(BackgroundTasks) && os(iOS)
52
+ return AppRefreshRequests()
53
+ #else
54
+ return nil
55
+ #endif
56
+ }
57
+ static func osBackgroundLaunches() -> (any BackgroundLaunches)? {
58
+ #if canImport(BackgroundTasks) && os(iOS)
59
+ return AppRefreshLaunches()
60
+ #else
61
+ return nil
62
+ #endif
63
+ }
64
+ static func osAttestor() -> (any PlatformAttestor)? {
65
+ #if canImport(DeviceCheck) && os(iOS)
66
+ return AppAttest.supported ? AppAttest() : nil
67
+ #else
68
+ return nil
69
+ #endif
70
+ }
71
+
72
+ /// The platform default store: Application Support/croche, excluded from backup.
73
+ static func standard() throws -> PlatformPal {
74
+ let directory = try NativeProjectFiles.directory(projectDirectory: nil)
75
+ return PlatformPal(directory: directory, secrets: testingSecrets(directory))
76
+ }
77
+ /// Tests keep secrets in files, out of the developer's Keychain (Keel, #861 6537337677).
78
+ static func testingSecrets(_ directory: URL) -> (any PlatformSecrets)? {
79
+ NativeProjectFiles.testing.map { _ in FileSecrets(storage: PlatformStorage(directory: directory)) }
80
+ }
81
+
82
+ private func host<T>(_ body: () throws -> T) throws -> T {
83
+ do { return try body() } catch { throw LegacyCrocheError(error).ffi }
84
+ }
85
+
86
+ // MARK: Storage
87
+ func read(key: String) throws -> String? { try host { try storage.read("state", key) } }
88
+ func write(key: String, value: String) throws { try host { try storage.write("state", key, value) } }
89
+ func remove(key: String) throws { try host { try storage.remove("state", key) } }
90
+ func list(prefix: String) throws -> [String] { try host { try storage.list("state", prefix) } }
91
+ /// Contention is the fact `.held`, never an error (ARCHITECTURE §2a).
92
+ @discardableResult func lock(key: String) throws -> PalLockOutcome { try host { try storage.lock(key) } }
93
+ func unlock(key: String) { storage.unlock(key) }
94
+ func readSecret(key: String) throws -> String? { try host { try secrets.read(key) } }
95
+ func writeSecret(key: String, value: String) throws { try host { try secrets.write(key, value) } }
96
+ func removeSecret(key: String) throws { try host { try secrets.remove(key) } }
97
+ func storeIdentity() -> String { directory.standardizedFileURL.path }
98
+
99
+ // MARK: Assets, resolver, facts
100
+ func readAsset(path: String) throws -> Data? { try effect { try PlatformAssets.read(path, bundle: bundle) } }
101
+ func resolve(host name: String, cancel: CancelToken) throws -> [String] { try effect { try PlatformResolver.resolve(name) } }
102
+ /// `debuggable` and `targetKind` come from `AppBuildFacts`, never the SDK's own build macro
103
+ /// (Keel's S2 ruling, pin 4).
104
+ /// Facts only; Core applies them (Keel 23:55Z/00:27Z). `locale`: the device's first preferred
105
+ /// language, which Core uses for an omitted `language`. `attestationPlatform`: set only when this
106
+ /// host has an attestor. `browserFetch`: never (a native host is not a browser).
107
+ func platformFacts() -> PalPlatformFacts {
108
+ PalPlatformFacts(targetKind: AppBuildFacts.targetKind, debuggable: AppBuildFacts.debuggable, locale: preferredLanguages().first, attestationPlatform: attestationPlatform, browserFetch: nil)
109
+ }
110
+
111
+ // MARK: HTTP
112
+ func http(request: PalHttpRequest, sink: HttpSink, cancel: CancelToken) throws {
113
+ try effect {
114
+ if try PlatformHTTP.direct(request, sink: sink, cancel: cancel) { return }
115
+ let session = session
116
+ _ = try blockOn(milliseconds: Double(request.timeoutMs), cancel: cancel) { signal -> Bool in
117
+ try await session.stream(request, into: sink, cancellation: signal); return true
118
+ }
119
+ }
120
+ }
121
+
122
+ // MARK: Images
123
+ func imageCodecAvailable() -> Bool { images.codecAvailable }
124
+ func readImage(request: PalImageReadRequest, cancel: CancelToken) throws -> Data {
125
+ try effect { try images.read(request, cancel) }
126
+ }
127
+ func prepareImage(source: PalImageBytes, plan: PalImagePreparePlan, cancel: CancelToken) throws -> PalImageBytes {
128
+ try effect { try images.prepare(source, plan, cancel) }
129
+ }
130
+ func releaseImage(capture: String) { images.release(capture) }
131
+ func decodeImage(bytes: Data, options: PalImageDecodeOptions, cancel: CancelToken) throws -> PalDecodedImage {
132
+ try effect { try images.decode(bytes, options, cancel) }
133
+ }
134
+ func renderImage(request: PalImageRenderRequest, cancel: CancelToken) throws -> Data {
135
+ try effect { try images.render(request, cancel) }
136
+ }
137
+ func releaseDecodedImage(handle: String) { images.releaseDecoded(handle) }
138
+ /// A fact about the host, never a batching choice. A React Native host reports .reactNative.
139
+ func streamPlatform() -> HostStreamPlatform { streamPlatformFact }
140
+
141
+ // MARK: Clock, randomness
142
+ func nowMs() -> Double { Date().timeIntervalSince1970 * 1000 }
143
+ func utcOffsetMinutes(atMs: Double) -> Int64 {
144
+ Int64(TimeZone.current.secondsFromGMT(for: Date(timeIntervalSince1970: atMs / 1000)) / 60)
145
+ }
146
+ func random() -> String { UUID().uuidString }
147
+
148
+ // MARK: Attestation, background
149
+ func attest(request: String, timeoutMs: UInt64) throws -> String {
150
+ try PlatformAttestation.run(attestor, request: request, timeoutMs: timeoutMs)
151
+ }
152
+ /// The pending set changed or the store opened: the timer and the OS request follow it.
153
+ func schedule(entries: String) throws { try schedules.apply(entries) }
154
+ /// Core's OS install: the launch handler for `identifier`, then the first request.
155
+ func registerBackground(identifier: String, wake: CoreBackgroundWake) throws {
156
+ try registration.register(identifier, wake)
157
+ }
158
+
159
+ // MARK: Legacy hooks during Core's keyed cutover
160
+ func tool(invocation: String, cancel: CancelToken) throws -> ToolOutput {
161
+ throw FfiError.Failure(code: "tool_not_dispatched", message: "Tools reach Core through their definitions.")
162
+ }
163
+ func wake(atMs: Double?) {}
164
+ func archiveAppendLine(entry: String, line: String) throws { throw Self.noArchive }
165
+ func archiveReadLines(entry: String) throws -> [String] { throw Self.noArchive }
166
+ func archiveReplaceLines(entry: String, lines: [String]) throws { throw Self.noArchive }
167
+ func archiveRemove(entry: String) throws { throw Self.noArchive }
168
+ func archiveEntries(prefix: String) throws -> [ArchiveEntry] { throw Self.noArchive }
169
+ func storageCapability() -> StorageCapability { .keyed }
170
+ private static let noArchive = FfiError.Failure(code: "archive_unavailable", message: "Core keeps the archive in keyed storage.")
171
+ }
172
+
173
+ /// App asset references, resolved unchanged (APP-API: iOS = a main-bundle resource or a
174
+ /// `file://` URL). Missing = nil (Core reports `invalid_wiki`); any other failure = asset_read_failed.
175
+ enum PlatformAssets {
176
+ static func read(_ reference: String, bundle: Bundle) throws -> Data? {
177
+ let file: URL
178
+ if reference.hasPrefix("file://") {
179
+ guard let url = URL(string: reference), url.isFileURL else { throw LegacyCrocheError("asset_read_failed", "The asset URL is malformed.") }
180
+ file = url
181
+ } else {
182
+ guard let url = bundle.url(forResource: reference, withExtension: nil) else { return nil }
183
+ file = url
184
+ }
185
+ var directory: ObjCBool = false
186
+ guard FileManager.default.fileExists(atPath: file.path, isDirectory: &directory) else { return nil }
187
+ guard !directory.boolValue else { throw LegacyCrocheError("asset_read_failed", "The asset is a directory.") }
188
+ do { return try Data(contentsOf: file) } catch { throw LegacyCrocheError("asset_read_failed", "The asset could not be read.") }
189
+ }
190
+ }
191
+
192
+ /// Resolver facts only: every address the system resolver gives, unfiltered. Core owns policy.
193
+ enum PlatformResolver {
194
+ static func resolve(_ name: String) throws -> [String] {
195
+ var hints = addrinfo()
196
+ hints.ai_family = AF_UNSPEC
197
+ #if canImport(Glibc)
198
+ hints.ai_socktype = Int32(SOCK_STREAM.rawValue) // Glibc imports __socket_type as an enum
199
+ #else
200
+ hints.ai_socktype = Int32(SOCK_STREAM)
201
+ #endif
202
+ var list: UnsafeMutablePointer<addrinfo>?
203
+ let status = getaddrinfo(name, nil, &hints, &list)
204
+ guard status == 0, let first = list else { throw LegacyCrocheError("network_error", "The host name did not resolve.") }
205
+ defer { freeaddrinfo(first) }
206
+ var addresses: [String] = []
207
+ for info in sequence(first: first, next: { $0.pointee.ai_next }) {
208
+ var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
209
+ guard getnameinfo(info.pointee.ai_addr, info.pointee.ai_addrlen, &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST) == 0 else { continue }
210
+ let address = String(cString: buffer)
211
+ if !addresses.contains(address) { addresses.append(address) }
212
+ }
213
+ return addresses
214
+ }
215
+ }
216
+
217
+ /// URLSession cannot dial a pinned address while keeping the URL host's Host/SNI. It serves a pin
218
+ /// only where the pin holds trivially (the URL host is that IP literal); any other pin goes to the
219
+ /// direct client, and where there is none it is `capability_unsupported`, never an unpinned success.
220
+ enum PlatformHTTP {
221
+ /// Whether this platform dials a pin that is not the URL's own IP literal. iOS does not in 0.6
222
+ /// (APP-API:42, Keel 15:43Z): a hostname image or debugger URL is `capability_unsupported`
223
+ /// there; IP literals and loopback are unchanged. macOS keeps the pinned dial. Linux has no
224
+ /// direct client (it needs Network.framework), so it does not dial named pins either.
225
+ #if os(iOS) || !canImport(Network)
226
+ static let dialsNamedPins = false
227
+ #else
228
+ static let dialsNamedPins = true
229
+ #endif
230
+
231
+ /// A pinned request goes through the direct client (true = done); an unpinned one, or an
232
+ /// IP-literal pin equal to the URL host, is URLSession's (false). Where the platform does not
233
+ /// dial named pins, any other pin is `capability_unsupported` before a connection.
234
+ static func direct(_ request: PalHttpRequest, sink: any HttpSinkProtocol, cancel: CancelToken,
235
+ dialsNamedPins: Bool = PlatformHTTP.dialsNamedPins) throws -> Bool {
236
+ guard let pin = request.connectTo, (try? check(request)) == nil else { return false }
237
+ if !dialsNamedPins { try check(request) }
238
+ #if canImport(Network)
239
+ try DirectHTTP().http(request, pin: pin, sink: sink, cancel: cancel)
240
+ return true
241
+ #else
242
+ try check(request)
243
+ return false
244
+ #endif
245
+ }
246
+ static func check(_ request: PalHttpRequest) throws {
247
+ guard let pin = request.connectTo else { return }
248
+ guard let host = URLComponents(string: request.url)?.host, isIPLiteral(host), canonical(host) == canonical(pin) else {
249
+ throw LegacyCrocheError("capability_unsupported", "This platform cannot pin a connection to a resolved address.")
250
+ }
251
+ }
252
+ static func isIPLiteral(_ host: String) -> Bool {
253
+ let bare = host.hasPrefix("[") && host.hasSuffix("]") ? String(host.dropFirst().dropLast()) : host
254
+ var v4 = in_addr(), v6 = in6_addr()
255
+ return inet_pton(AF_INET, bare, &v4) == 1 || inet_pton(AF_INET6, bare, &v6) == 1
256
+ }
257
+ /// One spelling per address, so `[::1]` and `::1` (or `0:0::1`) compare equal.
258
+ static func canonical(_ text: String) -> String {
259
+ let bare = text.hasPrefix("[") && text.hasSuffix("]") ? String(text.dropFirst().dropLast()) : text
260
+ var v4 = in_addr(), v6 = in6_addr()
261
+ var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
262
+ if inet_pton(AF_INET, bare, &v4) == 1, inet_ntop(AF_INET, &v4, &buffer, socklen_t(buffer.count)) != nil { return String(cString: buffer) }
263
+ if inet_pton(AF_INET6, bare, &v6) == 1, inet_ntop(AF_INET6, &v6, &buffer, socklen_t(buffer.count)) != nil { return String(cString: buffer) }
264
+ return bare.lowercased()
265
+ }
266
+ }
@@ -0,0 +1,195 @@
1
+ import Foundation
2
+ #if canImport(Darwin)
3
+ import Darwin
4
+ #elseif canImport(Glibc)
5
+ import Glibc
6
+ #endif
7
+
8
+ /// The 0.6 storage primitives (ARCHITECTURE §2a): opaque UTF-8 values under Core-chosen keys.
9
+ /// Core owns names, framing and retention; this keeps bytes durable and nothing else.
10
+ /// Key encoding is reversible: two hex components, so a 200-byte key fits 255-byte names.
11
+ final class PlatformStorage: @unchecked Sendable {
12
+ private let root: URL
13
+ private let guarded = NSLock()
14
+ /// Held lock files by lock name. flock is per open file: another handle (or process) on the
15
+ /// same directory contends even inside this process.
16
+ private var held: [String: Int32] = [:]
17
+
18
+ init(directory: URL) { root = directory.appendingPathComponent("kv-v1", isDirectory: true) }
19
+
20
+ /// Core's portable key grammar; anything else is a Core bug and never reaches the disk.
21
+ static func valid(_ key: String) -> Bool {
22
+ (1...200).contains(key.utf8.count) && key.utf8.allSatisfy { b in
23
+ (b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122) || b == 46 || b == 95 || b == 47 || b == 45
24
+ }
25
+ }
26
+ private static func hex<S: Sequence>(_ bytes: S) -> String where S.Element == UInt8 {
27
+ bytes.map { String(format: "%02x", $0) }.joined()
28
+ }
29
+ private func path(_ area: String, _ key: String, suffix: String) throws -> URL {
30
+ guard Self.valid(key) else { throw LegacyCrocheError("storage_error", "Invalid storage key.") }
31
+ let bytes = Array(key.utf8), split = min(100, bytes.count)
32
+ return root.appendingPathComponent(area, isDirectory: true)
33
+ .appendingPathComponent(Self.hex(bytes[..<split]), isDirectory: true)
34
+ .appendingPathComponent(Self.hex(bytes[split...]) + suffix)
35
+ }
36
+ private static func decode(_ name: String) -> String? {
37
+ guard name.utf8.count % 2 == 0 else { return nil }
38
+ var bytes: [UInt8] = [], digits = Array(name.utf8)
39
+ var index = 0
40
+ while index < digits.count {
41
+ guard let byte = UInt8(String(decoding: digits[index..<index + 2], as: UTF8.self), radix: 16) else { return nil }
42
+ bytes.append(byte); index += 2
43
+ }
44
+ digits.removeAll()
45
+ guard let key = String(bytes: bytes, encoding: .utf8), valid(key) else { return nil }
46
+ return key
47
+ }
48
+
49
+ func read(_ area: String, _ key: String) throws -> String? {
50
+ let file = try path(area, key, suffix: ".value")
51
+ do { return String(decoding: try Data(contentsOf: file), as: UTF8.self) }
52
+ catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil }
53
+ catch { throw LegacyCrocheError("storage_error", "Storage read failed.") }
54
+ }
55
+
56
+ /// Atomic replace, durable on return: temp file, fsync, rename, then the directory's fsync.
57
+ /// A crash leaves the old value or the new one, never a mix.
58
+ func write(_ area: String, _ key: String, _ value: String) throws {
59
+ let file = try path(area, key, suffix: ".value"), dir = file.deletingLastPathComponent()
60
+ try ensure(dir)
61
+ let temp = dir.appendingPathComponent(file.lastPathComponent + ".tmp-" + UUID().uuidString)
62
+ let fd = open(temp.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
63
+ guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage write failed.") }
64
+ let bytes = Array(value.utf8)
65
+ var written = 0, ok = true
66
+ while written < bytes.count {
67
+ let n = bytes.withUnsafeBufferPointer { posixWrite(fd, $0.baseAddress! + written, bytes.count - written) }
68
+ if n <= 0 { ok = false; break }
69
+ written += n
70
+ }
71
+ ok = ok && fsync(fd) == 0
72
+ close(fd)
73
+ guard ok, rename(temp.path, file.path) == 0 else {
74
+ unlink(temp.path)
75
+ throw LegacyCrocheError("storage_error", "Storage write failed.")
76
+ }
77
+ try sync(dir)
78
+ }
79
+
80
+ /// Real deletion; absent is not an error.
81
+ func remove(_ area: String, _ key: String) throws {
82
+ let file = try path(area, key, suffix: ".value")
83
+ if unlink(file.path) != 0 && errno != ENOENT { throw LegacyCrocheError("storage_error", "Storage remove failed.") }
84
+ if FileManager.default.fileExists(atPath: file.deletingLastPathComponent().path) { try sync(file.deletingLastPathComponent()) }
85
+ }
86
+
87
+ /// All and only the keys starting with `prefix`, in any order. Temporary files are not keys.
88
+ func list(_ area: String, _ prefix: String) throws -> [String] {
89
+ let base = root.appendingPathComponent(area, isDirectory: true), files = FileManager.default
90
+ guard let heads = try? files.contentsOfDirectory(atPath: base.path) else { return [] }
91
+ var keys: [String] = []
92
+ for head in heads {
93
+ guard let tails = try? files.contentsOfDirectory(atPath: base.appendingPathComponent(head).path) else { continue }
94
+ for tail in tails where tail.hasSuffix(".value") {
95
+ guard let key = Self.decode(head + tail.dropLast(6)) else { throw LegacyCrocheError("storage_error", "Invalid storage filename.") }
96
+ if key.hasPrefix(prefix) { keys.append(key) }
97
+ }
98
+ }
99
+ return keys
100
+ }
101
+
102
+ /// Exclusive across handles and processes; contention is the fact `.held`, never an error
103
+ /// and never a wait.
104
+ @discardableResult func lock(_ name: String) throws -> PalLockOutcome {
105
+ let file = try path("locks", name, suffix: ".lock")
106
+ try ensure(file.deletingLastPathComponent())
107
+ return try guarded.withLock {
108
+ guard held[name] == nil else { return .held }
109
+ let fd = open(file.path, O_RDWR | O_CREAT, 0o600)
110
+ guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage lock failed.") }
111
+ guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
112
+ let busy = errno == EWOULDBLOCK
113
+ close(fd)
114
+ if busy { return .held }
115
+ throw LegacyCrocheError("storage_error", "Storage lock failed.")
116
+ }
117
+ held[name] = fd
118
+ return .acquired
119
+ }
120
+ }
121
+ func unlock(_ name: String) {
122
+ guard let fd = guarded.withLock({ held.removeValue(forKey: name) }) else { return }
123
+ flock(fd, LOCK_UN); close(fd)
124
+ }
125
+
126
+ private func ensure(_ dir: URL) throws {
127
+ do { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) }
128
+ catch { throw LegacyCrocheError("storage_error", "Storage directory failed.") }
129
+ }
130
+ private func sync(_ dir: URL) throws {
131
+ let fd = open(dir.path, O_RDONLY)
132
+ guard fd >= 0 else { throw LegacyCrocheError("storage_error", "Storage sync failed.") }
133
+ defer { close(fd) }
134
+ guard fsync(fd) == 0 else { throw LegacyCrocheError("storage_error", "Storage sync failed.") }
135
+ }
136
+ }
137
+
138
+ #if canImport(Darwin)
139
+ private let posixWrite = Darwin.write
140
+ #else
141
+ private let posixWrite = Glibc.write
142
+ #endif
143
+
144
+ /// Where secrets live: apart from state, never through `read` or `list`.
145
+ protocol PlatformSecrets: Sendable {
146
+ func read(_ key: String) throws -> String?
147
+ func write(_ key: String, _ value: String) throws
148
+ func remove(_ key: String) throws
149
+ }
150
+
151
+ /// Files in their own area: hosts without a Keychain, and Croche's own tests.
152
+ struct FileSecrets: PlatformSecrets {
153
+ let storage: PlatformStorage
154
+ func read(_ key: String) throws -> String? { try storage.read("secrets", key) }
155
+ func write(_ key: String, _ value: String) throws { try storage.write("secrets", key, value) }
156
+ func remove(_ key: String) throws { try storage.remove("secrets", key) }
157
+ }
158
+
159
+ #if canImport(Security) && !os(Linux)
160
+ import Security
161
+
162
+ /// One Keychain generic-password item per Core secret key, readable after first unlock on
163
+ /// this device only (never in a backup or on another device).
164
+ struct KeychainSecrets: PlatformSecrets {
165
+ var service = "ai.croche.pal"
166
+ private func query(_ key: String) -> [String: Any] {
167
+ [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: key]
168
+ }
169
+ func read(_ key: String) throws -> String? {
170
+ var lookup = query(key)
171
+ lookup[kSecReturnData as String] = true
172
+ lookup[kSecMatchLimit as String] = kSecMatchLimitOne
173
+ var item: CFTypeRef?
174
+ let status = SecItemCopyMatching(lookup as CFDictionary, &item)
175
+ if status == errSecItemNotFound { return nil }
176
+ guard status == errSecSuccess, let data = item as? Data else { throw LegacyCrocheError("storage_error", "Keychain read failed (\(status)).") }
177
+ return String(decoding: data, as: UTF8.self)
178
+ }
179
+ func write(_ key: String, _ value: String) throws {
180
+ let data = Data(value.utf8)
181
+ let update = SecItemUpdate(query(key) as CFDictionary, [kSecValueData as String: data] as CFDictionary)
182
+ if update == errSecSuccess { return }
183
+ guard update == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(update)).") }
184
+ var add = query(key)
185
+ add[kSecValueData as String] = data
186
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
187
+ let status = SecItemAdd(add as CFDictionary, nil)
188
+ guard status == errSecSuccess else { throw LegacyCrocheError("storage_error", "Keychain write failed (\(status)).") }
189
+ }
190
+ func remove(_ key: String) throws {
191
+ let status = SecItemDelete(query(key) as CFDictionary)
192
+ guard status == errSecSuccess || status == errSecItemNotFound else { throw LegacyCrocheError("storage_error", "Keychain delete failed (\(status)).") }
193
+ }
194
+ }
195
+ #endif