@h1r-ai/croche-react-native 0.6.0 → 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 (183) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -4
  3. package/THIRD-PARTY-NOTICES +899 -6
  4. package/android/src/androidTest/java/dev/croche/reactnative/WikiFileBridgeTest.kt +4 -3
  5. package/android/src/main/AndroidManifest.xml +0 -5
  6. package/android/src/main/java/dev/croche/reactnative/CoreDispatch.kt +33 -8
  7. package/android/src/main/java/dev/croche/reactnative/CoreWire.kt +139 -5
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +5 -2
  9. package/android/src/main/java/dev/croche/reactnative/NativePal.kt +23 -6
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +28 -6
  11. package/android/src/test/java/dev/croche/reactnative/BackgroundDelegationTest.kt +4 -11
  12. package/android/src/test/java/dev/croche/reactnative/BlobFilesTest.kt +107 -0
  13. package/android/src/test/java/dev/croche/reactnative/ImageAdapterWireTest.kt +70 -0
  14. package/android/src/test/java/dev/croche/reactnative/OpenForwardingFixture.kt +19 -4
  15. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +2 -2
  16. package/android/src/test/java/dev/croche/reactnative/StorageVersionWireTest.kt +37 -0
  17. package/android/src/test/java/dev/croche/reactnative/VerificationDispatchTest.kt +24 -0
  18. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +5 -3
  19. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BackgroundWakeWorker.kt +4 -0
  20. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapDecodedImageCodec.kt +11 -11
  21. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +1 -0
  22. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidCoreHost.kt +11 -16
  23. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidPublicPlatform.kt +3 -3
  24. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStateStore.kt +216 -0
  25. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/pal/AndroidStoragePal.kt +45 -10
  26. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +0 -3
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Adapters.kt +75 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/BindingFacts.kt +1 -1
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ContextConfig.kt +9 -23
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +11 -2
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +83 -20
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +54 -8
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +19 -360
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheTools.kt +79 -10
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Decision.kt +170 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/DecodedImageCodec.kt +8 -5
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +8 -1
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/EncodedImageCodec.kt +51 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/GeneratedAppStream.kt +426 -33
  40. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +1 -351
  41. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +15 -29
  42. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeEvent.kt +59 -0
  43. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeHandleOwner.kt +118 -0
  44. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +10 -74
  45. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +196 -10
  46. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/PublicResults.kt +86 -3
  47. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/RunTool.kt +33 -0
  48. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +1 -1
  49. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StateStore.kt +90 -0
  50. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +68 -4
  51. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +3403 -6894
  52. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/AppStoragePal.kt +89 -18
  53. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreFactoryCalls.kt +1 -2
  54. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreOptionsEncoding.kt +2 -2
  55. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/CoreStreamCalls.kt +3 -3
  56. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ForeignCallbacks.kt +17 -18
  57. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/ImageAdapterHost.kt +28 -0
  58. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmCoreHost.kt +12 -14
  59. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStateStore.kt +125 -0
  60. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/JvmStoragePal.kt +36 -6
  61. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativeCoreInitialization.kt +21 -0
  62. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/NativePlatform.kt +21 -6
  63. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/PublicCalls.kt +16 -7
  64. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StateStoreContract.kt +103 -0
  65. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/StorageVersionContract.kt +40 -0
  66. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/AtomicKeyFiles.kt +25 -4
  67. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/BlobFiles.kt +157 -0
  68. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/InstancePayloadPurge.kt +79 -0
  69. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/s7/pal/VersionedKeyFiles.kt +71 -0
  70. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  71. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  72. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  73. package/croche-react-native.podspec +1 -0
  74. package/dist/react-native/src/core-native.d.ts +3 -0
  75. package/dist/react-native/src/core-native.js +148 -25
  76. package/dist/react-native/src/core-wire.d.ts +20 -3
  77. package/dist/rn-shared-build.json +8 -8
  78. package/dist/runtime/src/adapters.d.ts +8 -0
  79. package/dist/runtime/src/adapters.js +29 -0
  80. package/dist/runtime/src/agent.d.ts +53 -5
  81. package/dist/runtime/src/agent.js +69 -7
  82. package/dist/runtime/src/app-api.d.ts +307 -19
  83. package/dist/runtime/src/cancel.d.ts +2 -2
  84. package/dist/runtime/src/cancel.js +7 -4
  85. package/dist/runtime/src/core/foreground.d.ts +3 -0
  86. package/dist/runtime/src/core/foreground.js +40 -0
  87. package/dist/runtime/src/core/port.d.ts +48 -35
  88. package/dist/runtime/src/core/wasm-owner.d.ts +32 -0
  89. package/dist/runtime/src/core/wasm-owner.js +237 -0
  90. package/dist/runtime/src/croche.d.ts +64 -9
  91. package/dist/runtime/src/croche.js +78 -17
  92. package/dist/runtime/src/errors.d.ts +7 -0
  93. package/dist/runtime/src/errors.js +15 -1
  94. package/dist/runtime/src/generated/app-stream.d.ts +155 -1
  95. package/dist/runtime/src/generated/app-stream.js +7 -4
  96. package/dist/runtime/src/image-input.d.ts +5 -0
  97. package/dist/runtime/src/image-input.js +60 -0
  98. package/dist/runtime/src/index.d.ts +6 -0
  99. package/dist/runtime/src/index.js +5 -0
  100. package/dist/runtime/src/index.native.d.ts +1 -21
  101. package/dist/runtime/src/index.native.js +2 -8
  102. package/dist/runtime/src/native-adapter.d.ts +1 -1
  103. package/dist/runtime/src/native-adapter.js +10 -4
  104. package/dist/runtime/src/pal/host.d.ts +3 -3
  105. package/dist/runtime/src/pal/host.js +34 -9
  106. package/dist/runtime/src/pal/platform.d.ts +11 -6
  107. package/dist/runtime/src/pal/state-store-lock.d.ts +8 -0
  108. package/dist/runtime/src/pal/state-store-lock.js +2 -0
  109. package/dist/runtime/src/pal/state-store.d.ts +66 -0
  110. package/dist/runtime/src/pal/state-store.js +1 -0
  111. package/dist/runtime/src/pal/storage-version-contract.d.ts +19 -0
  112. package/dist/runtime/src/pal/storage-version-contract.js +68 -0
  113. package/dist/runtime/src/pal/transactional-storage.d.ts +3 -0
  114. package/dist/runtime/src/pal/transactional-storage.js +124 -0
  115. package/dist/runtime/src/tools.d.ts +20 -4
  116. package/dist/runtime/src/tools.js +31 -7
  117. package/ios/CoreAgentTransport.swift +2 -2
  118. package/ios/CoreNativePal.swift +26 -21
  119. package/ios/CorePlatformTransport.swift +4 -4
  120. package/ios/CoreWireDispatch.swift +38 -8
  121. package/ios/CoreWireSupport.swift +179 -4
  122. package/ios/CrocheRuntimeBridge.swift +1 -1
  123. package/ios/ProjectPal.swift +15 -12
  124. package/ios/vendor/CrocheRuntimeSDK/BlobFiles.swift +124 -0
  125. package/ios/vendor/CrocheRuntimeSDK/ContextConfig.swift +2 -6
  126. package/ios/vendor/CrocheRuntimeSDK/EncodedImages.swift +85 -0
  127. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +1 -174
  128. package/ios/vendor/CrocheRuntimeSDK/GeneratedAppStream.swift +233 -4
  129. package/ios/vendor/CrocheRuntimeSDK/Host.swift +1 -399
  130. package/ios/vendor/CrocheRuntimeSDK/ImagePal.swift +3 -3
  131. package/ios/vendor/CrocheRuntimeSDK/InstancePayloadPurge.swift +88 -0
  132. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +26 -10
  133. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +0 -155
  134. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +1 -27
  135. package/ios/vendor/CrocheRuntimeSDK/PlatformBackground.swift +8 -4
  136. package/ios/vendor/CrocheRuntimeSDK/PlatformPal.swift +57 -21
  137. package/ios/vendor/CrocheRuntimeSDK/PlatformStateStore.swift +253 -0
  138. package/ios/vendor/CrocheRuntimeSDK/PlatformStorage.swift +96 -10
  139. package/ios/vendor/CrocheRuntimeSDK/Project.swift +3 -382
  140. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +1 -412
  141. package/ios/vendor/CrocheRuntimeSDK/RuntimeHTTPAdapter.swift +42 -0
  142. package/ios/vendor/CrocheRuntimeSDK/S1/S1Adapters.swift +110 -0
  143. package/ios/vendor/CrocheRuntimeSDK/S1/S1Agent.swift +86 -33
  144. package/ios/vendor/CrocheRuntimeSDK/S1/S1Allowance.swift +20 -0
  145. package/ios/vendor/CrocheRuntimeSDK/S1/S1BindingFacts.swift +1 -1
  146. package/ios/vendor/CrocheRuntimeSDK/S1/S1Core.swift +12 -3
  147. package/ios/vendor/CrocheRuntimeSDK/S1/S1Croche.swift +135 -56
  148. package/ios/vendor/CrocheRuntimeSDK/S1/S1Decision.swift +146 -0
  149. package/ios/vendor/CrocheRuntimeSDK/S1/S1Events.swift +17 -8
  150. package/ios/vendor/CrocheRuntimeSDK/S1/S1HandleOwner.swift +58 -0
  151. package/ios/vendor/CrocheRuntimeSDK/S1/S1Options.swift +184 -15
  152. package/ios/vendor/CrocheRuntimeSDK/S1/S1RunTool.swift +31 -3
  153. package/ios/vendor/CrocheRuntimeSDK/S1/S1Storage.swift +131 -61
  154. package/ios/vendor/CrocheRuntimeSDK/S1/S1TestHooks.swift +10 -15
  155. package/ios/vendor/CrocheRuntimeSDK/S1/S1Tools.swift +86 -17
  156. package/ios/vendor/CrocheRuntimeSDK/S1/S1Verification.swift +27 -0
  157. package/ios/vendor/CrocheRuntimeSDK/S1/StateStoreContract.swift +189 -0
  158. package/ios/vendor/CrocheRuntimeSDK/S1/StorageVersionContract.swift +68 -0
  159. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +3 -249
  160. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +40 -8
  161. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +1720 -3883
  162. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +816 -1649
  163. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  164. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +816 -1649
  165. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +2 -2
  166. package/package.json +3 -3
  167. package/scripts/README.md +1 -1
  168. package/scripts/check-swift-vendor-modules.sh +15 -0
  169. package/scripts/vendor-native.sh +4 -3
  170. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +0 -32
  171. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +0 -146
  172. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +0 -113
  173. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +0 -201
  174. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +0 -25
  175. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +0 -87
  176. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +0 -181
  177. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StoragePal.kt +0 -18
  178. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +0 -252
  179. package/dist/runtime/src/pal/codec.d.ts +0 -15
  180. package/dist/runtime/src/pal/codec.js +0 -52
  181. package/ios/vendor/CrocheRuntimeSDK/Background.swift +0 -59
  182. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +0 -496
  183. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +0 -44
