@tokamakdev/platform-android-arm64 0.1.1-beta.127 → 0.1.1-beta.129

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.
@@ -0,0 +1,291 @@
1
+ package com.tokamak.runtime
2
+
3
+ import kotlin.coroutines.cancellation.CancellationException
4
+ import kotlin.enums.EnumEntries
5
+ import kotlin.reflect.KClass
6
+ import kotlin.reflect.KFunction
7
+ import kotlinx.coroutines.CoroutineScope
8
+ import kotlinx.coroutines.CoroutineStart
9
+ import kotlinx.coroutines.Job
10
+ import kotlinx.coroutines.asCoroutineDispatcher
11
+ import kotlinx.coroutines.channels.BufferOverflow
12
+ import kotlinx.coroutines.flow.Flow
13
+ import kotlinx.coroutines.flow.MutableSharedFlow
14
+ import kotlinx.coroutines.flow.onSubscription
15
+ import kotlinx.coroutines.launch
16
+ import org.json.JSONArray
17
+ import org.json.JSONObject
18
+
19
+ /**
20
+ * The methods a plugin's `android/Exports.kt` lists for the Worker to call, and the events the Worker
21
+ * receives. `tok plugin generate android` runs [exports] to write the plugin's dispatch and
22
+ * TypeScript API; the app never does.
23
+ */
24
+ interface TokamakExports<P : TokamakPlugin> {
25
+ fun exports(e: TokamakExporter<P>)
26
+ }
27
+
28
+ /** What a stream does with values a slow reader has not taken. */
29
+ enum class TokamakOverflow {
30
+ /** Ends the stream with `QuotaExceededError`. */
31
+ ERROR,
32
+
33
+ /** Drops the oldest values, for samples where only recent ones matter. */
34
+ DROP_OLDEST,
35
+ }
36
+
37
+ /** Records the methods a plugin exports, with their options, and the events it emits. */
38
+ class TokamakExporter<P : TokamakPlugin> internal constructor() {
39
+ internal class Export(val kind: String, val method: KFunction<*>, val doc: String, val overflow: TokamakOverflow)
40
+
41
+ internal class Event(val name: String, val type: KClass<*>, val reply: KClass<*>?, val doc: String)
42
+
43
+ internal val exports = mutableListOf<Export>()
44
+ internal val events = mutableListOf<Event>()
45
+
46
+ /** Lists the event [name], whose listeners receive a [type] and may reply with a [reply]. */
47
+ fun event(name: String, type: KClass<*>, reply: KClass<*>? = null, doc: String = "") {
48
+ events += Event(name, type, reply, doc)
49
+ }
50
+
51
+ /** Exports [method], which returns once. */
52
+ fun call(method: KFunction<*>, doc: String = "") {
53
+ exports += Export("call", method, doc, TokamakOverflow.ERROR)
54
+ }
55
+
56
+ /** Exports [method], whose values the Worker reads until it cancels. */
57
+ fun stream(method: KFunction<Flow<*>>, overflow: TokamakOverflow = TokamakOverflow.ERROR, doc: String = "") {
58
+ exports += Export("stream", method, doc, overflow)
59
+ }
60
+
61
+ /** Exports [method], which returns a native object the Worker holds as a `NativeReference`. */
62
+ fun resource(method: KFunction<Any>, doc: String = "") {
63
+ exports += Export("resource", method, doc, TokamakOverflow.ERROR)
64
+ }
65
+ }
66
+
67
+ /** How many values listeners keep: those a slow reader has not taken, or those held for the first. */
68
+ private const val LISTENER_CAPACITY = 64
69
+
70
+ /**
71
+ * The flows of an event's listeners, such as a page's, each of which receives every value [send]
72
+ * delivers while it collects, keeping the newest 64 that a slow one has not taken. When [holding],
73
+ * the newest 64 values sent while none listen wait for the first listener.
74
+ */
75
+ class TokamakListeners<T>(private val holding: Boolean = false) {
76
+ private val values = MutableSharedFlow<T>(extraBufferCapacity = LISTENER_CAPACITY, onBufferOverflow = BufferOverflow.DROP_OLDEST)
77
+ private val held = mutableListOf<T>()
78
+
79
+ /** A new listener's flow. */
80
+ fun stream(): Flow<T> =
81
+ values.onSubscription {
82
+ synchronized(held) { held.toList().also { held.clear() } }.forEach { emit(it) }
83
+ }
84
+
85
+ fun send(value: T) {
86
+ synchronized(held) {
87
+ if (holding && values.subscriptionCount.value == 0) {
88
+ held += value
89
+ if (held.size > LISTENER_CAPACITY) held.removeAt(0)
90
+ return
91
+ }
92
+ }
93
+ values.tryEmit(value)
94
+ }
95
+ }
96
+
97
+ /** A native object another plugin retained, which the Worker passes as a `NativeReference`. */
98
+ class TokamakReference<T : Any>(val value: T)
99
+
100
+ /**
101
+ * Names the [field] that tags the forms of a sealed type the Worker passes: each form is an object
102
+ * whose [field] is the form's name, with a data class form's fields.
103
+ */
104
+ @Target(AnnotationTarget.CLASS)
105
+ annotation class TokamakTag(val field: String)
106
+
107
+ /** A JSON value in a call's arguments, at [path], which errors name. */
108
+ class TokamakValue(private val json: Any?, private val path: String) {
109
+ /** The field [key] of this object. */
110
+ operator fun get(key: String): TokamakValue {
111
+ val json = json as? JSONObject ?: throw invalid("an object")
112
+ return TokamakValue(json.opt(key), if (path.isEmpty()) key else "$path.$key")
113
+ }
114
+
115
+ fun string(): String = json as? String ?: throw invalid("a string")
116
+
117
+ fun boolean(): Boolean = json as? Boolean ?: throw invalid("a boolean")
118
+
119
+ fun double(): Double = (json as? Number)?.toDouble() ?: throw invalid("a number")
120
+
121
+ fun float(): Float = double().toFloat()
122
+
123
+ /** The whole number, which JSON from JavaScript carries exactly up to 2^53. */
124
+ fun long(): Long {
125
+ val number = json as? Number ?: throw invalid("a number")
126
+ if (number is Long || number is Int) return number.toLong()
127
+ // A Double from 2^63 up converts to Long.MAX_VALUE.
128
+ val double = number.toDouble()
129
+ if (double % 1.0 != 0.0) throw invalid("a whole number")
130
+ if (double < Long.MIN_VALUE.toDouble() || double >= -Long.MIN_VALUE.toDouble()) throw invalid("a Long")
131
+ return double.toLong()
132
+ }
133
+
134
+ fun int(): Int = long().takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.toInt() ?: throw invalid("an Int")
135
+
136
+ fun short(): Short = long().takeIf { it in Short.MIN_VALUE..Short.MAX_VALUE }?.toShort() ?: throw invalid("a Short")
137
+
138
+ fun byte(): Byte = long().takeIf { it in Byte.MIN_VALUE..Byte.MAX_VALUE }?.toByte() ?: throw invalid("a Byte")
139
+
140
+ /** Any JSON value, as org.json reads it, with null for JSON null. */
141
+ fun json(): Any? = json.takeUnless { it == JSONObject.NULL }
142
+
143
+ /** A JSON value other than null, as org.json reads it. */
144
+ fun any(): Any = json() ?: throw invalid("a value other than null")
145
+
146
+ fun jsonObject(): JSONObject = json as? JSONObject ?: throw invalid("an object")
147
+
148
+ fun jsonArray(): JSONArray = json as? JSONArray ?: throw invalid("an array")
149
+
150
+ /** Null for JSON null or a missing field, and otherwise what [read] reads. */
151
+ fun <T> nullable(read: (TokamakValue) -> T): T? = if (json == null || json == JSONObject.NULL) null else read(this)
152
+
153
+ fun <T> list(read: (TokamakValue) -> T): List<T> {
154
+ val array = json as? JSONArray ?: throw invalid("an array")
155
+ return List(array.length()) { read(TokamakValue(array.opt(it), "$path[$it]")) }
156
+ }
157
+
158
+ fun <T> map(read: (TokamakValue) -> T): Map<String, T> {
159
+ val json = json as? JSONObject ?: throw invalid("an object")
160
+ return json.keys().asSequence().associateWith { read(get(it)) }
161
+ }
162
+
163
+ fun <E : Enum<E>> enum(entries: EnumEntries<E>): E {
164
+ val name = string()
165
+ return entries.firstOrNull { it.name == name } ?: throw invalid("one of ${entries.joinToString()}")
166
+ }
167
+
168
+ /** The error of a value that is none of the forms of the sealed type [name]. */
169
+ fun mismatch(name: String): TokamakPluginError = invalid("one of $name's forms")
170
+
171
+ /** The object of type [type] that [resources] retains as this ID. */
172
+ fun <T : Any> reference(resources: TokamakResources, type: Class<T>): TokamakReference<T> =
173
+ TokamakReference(resources.get(string(), type))
174
+
175
+ private fun invalid(expected: String) = TokamakPluginError.typeError("${path.ifEmpty { "arguments" }} must be $expected")
176
+
177
+ companion object {
178
+ /** A call's arguments: a JSON object of them by parameter name. */
179
+ fun arguments(payload: ByteArray): TokamakValue =
180
+ TokamakValue(runCatching { decodePluginValue(payload) }.getOrNull(), "")
181
+ }
182
+ }
183
+
184
+ /**
185
+ * A plugin with the dispatch generated from its `android/Exports.kt`. The app's registry creates the
186
+ * generated subclass in place of [plugin], which plugins find with `tokamakPlugin(id)`.
187
+ */
188
+ abstract class TokamakDispatch<P : TokamakPlugin>(val plugin: P, protected val host: TokamakHost) : TokamakPlugin by plugin {
189
+ /** [event] as the JSON payload of the event [name], which `android/Exports.kt` lists. */
190
+ open fun eventPayload(name: String, event: Any): ByteArray = throw TokamakPluginError.unlistedEvent(name)
191
+
192
+ /** The listeners' [reply] to the event [name], which `android/Exports.kt` lists with a reply, as its type. */
193
+ open fun eventReply(name: String, reply: TokamakValue): Any = throw TokamakPluginError.unlistedReply(name)
194
+
195
+ /** [value], of a data class or sealed type the plugin's methods and events use, as the JSON org.json writes. */
196
+ open fun encodeValue(value: Any): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${value.javaClass.simpleName}")
197
+
198
+ /** [json] as a data class or sealed [type] the plugin's methods and events use. */
199
+ open fun decodeValue(json: TokamakValue, type: KClass<*>): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${type.simpleName}")
200
+
201
+ /** The JSON [json], as org.json reads it, as a [type], which [decodeValue] decodes. */
202
+ fun <T : Any> fromJson(json: Any?, type: KClass<T>): T {
203
+ val value = decodeValue(TokamakValue(json, "json"), type)
204
+ return type.castOrNull(value) ?: throw TokamakPluginError.typeError("json is ${value.javaClass.simpleName}, not ${type.simpleName}")
205
+ }
206
+
207
+ /** Delivers [event] to the Worker's listeners of the event [name], returning their encoded reply. */
208
+ fun emit(name: String, event: Any, timeoutMillis: Long): ByteArray = host.emitBytes(name, eventPayload(name, event), timeoutMillis)
209
+
210
+ /** [emit] returning the listeners' reply as a [reply], or null when none replied. */
211
+ fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R? {
212
+ val payload = emit(name, event, timeoutMillis)
213
+ if (payload.isEmpty()) return null
214
+ val json = decodePluginValue(payload).takeUnless { it == JSONObject.NULL } ?: return null
215
+ val value = eventReply(name, TokamakValue(json, "reply"))
216
+ return reply.castOrNull(value)
217
+ ?: throw TokamakPluginError.typeError("event $name replies with ${value.javaClass.simpleName}, not ${reply.simpleName}")
218
+ }
219
+
220
+ /** [event] as the payload of the event [name], whose listeners receive a [type] as [encode] encodes it. */
221
+ protected fun <T : Any> encodeEvent(name: String, event: Any, type: KClass<T>, encode: (T) -> Any?): ByteArray {
222
+ val value = type.castOrNull(event)
223
+ ?: throw TokamakPluginError.typeError("event $name takes ${type.simpleName}, not ${event.javaClass.simpleName}")
224
+ return encodePluginValue(encode(value))
225
+ }
226
+
227
+ /** Replies with what [method] returns, on the call's executor, with nothing to cancel. */
228
+ protected fun respond(reply: TokamakPluginBytesReply, method: () -> Any?): (() -> Unit)? {
229
+ reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(method().unlessUnit()) }, true))
230
+ return null
231
+ }
232
+
233
+ /**
234
+ * Runs the suspending [block] in a coroutine on the executor of [method], replying with what it
235
+ * returns. Cancelling the call cancels the coroutine.
236
+ */
237
+ protected fun launch(method: String, reply: TokamakPluginBytesReply, block: suspend () -> Any?): () -> Unit =
238
+ start(method) {
239
+ reply(TokamakPluginResult.encoded(catching { encodePluginValue(block().unlessUnit()) }, true))
240
+ }
241
+
242
+ /** Replies with each of [values], encoded by [encode], until they end or the Worker cancels. */
243
+ protected fun <T> collect(method: String, reply: TokamakPluginBytesReply, values: Flow<T>, encode: (T) -> Any? = { it }): () -> Unit =
244
+ start(method) {
245
+ val ended = catching { values.collect { reply(TokamakPluginResult(encodePluginValue(encode(it)), false, false)) } }
246
+ reply(TokamakPluginResult.encoded(ended.map { ByteArray(0) }, true))
247
+ }
248
+
249
+ /** Retains [value], replying with its ID, until the subscription ends. */
250
+ protected fun retain(reply: TokamakPluginBytesReply, value: Any): () -> Unit =
251
+ host.resources.retain(value) { reply(TokamakPluginResult.encoded(it.mapCatching(::encodePluginValue), false)) }
252
+
253
+ /** Retains what the suspending [block] returns, replying with its ID, until the subscription ends. */
254
+ protected fun retain(method: String, reply: TokamakPluginBytesReply, block: suspend () -> Any): () -> Unit {
255
+ // The coroutine and its cancellation run on the method's serial executor.
256
+ var release: (() -> Unit)? = null
257
+ var cancelled = false
258
+ val cancel = start(method) {
259
+ catching { block() }.fold(
260
+ // A method that returns after cancellation, ignoring it, leaves nothing to retain.
261
+ { value -> if (!cancelled) release = retain(reply, value) },
262
+ { reply(TokamakPluginResult.encoded(Result.failure(it), true)) },
263
+ )
264
+ }
265
+ return {
266
+ cancelled = true
267
+ cancel()
268
+ release?.invoke()
269
+ }
270
+ }
271
+
272
+ private fun start(method: String, block: suspend () -> Unit): () -> Unit {
273
+ val job: Job = CoroutineScope(executor(method).asCoroutineDispatcher()).launch(start = CoroutineStart.UNDISPATCHED) { block() }
274
+ return { job.cancel() }
275
+ }
276
+ }
277
+
278
+ private fun Any?.unlessUnit(): Any? = takeUnless { it == Unit }
279
+
280
+ /** [value] as a [T], or null when it is of another type. */
281
+ private fun <T : Any> KClass<T>.castOrNull(value: Any): T? = javaObjectType.takeIf { it.isInstance(value) }?.cast(value)
282
+
283
+ /** What [block] returns or throws, except cancellation, which ends the coroutine. */
284
+ private suspend fun <T> catching(block: suspend () -> T): Result<T> =
285
+ try {
286
+ Result.success(block())
287
+ } catch (error: CancellationException) {
288
+ throw error
289
+ } catch (error: Throwable) {
290
+ Result.failure(error)
291
+ }
@@ -6,6 +6,7 @@ import android.content.Intent
6
6
  import android.os.Handler