@@ -9,6 +9,7 @@ import kotlin.coroutines.resumeWithException
9
9
 
10
10
  /** No result/default/code policy: only translate Core's supplied public error envelope. */
11
11
  internal fun publicFailure(error: Throwable): Throwable = when (error) {
12
+ is java.lang.reflect.UndeclaredThrowableException -> publicFailure(error.undeclaredThrowable)
12
13
  is CrocheError -> error
13
14
  is CoreApiException.Failure -> CrocheError(error.code, error.detail,
14
15
  ErrorCategory.entries.firstOrNull { it.name.equals(error.category, ignoreCase = true) } ?: ErrorCategory.INTERNAL, error.path, error.retryAfter)
@@ -20,15 +21,23 @@ private val calls = CoroutineScope(SupervisorJob() + Dispatchers.IO)
20
21
  /** One off-thread native call; cancellation fires the Core token, never Agent.cancel(). */
21
22
  @OptIn(ExperimentalCoroutinesApi::class)
22
23
  internal suspend fun <T> publicCall(discard: (T) -> Unit = {}, block: (CancelToken) -> T): T = suspendCancellableCoroutine { continuation ->
24
+ ensureNativeCoreInitialized()
23
25
  val token = CancelToken()
24
- continuation.invokeOnCancellation { token.cancel() }
26
+ val tokenLock = Any()
27
+ var tokenLive = true
28
+ continuation.invokeOnCancellation { synchronized(tokenLock) { if (tokenLive) token.cancel() } }
25
29
  calls.launch {
26
- val answer: Result<T> = runCatching { publicSync { block(token) } }
27
- answer.fold(
28
- { value -> continuation.resume(value) { _, unreceived, _ -> discard(unreceived) } },
29
- { error -> continuation.resumeWithException(error) },
30
- )
30
+ try {
31
+ val answer: Result<T> = runCatching { publicSync { block(token) } }
32
+ answer.fold(
33
+ { value -> continuation.resume(value) { _, unreceived, _ -> discard(unreceived) } },
34
+ { error -> continuation.resumeWithException(error) },
35
+ )
36
+ } finally { synchronized(tokenLock) { tokenLive = false; token.destroy() } }
31
37
  }
32
38
  }
33
39
 
34
- internal fun <T> publicSync(block: () -> T): T = try { block() } catch (error: Throwable) { throw publicFailure(error) }
40
+ internal fun <T> publicSync(block: () -> T): T {
41
+ ensureNativeCoreInitialized()
42
+ return try { block() } catch (error: Throwable) { throw publicFailure(error) }
43
+ }
@@ -0,0 +1,103 @@
1
+ package dev.croche.s7
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonNull
5
+ import com.google.gson.JsonParser
6
+ import dev.croche.StateCommitResult
7
+ import dev.croche.StateCondition
8
+ import dev.croche.StateEntry
9
+ import dev.croche.StateListOptions
10
+ import dev.croche.StateOp
11
+ import dev.croche.StatePage
12
+ import dev.croche.ffi.CoreStateCommit
13
+ import dev.croche.ffi.CoreStateCondition
14
+ import dev.croche.ffi.CoreStateEntry
15
+ import dev.croche.ffi.CoreStateListOptions
16
+ import dev.croche.ffi.CoreStateOp
17
+ import dev.croche.ffi.CoreStatePage
18
+
19
+ private val stateKeyPattern = Regex("[A-Za-z0-9._/-]{1,200}")
20
+ internal fun stateKey(key: String): String {
21
+ require(stateKeyPattern.matches(key)) { "Invalid StateStore key" }
22
+ return key
23
+ }
24
+
25
+ internal fun validateStateBatch(ops: List<StateOp>, condition: StateCondition) {
26
+ stateKey(condition.key)
27
+ storageVersion(condition.version)
28
+ require(ops.isNotEmpty()) { "Invalid StateStore batch" }
29
+ val keys = mutableSetOf<String>()
30
+ for (op in ops) {
31
+ stateKey(op.key)
32
+ require(keys.add(op.key)) { "Invalid StateStore batch" }
33
+ }
34
+ }
35
+
36
+ /** Bounds use Core's ASCII key grammar, so SQLite BINARY is the same UTF-8 order. */
37
+ internal class StateRange(private val prefix: String, private val options: StateListOptions) {
38
+ val lower: String
39
+ val upper: String
40
+ val after: String
41
+ val limit: Int
42
+ val reverse = options.reverse
43
+
44
+ // The two key bounds of this page (HLD storage, "Range reads"). A cursor replaces a bound.
45
+ // Written as a third predicate it makes SQLite seek to the range start and filter every
46
+ // earlier page again.
47
+ private val resumed = options.cursor != null
48
+ /** Lower bound: exclusive when an ascending walk resumes after its cursor, else inclusive. */
49
+ val from: String get() = if (!reverse && resumed) after else lower
50
+ val fromExclusive: Boolean get() = !reverse && resumed
51
+ /** Upper bound, always exclusive: the cursor when a descending walk resumes. */
52
+ val to: String get() = if (reverse && resumed) after else upper
53
+ /** The key bounds and order of the page statement; binds `from`, `to`, then the row limit. */
54
+ val bounds: String get() =
55
+ "FROM state WHERE key ${if (fromExclusive) ">" else ">="} ? AND key < ? ORDER BY key ${if (reverse) "DESC" else "ASC"} LIMIT ?"
56
+
57
+ init {
58
+ if (prefix.isNotEmpty()) stateKey(prefix)
59
+ options.start?.let(::stateKey)
60
+ val size = options.limit ?: 128u
61
+ require(size > 0u) { "Invalid StateStore list limit" }
62
+ limit = minOf(size, 128u).toInt()
63
+ lower = maxOf(prefix, options.start ?: prefix)
64
+ upper = if (prefix.isEmpty()) "\u007f" else prefix.dropLast(1) + (prefix.last() + 1)
65
+ after = options.cursor?.let { cursor ->
66
+ try {
67
+ val fields = JsonParser.parseString(cursor).asJsonArray
68
+ require(fields.size() == 4 && fields[0].asJsonPrimitive.isString && fields[0].asString == prefix)
69
+ require(if (options.start == null) fields[1].isJsonNull else
70
+ fields[1].asJsonPrimitive.isString && fields[1].asString == options.start)
71
+ require(fields[2].asJsonPrimitive.isBoolean && fields[2].asBoolean == reverse)
72
+ require(fields[3].asJsonPrimitive.isString)
73
+ stateKey(fields[3].asString).also { require(it >= lower && it < upper) }
74
+ } catch (_: RuntimeException) {
75
+ throw IllegalArgumentException("Invalid StateStore cursor")
76
+ }
77
+ } ?: if (reverse) upper else ""
78
+ }
79
+
80
+ /** `more`: the adapter stopped before the range ended, so a short page still carries a cursor. */
81
+ fun page(rows: List<StateEntry>, more: Boolean = false): StatePage {
82
+ val entries = rows.take(limit)
83
+ val cursor = if (rows.size > limit || (more && entries.isNotEmpty())) JsonArray().apply {
84
+ add(prefix)
85
+ if (options.start == null) add(JsonNull.INSTANCE) else add(options.start)
86
+ add(reverse)
87
+ add(entries.last().key)
88
+ }.toString() else null
89
+ return StatePage(entries, cursor)
90
+ }
91
+ }
92
+
93
+ internal fun CoreStateCondition.toApp() = StateCondition(key, version)
94
+ internal fun CoreStateListOptions.toApp() = StateListOptions(start, reverse, limit, cursor)
95
+ internal fun CoreStateOp.toApp(): StateOp = when (this) {
96
+ is CoreStateOp.Put -> StateOp.Put(key, value)
97
+ is CoreStateOp.Delete -> StateOp.Delete(key)
98
+ }
99
+ internal fun StateCommitResult.toCore(): CoreStateCommit = when (this) {
100
+ is StateCommitResult.Committed -> CoreStateCommit.Committed(storageVersion(version))
101
+ StateCommitResult.Conflict -> CoreStateCommit.Conflict
102
+ }
103
+ internal fun StatePage.toCore() = CoreStatePage(entries.map { CoreStateEntry(it.key, it.value) }, nextCursor)
@@ -0,0 +1,40 @@
1
+ package dev.croche.s7
2
+
3
+ import dev.croche.VersionedValue
4
+ import dev.croche.WriteOutcome
5
+ import dev.croche.ffi.CoreVersionedValue
6
+ import dev.croche.ffi.CoreWriteOutcome
7
+ import java.io.IOException
8
+
9
+ internal fun logicalStorageKey(key: String): String {
10
+ if (key.trimEnd('/').substringAfterLast('/') == ".p1") throw IOException("Reserved storage sibling")
11
+ return key
12
+ }
13
+ internal fun versionedStorageKey(key: String): String {
14
+ logicalStorageKey(key)
15
+ if (!Regex("[A-Za-z0-9._/-]{1,196}").matches(key) || key.split('/').contains("secret-index")) {
16
+ throw IOException("Invalid versioned storage key")
17
+ }
18
+ return key
19
+ }
20
+ internal fun storageVersion(token: String?): String? {
21
+ if (token != null && (token.isEmpty() || token.length > 128 || token.any { it.code !in 0x21..0x7e })) {
22
+ throw IOException("Invalid storage version")
23
+ }
24
+ return token
25
+ }
26
+ internal fun VersionedValue.toCore(): CoreVersionedValue {
27
+ val token = storageVersion(version)
28
+ if ((value == null) != (token == null)) throw IOException("Unpaired storage value and version")
29
+ return CoreVersionedValue(value, token)
30
+ }
31
+ /** Pair with the immutable request value, never a later read/current request. */
32
+ internal fun WriteOutcome.toCore(requestedValue: String?): CoreWriteOutcome = when (this) {
33
+ is WriteOutcome.Conflict -> CoreWriteOutcome.Conflict(storageVersion(version))
34
+ is WriteOutcome.Written -> {
35
+ val token = storageVersion(version)
36
+ if ((requestedValue == null) != (token == null)) throw IOException("Written version does not match request")
37
+ if (token == "legacy") throw IOException("Written must return a new storage version")
38
+ CoreWriteOutcome.Written(token)
39
+ }
40
+ }
@@ -25,13 +25,22 @@ internal class AtomicKeyFiles(private val root: File, private val syncDirectory:
25
25
  if (!directory.mkdir() && !directory.isDirectory) throw java.io.IOException("Cannot create PAL directory")
26
26
  directory.parentFile?.let(syncDirectory)
27
27
  }
28
- fun read(key: String): String? = storage {
28
+ internal fun instancePurgePlan(prefix: String) = planInstancePayloads(File(root, "values"), prefix, syncDirectory)
29
+ private val versioned by lazy { VersionedKeyFiles(this) }
30
+ fun read(key: String) = versioned.read(key)
31
+ fun write(key: String, value: String) = versioned.write(key, value)
32
+ fun remove(key: String) = versioned.remove(key)
33
+ fun list(prefix: String) = versioned.list(prefix)
34
+ fun readVersioned(key: String) = versioned.readVersioned(key)
35
+ fun writeIf(key: String, value: String?, expect: String?) = versioned.writeIf(key, value, expect)
36
+ // Private physical paths only; never expose a reservation bypass at the PAL boundary.
37
+ internal fun readRaw(key: String): String? = storage {
29
38
  val file = path(key, "values")
30
39
  try { file.readText(Charsets.UTF_8) } catch (e: java.io.FileNotFoundException) {
31
40
  if (file.exists()) throw e else null
32
41
  }
33
42
  }
34
- fun write(key: String, value: String) = storage {
43
+ internal fun writeRaw(key: String, value: String) = storage {
35
44
  val target = path(key, "values")
36
45
  mkdirs(target.parentFile!!)
37
46
  val temporary = File.createTempFile("pending-", ".tmp", target.parentFile)
@@ -43,12 +52,12 @@ internal class AtomicKeyFiles(private val root: File, private val syncDirectory:
43
52
  } finally { temporary.delete() }
44
53
  Unit
45
54
  }
46
- fun remove(key: String) = storage {
55
+ internal fun removeRaw(key: String) = storage {
47
56
  val file = path(key, "values")
48
57
  if (Files.deleteIfExists(file.toPath())) syncDirectory(file.parentFile!!)
49
58
  Unit
50
59
  }
51
- fun list(prefix: String): List<String> = storage {
60
+ internal fun listRaw(prefix: String): List<String> = storage {
52
61
  val directory = File(root, "values")
53
62
  if (!directory.exists()) return@storage emptyList()
54
63
  directory.walkTopDown().filter { it.isFile && it.name == "value" }.map { file ->
@@ -74,6 +83,18 @@ internal class AtomicKeyFiles(private val root: File, private val syncDirectory:
74
83
  // Never unlink the lock inode: another process may already hold it.
75
84
  Unit
76
85
  }
86
+ /** Independent per-key cross-process gate; never reacquire a Core lifetime lock. */
87
+ internal fun <T> mutation(key: String, block: () -> T): T {
88
+ // Custody metadata contains no reversible key, value, version or deletion receipt.
89
+ val name = java.security.MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8))
90
+ .joinToString("") { "%02x".format(it.toInt() and 255) }
91
+ val file = File(File(root, "writers"), "$name.lock"); mkdirs(file.parentFile!!)
92
+ return RandomAccessFile(file, "rw").use { opened ->
93
+ val gate = try { opened.channel.tryLock() } catch (_: OverlappingFileLockException) { null }
94
+ if (gate == null) throw java.io.IOException("A value mutation is already active")
95
+ try { block() } finally { gate.release() }
96
+ }
97
+ }
77
98
  // Exceptions remain raw facts; the Core callback boundary assigns storage_error.
78
99
  private inline fun <T> storage(block: () -> T): T = block()
79
100
  }
@@ -0,0 +1,157 @@
1
+ package dev.croche.s7.pal
2
+
3
+ import dev.croche.ffi.FfiException
4
+ import dev.croche.ffi.PalBlobEntry
5
+ import dev.croche.ffi.PalBlobReply
6
+ import java.io.File
7
+ import java.io.FileOutputStream
8
+ import java.io.IOException
9
+ import java.nio.file.FileAlreadyExistsException
10
+ import java.nio.file.Files
11
+ import java.nio.file.LinkOption.NOFOLLOW_LINKS
12
+ import java.nio.file.NoSuchFileException
13
+ import java.nio.file.StandardCopyOption.ATOMIC_MOVE
14
+ import java.nio.file.StandardCopyOption.REPLACE_EXISTING
15
+ import java.nio.file.attribute.BasicFileAttributes
16
+
17
+ /** Private file transport for Core's blob keys. The bytes on disk are the original bytes. */
18
+ internal class BlobFiles(
19
+ private val parent: File,
20
+ private val prepareParent: (() -> Unit)? = null,
21
+ private val syncDirectory: (File) -> Unit,
22
+ ) {
23
+ internal data class Entry(val key: String, val size: Long)
24
+ internal data class Page(val entries: List<Entry>, val nextCursor: String?)
25
+
26
+ private val root = File(parent, "blobs")
27
+ private val segment = Regex("[a-z0-9~][a-z0-9._~-]*")
28
+
29
+ private fun createDirectory(path: File) {
30
+ try {
31
+ Files.createDirectory(path.toPath())
32
+ syncDirectory(path.parentFile)
33
+ } catch (_: FileAlreadyExistsException) {
34
+ // A concurrent publisher may have created the same ancestor.
35
+ }
36
+ if (!Files.isDirectory(path.toPath(), NOFOLLOW_LINKS)) throw IOException("Invalid blob directory")
37
+ }
38
+
39
+ private fun directory(key: String, create: Boolean): File? {
40
+ val parts = if (key.isEmpty()) emptyList() else key.split('/')
41
+ require(key.length <= 1024 && parts.all(segment::matches)) { "Invalid blob key" }
42
+ if (create && !Files.isDirectory(parent.toPath(), NOFOLLOW_LINKS)) {
43
+ if (!Files.exists(parent.toPath(), NOFOLLOW_LINKS)) prepareParent?.invoke()
44
+ createDirectory(parent)
45
+ }
46
+ var path = root
47
+ for (part in listOf("") + parts) {
48
+ if (part.isNotEmpty()) path = path.resolve(part)
49
+ if (create) createDirectory(path)
50
+ else {
51
+ if (!Files.exists(path.toPath(), NOFOLLOW_LINKS)) return null
52
+ if (!Files.isDirectory(path.toPath(), NOFOLLOW_LINKS)) throw IOException("Invalid blob directory")
53
+ }
54
+ }
55
+ return path
56
+ }
57
+
58
+ fun operation(operation: String, key: String, cursor: String?, bytes: ByteArray?): PalBlobReply {
59
+ try {
60
+ when (operation) {
61
+ "get" -> return PalBlobReply(get(key), emptyList(), null)
62
+ "put" -> put(key, requireNotNull(bytes))
63
+ "delete" -> delete(key)
64
+ "list" -> {
65
+ val page = list(key, cursor)
66
+ return PalBlobReply(null, page.entries.map { PalBlobEntry(it.key, it.size.toULong()) }, page.nextCursor)
67
+ }
68
+ "purgeStaging" -> purgeStaging(key)
69
+ else -> throw IOException("Unknown blob operation")
70
+ }
71
+ return PalBlobReply(null, emptyList(), null)
72
+ } catch (error: Exception) {
73
+ // Keep platform diagnostics attached locally. The FFI detail carries no filesystem paths.
74
+ throw FfiException.Failure("storage_error", "Blob operation failed").apply { initCause(error) }
75
+ }
76
+ }
77
+
78
+ fun put(key: String, bytes: ByteArray) {
79
+ require(key.isNotEmpty())
80
+ val dir = directory(key, true) ?: throw IOException("Blob directory disappeared")
81
+ val temporary = Files.createTempFile(dir.toPath(), ".tmp-", "").toFile()
82
+ try {
83
+ FileOutputStream(temporary).use { file -> file.write(bytes); file.fd.sync() }
84
+ Files.move(temporary.toPath(), dir.resolve("object").toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
85
+ syncDirectory(dir)
86
+ } finally {
87
+ Files.deleteIfExists(temporary.toPath())
88
+ }
89
+ }
90
+
91
+ fun get(key: String): ByteArray? {
92
+ require(key.isNotEmpty())
93
+ val path = directory(key, false)?.resolve("object")?.toPath() ?: return null
94
+ if (!Files.exists(path, NOFOLLOW_LINKS)) return null
95
+ if (!Files.isRegularFile(path, NOFOLLOW_LINKS)) throw IOException("Invalid blob object")
96
+ return Files.readAllBytes(path)
97
+ }
98
+
99
+ fun delete(key: String) {
100
+ require(key.isNotEmpty())
101
+ val dir = directory(key, false) ?: return
102
+ if (Files.deleteIfExists(dir.resolve("object").toPath())) syncDirectory(dir)
103
+ }
104
+
105
+ fun list(prefix: String, cursor: String?): Page {
106
+ val parent = prefix.substringBeforeLast('/', "")
107
+ val dir = directory(parent, false) ?: return Page(emptyList(), null)
108
+ val entries = ArrayList<Entry>()
109
+ fun walk(folder: File, key: String) {
110
+ Files.newDirectoryStream(folder.toPath()).use { children ->
111
+ for (child in children) {
112
+ val name = child.fileName.toString()
113
+ if (name == "object" && key.startsWith(prefix) &&
114
+ (cursor == null || key > cursor) && Files.isRegularFile(child, NOFOLLOW_LINKS)) {
115
+ entries.add(Entry(key, Files.size(child)))
116
+ } else if (segment.matches(name) && Files.isDirectory(child, NOFOLLOW_LINKS)) {
117
+ val childKey = if (key.isEmpty()) name else "$key/$name"
118
+ if (childKey.startsWith(prefix) || prefix.startsWith("$childKey/")) {
119
+ walk(child.toFile(), childKey)
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ walk(dir, parent)
126
+ entries.sortBy(Entry::key)
127
+ val page = entries.take(1000)
128
+ return Page(page, if (entries.size > page.size) page.last().key else null)
129
+ }
130
+
131
+ /** The owning Core writer has drained this scope before calling this. */
132
+ fun purgeStaging(prefix: String) {
133
+ require(prefix.length > 1 && prefix.endsWith('/'))
134
+ val dir = directory(prefix.dropLast(1), false) ?: return
135
+ removeStagedFiles(dir)
136
+ }
137
+
138
+ private fun removeStagedFiles(dir: File) {
139
+ // The exact owner lease covers the no-follow check and subsequent unlink.
140
+ Files.newDirectoryStream(dir.toPath()).use { children ->
141
+ for (child in children) {
142
+ val name = child.fileName.toString()
143
+ val facts = try {
144
+ Files.readAttributes(child, BasicFileAttributes::class.java, NOFOLLOW_LINKS)
145
+ } catch (_: NoSuchFileException) {
146
+ continue
147
+ }
148
+ if (facts.isRegularFile && name.startsWith(".tmp-")) {
149
+ Files.deleteIfExists(child)
150
+ } else if (facts.isDirectory && segment.matches(name)) {
151
+ removeStagedFiles(child.toFile())
152
+ }
153
+ }
154
+ }
155
+ syncDirectory(dir)
156
+ }
157
+ }
@@ -0,0 +1,79 @@
1
+ package dev.croche.s7.pal
2
+
3
+ import java.io.File
4
+ import java.io.IOException
5
+ import java.nio.ByteBuffer
6
+ import java.nio.charset.StandardCharsets
7
+ import java.nio.file.Files
8
+ import java.nio.file.LinkOption.NOFOLLOW_LINKS
9
+ import java.util.Base64
10
+
11
+ internal data class PayloadPurgePlan(
12
+ val temporaries: List<File>, val values: List<File>, val directories: Set<File>,
13
+ val sync: (File) -> Unit,
14
+ ) {
15
+ fun erase(files: List<File>) { for (file in files) Files.deleteIfExists(file.toPath()) }
16
+ fun durable() { for (directory in directories) sync(directory) }
17
+ }
18
+ private val portableKey = Regex("[A-Za-z0-9._/-]{1,200}")
19
+ private fun keyAt(base: File, directory: File): String? {
20
+ val parts = directory.relativeTo(base).invariantSeparatorsPath.split('/')
21
+ if (parts.any { it.isEmpty() || it.length > 100 } || parts.dropLast(1).any { it.length != 100 }) return null
22
+ return try {
23
+ val encoded = parts.joinToString("")
24
+ val bytes = Base64.getUrlDecoder().decode(encoded)
25
+ if (Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) != encoded) return null
26
+ StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString().takeIf { portableKey.matches(it) }
27
+ } catch (_: IllegalArgumentException) { null } catch (_: java.nio.charset.CharacterCodingException) { null }
28
+ }
29
+
30
+ /** Physical encoding only: one base64url key directory, never Core's namespace layout. */
31
+ internal fun planInstancePayloads(base: File, prefix: String, sync: (File) -> Unit): PayloadPurgePlan {
32
+ val temps = mutableListOf<File>(); val values = mutableListOf<File>(); val directories = linkedSetOf<File>()
33
+ val attributes = try {
34
+ // The area check alone follows a replaced backend-managed state/secrets ancestor.
35
+ val parent = Files.readAttributes(base.parentFile.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, NOFOLLOW_LINKS)
36
+ if (!parent.isDirectory) throw IOException("Invalid payload ancestor")
37
+ Files.readAttributes(base.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, NOFOLLOW_LINKS)
38
+ }
39
+ catch (_: java.nio.file.NoSuchFileException) { return PayloadPurgePlan(temps, values, directories, sync) }
40
+ if (!attributes.isDirectory) throw IOException("Invalid payload area")
41
+ Files.walk(base.toPath()).use { paths ->
42
+ paths.forEach { path ->
43
+ if (path == base.toPath()) return@forEach
44
+ val file = path.toFile()
45
+ if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
46
+ // Retained empty key directories allow a retry to acknowledge prior temp deletion.
47
+ if (keyAt(base, file)?.startsWith(prefix) == true) directories.add(file)
48
+ return@forEach
49
+ }
50
+ val key = keyAt(base, file.parentFile) ?: throw IOException("Undecodable payload path")
51
+ if (!key.startsWith(prefix)) return@forEach
52
+ if (!Files.isRegularFile(path, NOFOLLOW_LINKS)) throw IOException("Invalid selected payload")
53
+ directories.add(file.parentFile)
54
+ when {
55
+ file.name == "value" -> values.add(file)
56
+ file.name.startsWith("pending-") && file.name.endsWith(".tmp") -> temps.add(file)
57
+ else -> throw IOException("Unrecognized selected payload")
58
+ }
59
+ }
60
+ }
61
+ return PayloadPurgePlan(temps, values, directories, sync)
62
+ }
63
+
64
+ /** Erases every payload file of one instance, not log-floor pruning. Core owns exact lifetime custody. */
65
+ internal fun purgeInstanceFiles(
66
+ values: AtomicKeyFiles?, secrets: AtomicKeyFiles?, prefix: String,
67
+ deleteSecret: () -> Unit = {}, deleteState: () -> Unit = {},
68
+ ) {
69
+ require(portableKey.matches(prefix) && prefix.length > 1 && prefix.endsWith('/')) { "Invalid purge prefix" }
70
+ val ordinary = values?.instancePurgePlan(prefix)
71
+ val secret = secrets?.instancePurgePlan(prefix)
72
+ // Validate both local areas before a write. Durable temp erasure precedes canonical deletion.
73
+ ordinary?.let { it.erase(it.temporaries); it.durable() }
74
+ secret?.let { it.erase(it.temporaries); it.durable() }
75
+ deleteSecret()
76
+ secret?.let { it.erase(it.values); it.durable() }
77
+ deleteState()
78
+ ordinary?.let { it.erase(it.values); it.durable() }
79
+ }
@@ -0,0 +1,71 @@
1
+ package dev.croche.s7.pal
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonParser
5
+ import dev.croche.VersionedValue
6
+ import dev.croche.WriteOutcome
7
+ import dev.croche.s7.logicalStorageKey
8
+ import dev.croche.s7.storageVersion
9
+ import dev.croche.s7.versionedStorageKey
10
+ import java.io.IOException
11
+ import java.security.SecureRandom
12
+
13
+ /** Integral frames at K/.p1 through the same physical encoder and atomic writer. */
14
+ internal class VersionedKeyFiles(private val files: AtomicKeyFiles) {
15
+ private fun frame(key: String): String? =
16
+ if (Regex("[A-Za-z0-9._/-]{1,196}").matches(key) && !key.split('/').contains("secret-index")) "$key/.p1" else null
17
+ private fun snapshot(key: String): VersionedValue {
18
+ val encoded = frame(key)?.let { files.readRaw(it) }
19
+ if (encoded != null) {
20
+ val raw = JsonParser.parseString(encoded)
21
+ if (!raw.isJsonArray) throw IOException("Invalid versioned value frame")
22
+ val parts = raw.asJsonArray
23
+ if (parts.size() != 3 || !parts[0].isJsonPrimitive || !parts[0].asJsonPrimitive.isNumber || parts[0].asString != "1"
24
+ || !parts[1].isJsonPrimitive || !parts[1].asJsonPrimitive.isString || !Regex("[a-f0-9]{32}").matches(parts[1].asString)
25
+ || !parts[2].isJsonPrimitive || !parts[2].asJsonPrimitive.isString) throw IOException("Invalid versioned value frame")
26
+ return VersionedValue(parts[2].asString, parts[1].asString)
27
+ }
28
+ val value = files.readRaw(key)
29
+ return VersionedValue(value, if (value == null) null else "legacy")
30
+ }
31
+ private fun publish(key: String, value: String): String {
32
+ val token = ByteArray(16).also(random::nextBytes).joinToString("") { "%02x".format(it.toInt() and 255) }
33
+ val encoded = JsonArray().apply { add(1); add(token); add(value) }.toString()
34
+ files.writeRaw(frame(key) ?: throw IOException("Invalid versioned key"), encoded)
35
+ return token
36
+ }
37
+ private fun erase(key: String) {
38
+ // A partial failure leaves the authoritative frame, never stale raw bytes.
39
+ files.removeRaw(key); frame(key)?.let(files::removeRaw)
40
+ }
41
+ fun read(key: String): String? = snapshot(logicalStorageKey(key)).value
42
+ fun write(key: String, value: String) {
43
+ logicalStorageKey(key)
44
+ files.mutation(key) {
45
+ val current = snapshot(key)
46
+ if (current.version != null && current.version != "legacy") publish(key, value)
47
+ else files.writeRaw(key, value)
48
+ }
49
+ }
50
+ fun remove(key: String) { logicalStorageKey(key); files.mutation(key) { erase(key) } }
51
+ fun list(prefix: String): List<String> {
52
+ logicalStorageKey(prefix)
53
+ return files.listRaw(prefix).map { key ->
54
+ if (key.endsWith("/.p1")) versionedStorageKey(key.dropLast(4)) else logicalStorageKey(key)
55
+ }.filter { it.startsWith(prefix) }.distinct()
56
+ }
57
+ fun readVersioned(key: String): VersionedValue {
58
+ versionedStorageKey(key)
59
+ return files.mutation(key) { snapshot(key) }
60
+ }
61
+ fun writeIf(key: String, value: String?, expect: String?): WriteOutcome {
62
+ versionedStorageKey(key); storageVersion(expect)
63
+ return files.mutation(key) {
64
+ val current = snapshot(key)
65
+ if (current.version != expect) WriteOutcome.Conflict(current.version)
66
+ else if (value == null) { erase(key); WriteOutcome.Written(null) }
67
+ else WriteOutcome.Written(publish(key, value))
68
+ }
69
+ }
70
+ private companion object { val random = SecureRandom() }
71
+ }
@@ -22,6 +22,7 @@ Pod::Spec.new do |s|
22
22
  # compiled into one module; the bindings import the croche_ffiFFI C module.
23
23
  s.source_files = "ios/*.{h,m,mm,swift}", "ios/vendor/CrocheRuntimeSDK/**/*.swift"
24
24
  s.vendored_frameworks = "ios/vendor/croche_ffiFFI.xcframework"
25
+ s.libraries = "sqlite3"
25
26
  s.frameworks = "DeviceCheck", "Security"
26
27
 
27
28
  install_modules_dependencies(s)
@@ -1,3 +1,6 @@
1
1
  import type { CoreStoragePal, CoreModule } from '../../runtime/src/core/port';
2
+ import type { ImageAdapter } from '../../runtime/src/app-api';
2
3
  import type { NativeCoreWire } from './core-wire';
4
+ /** Default native encoded-image effects use the same owned cancel handles as Core. */
5
+ export declare function createNativeImageAdapter(wire: NativeCoreWire): ImageAdapter | undefined;
3
6
  export declare function createNativeCore(wire: NativeCoreWire, defaultStorage?: CoreStoragePal): CoreModule;