7
7
  import android.os.Looper
8
8
  import java.util.concurrent.Executor
9
+ import kotlin.reflect.KClass
9
10
  import org.json.JSONArray
10
11
  import org.json.JSONObject
11
12
  import org.json.JSONTokener
@@ -27,6 +28,12 @@ class TokamakPluginError(
27
28
 
28
29
  /** UI was needed while the app is in the background, where it cannot show any. */
29
30
  fun needsUI() = TokamakPluginError("NeedsUIError", "The app cannot show UI while it is in the background")
31
+
32
+ /** The plugin emitted an event its registration does not list. */
33
+ fun unlistedEvent(name: String) = typeError("android/Exports.kt lists no event $name")
34
+
35
+ /** The plugin asked for the reply to an event its registration lists without one. */
36
+ fun unlistedReply(name: String) = typeError("android/Exports.kt lists no reply to event $name")
30
37
  }
31
38
  }
32
39
 
@@ -199,18 +206,35 @@ interface TokamakHost {
199
206
 
200
207
  /**
201
208
  * Delivers the plugin's event [name], which the Worker's listeners receive as
202
- * `<plugin>.<name>`, with its encoded [payload], and returns their encoded reply, which is
203
- * empty when none replied. Starts the runtime when it is not running. Blocks, so call it off
209
+ * `<plugin>.android.<name>`, with its encoded [payload], and returns their encoded reply, which
210
+ * is empty when none replied. Starts the runtime when it is not running. Blocks, so call it off
204
211
  * the main thread; throws unless the listeners return within [timeoutMillis], which includes
205
212
  * runtime startup.
206
213
  */
207
214
  fun emitBytes(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray
208
215
 
209
- /** [emitBytes] with [event] encoded as JSON, returning their reply decoded from JSON, or null when none replied. */
210
- fun emit(name: String, event: Any?, timeoutMillis: Long): Any? {
211
- val reply = emitBytes(name, encodePluginValue(event), timeoutMillis)
212
- return if (reply.isEmpty()) null else decodePluginValue(reply).takeUnless { it == JSONObject.NULL }
213
- }
216
+ /**
217
+ * Delivers [event] to the Worker's listeners of the plugin's event [name], which
218
+ * `android/Exports.kt` lists. Starts the runtime when it is not running. Blocks, so call it off
219
+ * the main thread; throws unless the listeners return within [timeoutMillis], which includes
220
+ * runtime startup.
221
+ */
222
+ fun emit(name: String, event: Any, timeoutMillis: Long)
223
+
224
+ /** [emit] of an event whose listeners may reply, returning the reply, or null when none replied. */
225
+ fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R?
226
+
227
+ /**
228
+ * [value], of a data class or sealed type `android/Exports.kt`'s methods and events use, as
229
+ * the JSON the Worker receives, which org.json writes, for a value the plugin stores.
230
+ */
231
+ fun json(value: Any): Any
232
+
233
+ /**
234
+ * The JSON [json], as org.json reads it, as a data class or sealed [type] `android/Exports.kt`'s
235
+ * methods and events use, for a value the plugin stored with [json].
236
+ */
237
+ fun <T : Any> fromJson(json: Any?, type: KClass<T>): T
214
238
 
215
239
  /**
216
240
  * What the app serves at [path], as its WebView would load it: a file the app ships or the
@@ -2,50 +2,21 @@ package com.tokamak.runtime
2
2
 
3
3
  import java.util.UUID
4
4
 
5
- /** Native objects that plugins share by ID. Each belongs to a scope and is kept until it is released or its scope ends. */
5
+ /** Native objects that plugins share by ID. Each is kept until the subscription that retained it ends. */
6
6
  class TokamakResources {
7
- private val objects = HashMap<String, Pair<Any, String>>()
8
- private val scopes = HashMap<String, MutableSet<String>>()
7
+ private val objects = HashMap<String, Any>()
9
8
 
10
- /** Starts a scope and returns its ID. */
11
- fun open(): String {
12
- val scope = UUID.randomUUID().toString()
13
- synchronized(this) { scopes[scope] = HashSet() }
14
- return scope
15
- }
16
-
17
- /** Keeps [value] in [scope] and returns its ID. An ended scope keeps nothing, so the ID finds no object. */
18
- fun retain(value: Any, scope: String): String {
19
- val id = UUID.randomUUID().toString()
20
- synchronized(this) {
21
- if (scopes[scope]?.add(id) == true) objects[id] = value to scope
22
- }
23
- return id
24
- }
25
-
26
- /** Keeps [value] in a scope of its own, replies with its ID, and returns the release to return from `subscribe`. */
9
+ /** Keeps [value], replies with its ID, and returns the release to return from `subscribe`. */
27
10
  fun retain(value: Any, reply: TokamakPluginReply): () -> Unit {
28
- val scope = open()
29
- reply(Result.success(retain(value, scope)))
30
- return { end(scope) }
31
- }
32
-
33
- /** Releases the object retained as [id], if it is still kept. */
34
- fun release(id: Any?) {
35
- synchronized(this) {
36
- val (_, scope) = objects.remove(id as? String) ?: return
37
- scopes[scope]?.remove(id)
38
- }
39
- }
40
-
41
- /** Releases every object [scope] keeps, and keeps nothing in it later. */
42
- fun end(scope: String) {
43
- synchronized(this) { scopes.remove(scope)?.forEach { objects.remove(it) } }
11
+ val id = UUID.randomUUID().toString()
12
+ synchronized(this) { objects[id] = value }
13
+ reply(Result.success(id))
14
+ return { synchronized(this) { objects.remove(id) } }
44
15
  }
45
16
 
46
17
  /** The object retained as [id]. */
47
18
  fun <T : Any> get(id: Any?, type: Class<T>): T {
48
- val value = synchronized(this) { objects[id as? String]?.first }
19
+ val value = synchronized(this) { objects[id as? String] }
49
20
  ?: throw TokamakPluginError("InvalidStateError", "The native reference is closed")
50
21
  if (!type.isInstance(value)) throw TokamakPluginError.typeError("The native reference is not ${type.simpleName}")
51
22
  return type.cast(value)!!
@@ -24,11 +24,9 @@
24
24
  }
25
25
  },
26
26
  "pluginKeys": {
27
- "bindings": "paths",
28
27
  "class": "string",
29
28
  "dependencies": "strings",
30
29
  "manifest": "path",
31
- "raw": "paths",
32
- "sources": "paths"
30
+ "raw": "paths"
33
31
  }
34
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.127",
3
+ "version": "0.1.1-beta.129",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,172 +0,0 @@
1
- package com.tokamak.runtime
2
-
3
- import java.util.Base64
4
- import org.json.JSONArray
5
- import org.json.JSONObject
6
-
7
- /**
8
- * One call or subscription of a generated platform binding. It decodes the Worker's JSON into
9
- * native values and encodes native values back, keeping the native objects it returns in the
10
- * receiving invocation's scope.
11
- *
12
- * JSON objects tagged `#` carry what JSON lacks: native objects, bytes, errors, non-finite
13
- * numbers, and records whose keys include `#`.
14
- */
15
- class TokamakBinding(payload: ByteArray, private val resources: TokamakResources, private val reply: TokamakPluginBytesReply) {
16
- companion object {
17
- /** The rejection of a member the running API level lacks. */
18
- val unavailable get() = TokamakPluginError.notSupported("The API is unavailable on this API level")
19
- }
20
-
21
- private val request = decodePluginValue(payload) as? JSONObject
22
- ?: throw TokamakPluginError.typeError("A binding request is an object")
23
-
24
- /** Argument [index] as JSON. */
25
- operator fun get(index: Int): Any? = request.optJSONArray("arguments")?.opt(index) ?: JSONObject.NULL
26
-
27
- /** The object the call is made on. */
28
- fun <T : Any> target(type: Class<T>): T = obj(request.opt("target"), type)
29
-
30
- /** The handlers an implementation calls. */
31
- val methods: Set<String> by lazy {
32
- val methods = request.optJSONArray("methods") ?: return@lazy emptySet()
33
- (0 until methods.length()).map(methods::getString).toSet()
34
- }
35
-
36
- private val scope: String get() = request.optString("scope")
37
-
38
- fun boolean(value: Any?): Boolean = value as? Boolean ?: throw mismatch(value, "boolean")
39
-
40
- fun byte(value: Any?): Byte = long(value).let { if (it in Byte.MIN_VALUE..Byte.MAX_VALUE) it.toByte() else throw mismatch(value, "byte") }
41
-
42
- fun short(value: Any?): Short = long(value).let { if (it in Short.MIN_VALUE..Short.MAX_VALUE) it.toShort() else throw mismatch(value, "short") }
43
-
44
- fun int(value: Any?): Int = long(value).let { if (it in Int.MIN_VALUE..Int.MAX_VALUE) it.toInt() else throw mismatch(value, "int") }
45
-
46
- fun long(value: Any?): Long {
47
- val number = double(value)
48
- val integer = number.toLong()
49
- if (integer.toDouble() != number) throw mismatch(value, "long")
50
- return integer
51
- }
52
-
53
- fun float(value: Any?): Float = double(value).toFloat()
54
-
55
- fun double(value: Any?): Double =
56
- (value as? Number)?.toDouble() ?: string(tagged(value, "number")).toDoubleOrNull() ?: throw mismatch(value, "double")
57
-
58
- fun char(value: Any?): Char = string(value).singleOrNull() ?: throw mismatch(value, "char")
59
-
60
- fun string(value: Any?): String = value as? String ?: throw mismatch(value, "String")
61
-
62
- fun bytes(value: Any?): ByteArray = Base64.getDecoder().decode(string(tagged(value, "bytes")))
63
-
64
- /** The native object [value] refers to. */
65
- fun <T : Any> obj(value: Any?, type: Class<T>): T = resources.get(tagged(value, "object", "id"), type)
66
-
67
- /** A value of an erased or `Object` type: JSON as it is, or the native value a tag carries. */
68
- fun any(value: Any?): Any? =
69
- when (value) {
70
- null, JSONObject.NULL -> null
71
- is JSONArray -> list(value, ::any)
72
- is JSONObject ->
73
- when (value.optString("#")) {
74
- "object" -> obj(value, Any::class.java)
75
- "bytes" -> bytes(value)
76
- "number" -> double(value)
77
- else -> map(value, ::any)
78
- }
79
- else -> value
80
- }
81
-
82
- fun <T> optional(value: Any?, decode: (Any?) -> T): T? = if (value == null || value == JSONObject.NULL) null else decode(value)
83
-
84
- fun <T> list(value: Any?, decode: (Any?) -> T): List<T> {
85
- val values = value as? JSONArray ?: throw mismatch(value, "List")
86
- return (0 until values.length()).map { decode(values.get(it)) }
87
- }
88
-
89
- fun <T> map(value: Any?, decode: (Any?) -> T): Map<String, T> {
90
- val fields = (value as? JSONObject)?.let { if (it.optString("#") == "record") it.getJSONObject("value") else it }
91
- ?: throw mismatch(value, "Map")
92
- return fields.keys().asSequence().associateWith { decode(fields.get(it)) }
93
- }
94
-
95
- /**
96
- * [value] as JSON: values by their runtime type, and native objects as references kept in the
97
- * invocation's scope, with the names of their class and superclasses.
98
- */
99
- fun encode(value: Any?): Any =
100
- when (value) {
101
- null -> JSONObject.NULL
102
- is Boolean, is String, is Int, is Long, is Short, is Byte -> value
103
- is Double -> if (value.isFinite()) value else JSONObject().put("#", "number").put("value", value.toString())
104
- is Float -> encode(value.toDouble())
105
- is Char, is CharSequence -> value.toString()
106
- is ByteArray -> JSONObject().put("#", "bytes").put("value", Base64.getEncoder().encodeToString(value))
107
- is IntArray -> JSONArray(value.map(::encode))
108
- is LongArray -> JSONArray(value.map(::encode))
109
- is FloatArray -> JSONArray(value.map(::encode))
110
- is DoubleArray -> JSONArray(value.map(::encode))
111
- is BooleanArray -> JSONArray(value.map(::encode))
112
- is Array<*> -> JSONArray(value.map(::encode))
113
- is Iterable<*> -> JSONArray(value.map(::encode))
114
- is Map<*, *> -> record(value)
115
- is Enum<*> -> value.name
116
- is Throwable -> error(value)
117
- else -> JSONObject().put("#", "object").put("id", resources.retain(value, scope)).put("types", JSONArray(types(value)))
118
- }
119
-
120
- /** Replies with the JSON [body] returns, or the exception it throws. */
121
- fun run(body: () -> Any?): (() -> Unit)? {
122
- reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(body()) }, true))
123
- return null
124
- }
125
-
126
- /** Keeps the implementation [create] makes while the subscription lasts, and replies with its ID. */
127
- fun implement(create: (TokamakBinding) -> Any): () -> Unit {
128
- val scope = resources.open()
129
- send(resources.retain(create(this), scope))
130
- return { resources.end(scope) }
131
- }
132
-
133
- /**
134
- * Calls the handler [method], when the implementation has one, with the arguments it encodes,
135
- * and returns whether it had one.
136
- */
137
- fun call(method: String, arguments: (TokamakBinding) -> List<Any?>): Boolean {
138
- if (method !in methods) return false
139
- send(JSONObject().put("method", method).put("arguments", JSONArray(arguments(this))))
140
- return true
141
- }
142
-
143
- private fun send(value: Any?) {
144
- reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(value) }, false))
145
- }
146
-
147
- private fun record(fields: Map<*, *>): JSONObject {
148
- val encoded = JSONObject()
149
- fields.forEach { (key, value) -> encoded.put(key.toString(), encode(value)) }
150
- return if (encoded.has("#")) JSONObject().put("#", "record").put("value", encoded) else encoded
151
- }
152
-
153
- private fun error(error: Throwable): JSONObject = failure(error).put("#", "error")
154
-
155
- /** The field [key] of [value] tagged [tag]. */
156
- private fun tagged(value: Any?, tag: String, key: String = "value"): Any? {
157
- val fields = value as? JSONObject
158
- if (fields?.optString("#") != tag || !fields.has(key)) throw TokamakPluginError.typeError("Expected a tagged $tag")
159
- return fields.get(key)
160
- }
161
-
162
- private fun mismatch(value: Any?, type: String) = TokamakPluginError.typeError("${value?.javaClass?.simpleName} is not $type")
163
-
164
- /** The names of [value]'s class and superclasses, then of the interfaces they implement. */
165
- private fun types(value: Any): List<String> {
166
- val classes = generateSequence<Class<*>>(value.javaClass) { it.superclass }.toList()
167
- return (classes + classes.flatMap(::interfaces)).distinct().map { it.name }
168
- }
169
-
170
- /** The interfaces [type] implements, each followed by those it extends. */
171
- private fun interfaces(type: Class<*>): List<Class<*>> = type.interfaces.flatMap { listOf(it) + interfaces(it) }
172
- }
@@ -1,23 +0,0 @@
1
- package com.tokamak.runtime
2
-
3
- import org.json.JSONObject
4
-
5
- /** [arguments] as an object; throws a `TypeError` otherwise. */
6
- fun requireObject(arguments: Any?): JSONObject =
7
- arguments as? JSONObject ?: throw TokamakPluginError.typeError("arguments must be an object")
8
-
9
- /** The string [name]; throws a `TypeError` otherwise. */
10
- fun JSONObject.requireString(name: String): String =
11
- optionalString(name) ?: throw TokamakPluginError.typeError("$name must be a string")
12
-
13
- /** The string [name], or null when it is absent or null; throws a `TypeError` otherwise. */
14
- fun JSONObject.optionalString(name: String): String? =
15
- when (val value = opt(name)) {
16
- null, JSONObject.NULL -> null
17
- is String -> value
18
- else -> throw TokamakPluginError.typeError("$name must be a string")
19
- }
20
-
21
- /** The boolean [name]; throws a `TypeError` otherwise. */
22
- fun JSONObject.requireBoolean(name: String): Boolean =
23
- opt(name) as? Boolean ?: throw TokamakPluginError.typeError("$name must be a boolean")