orvyn-lang 0.2.0 → 0.3.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 (55) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +744 -27
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +186 -10
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +428 -57
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +518 -44
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +266 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -34
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +406 -56
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +792 -10
  39. package/src/lang/runtime.js +362 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/vite-plugin.js +82 -3
  48. package/src/lang/web-overlay.js +578 -0
  49. package/src/lang/widgets.js +94 -0
  50. package/src/lang/words.js +38 -0
  51. package/src/runtime/mount.js +116 -27
  52. package/src/runtime/patch.js +90 -11
  53. package/src/runtime/style.js +11 -1
  54. package/src/styling/fluid.js +91 -4
  55. package/src/styling/spec.js +306 -0
package/src/lang/form.js CHANGED
@@ -1,6 +1,7 @@
1
- import { signal } from "../core/signal.js";
1
+ import { onCleanup, signal } from "../core/signal.js";
2
2
  import { createVNode } from "../runtime/vnode.js";
3
3
  import { validate } from "./validation.js";
4
+ import { currentComponentInstance, errorText } from "./runtime-shared.js";
4
5
  const RULE_KEYS = ["required", "minLength", "maxLength", "email", "label", "message"];
5
6
  const stateIds = /* @__PURE__ */ new WeakMap();
6
7
  let nextId = 0;
@@ -12,7 +13,7 @@ function createForm(cache, slot, props, children) {
12
13
  const collect = (value, path) => {
13
14
  if (Array.isArray(value)) return value.forEach((child, i) => collect(child, `${path}.${i}`));
14
15
  if (!value || typeof value !== "object" || !value.tag || value.tag === "form") return;
15
- if (value.tag === "input") {
16
+ if (value.tag === "input" || value.tag === "textarea" || value.tag === "select") {
16
17
  const rules2 = {};
17
18
  for (const key2 of RULE_KEYS) if (value.props[key2] !== void 0) rules2[key2] = value.props[key2];
18
19
  if (value.props.type === "email") rules2.email = true;
@@ -33,13 +34,37 @@ function createForm(cache, slot, props, children) {
33
34
  if (!stateIds.has(binding.state)) stateIds.set(binding.state, ++nextId);
34
35
  return [stateIds.get(binding.state), binding.key, binding.indexed];
35
36
  });
36
- const key = JSON.stringify([slot, props.key ?? identity]);
37
+ const key = JSON.stringify([currentComponentInstance(), slot, props.key ?? identity]);
37
38
  let errors = cache.get(key);
38
39
  if (!errors) {
39
- errors = { errors: signal({}), attempted: false, id: ++nextId };
40
+ errors = {
41
+ errors: signal({}),
42
+ pending: signal(false),
43
+ submitError: signal(""),
44
+ attempted: false,
45
+ disposed: false,
46
+ id: ++nextId,
47
+ users: 0
48
+ };
40
49
  cache.set(key, errors);
41
50
  }
51
+ const entry = errors;
52
+ entry.users++;
53
+ onCleanup(() => {
54
+ entry.users--;
55
+ queueMicrotask(() => {
56
+ if (entry.users === 0 && cache.get(key) === entry) {
57
+ entry.disposed = true;
58
+ cache.delete(key);
59
+ entry.errors.dispose();
60
+ entry.pending.dispose();
61
+ entry.submitError.dispose();
62
+ }
63
+ });
64
+ });
42
65
  const currentErrors = errors.errors.get();
66
+ const isPending = errors.pending.get();
67
+ const submitError = errors.submitError.get();
43
68
  const byPath = new Map(fields.map((field) => [field.id, field]));
44
69
  const values = () => Object.fromEntries(fields.map((field) => [
45
70
  field.id,
@@ -55,6 +80,7 @@ function createForm(cache, slot, props, children) {
55
80
  const inputProps = { ...value.props };
56
81
  for (const key2 of RULE_KEYS) delete inputProps[key2];
57
82
  inputProps["aria-invalid"] = !!currentErrors[field.id];
83
+ if (currentErrors[field.id]) inputProps.error = currentErrors[field.id];
58
84
  inputProps["aria-required"] = !!field.rules.required;
59
85
  inputProps["aria-label"] ??= field.rules.label;
60
86
  const errorId = `orvyn-form-${errors.id}-${field.id}-error`;
@@ -75,23 +101,58 @@ function createForm(cache, slot, props, children) {
75
101
  return result;
76
102
  };
77
103
  return createVNode("div", { key: value.props.key ?? path, flex: true, direction: "column", gap: 4 }, [
78
- createVNode("input", inputProps, value.children),
104
+ createVNode(value.tag, inputProps, value.children),
79
105
  createVNode("span", { id: errorId, color: "red", role: "alert" }, [currentErrors[field.id] ?? ""])
80
106
  ]);
81
107
  }
108
+ if (value.tag === "button" && value.props.type === "submit" && value.props.loading === void 0) {
109
+ return createVNode(value.tag, { ...value.props, loading: isPending }, decorate(value.children, `${path}.c`));
110
+ }
82
111
  return createVNode(value.tag, value.props, decorate(value.children, `${path}.c`));
83
112
  };
113
+ const { onError, ...formProps } = props;
114
+ const decorated = decorate(children, "field");
115
+ const formChildren = submitError ? [...decorated, createVNode("span", { key: `orvyn-form-err-${errors.id}`, color: "red", role: "alert" }, [submitError])] : decorated;
84
116
  return createVNode("form", {
85
- ...props,
117
+ ...formProps,
86
118
  noValidate: true,
87
119
  onSubmit: (event) => {
88
120
  event?.preventDefault?.();
121
+ if (entry.pending.get()) return;
89
122
  const result = validate(values(), rules);
90
123
  errors.attempted = true;
91
124
  errors.errors.set(result.errors);
92
- if (result.valid) return props.onSubmit();
125
+ if (!result.valid) return;
126
+ entry.submitError.set("");
127
+ try {
128
+ const outcome = props.onSubmit();
129
+ if (outcome && typeof outcome.then === "function") {
130
+ entry.pending.set(true);
131
+ return Promise.resolve(outcome).then(
132
+ (value) => {
133
+ if (!entry.disposed) entry.pending.set(false);
134
+ return value;
135
+ },
136
+ (error) => {
137
+ if (!entry.disposed) {
138
+ entry.pending.set(false);
139
+ const message = errorText(error);
140
+ entry.submitError.set(message);
141
+ onError?.(message);
142
+ }
143
+ }
144
+ );
145
+ }
146
+ return outcome;
147
+ } catch (error) {
148
+ if (!entry.disposed) {
149
+ const message = errorText(error);
150
+ entry.submitError.set(message);
151
+ onError?.(message);
152
+ }
153
+ }
93
154
  }
94
- }, decorate(children, "field"));
155
+ }, formChildren);
95
156
  }
96
157
  export {
97
158
  createForm,
package/src/lang/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { parse } from "./parser.js";
2
2
  import { generate } from "./codegen.js";
3
+ import { checkTypes } from "./types.js";
3
4
  import { tokenize, OrvynSyntaxError } from "./lexer.js";
4
5
  import { parse as parse2 } from "./parser.js";
5
6
  function compile(source, options = {}) {
6
- return generate(parse(source), options);
7
+ return generate(checkTypes(parse(source), options.resolveImport), options);
7
8
  }
8
9
  export {
9
10
  OrvynSyntaxError,
package/src/lang/lexer.js CHANGED
@@ -13,6 +13,8 @@ const KEYWORDS = /* @__PURE__ */ new Set([
13
13
  "use",
14
14
  "from",
15
15
  "start",
16
+ "try",
17
+ "catch",
16
18
  "true",
17
19
  "false",
18
20
  "null"
@@ -0,0 +1,44 @@
1
+ import { createVNode } from "../runtime/vnode.js";
2
+ import { componentState } from "./runtime-shared.js";
3
+ const OVERSCAN = 5;
4
+ function createList(windowed) {
5
+ return function List(props) {
6
+ const { items, row, rowHeight = 48, height = 480, keyOf, children: _children, ...style } = props;
7
+ const all = Array.from(items ?? []);
8
+ const make = (item, index) => createVNode("div", {
9
+ key: keyOf ? `k:${keyOf(item)}` : `i:${index}`,
10
+ flex: true,
11
+ direction: "column",
12
+ justify: "center",
13
+ height: rowHeight,
14
+ shrink: 0,
15
+ overflow: "hidden"
16
+ }, row(item));
17
+ if (!windowed) {
18
+ return [createVNode("div", { ...style, height, nativeRole: "list", rowHeight }, all.map(make))];
19
+ }
20
+ const scroll = componentState()(0, () => 0);
21
+ const visible = Math.ceil(Number(height) / rowHeight) || 20;
22
+ const first = Math.max(0, Math.min(Math.floor(scroll.get() / rowHeight) - OVERSCAN, all.length - visible));
23
+ const end = Math.min(all.length, first + visible + OVERSCAN * 2);
24
+ const spacer = (key, rows) => createVNode("div", { key, height: rows * rowHeight, shrink: 0 }, []);
25
+ return [createVNode("div", {
26
+ ...style,
27
+ height,
28
+ overflowY: "auto",
29
+ role: "list",
30
+ onScroll: (event) => scroll.set(event.target.scrollTop)
31
+ }, [
32
+ spacer("before", first),
33
+ ...all.slice(first, end).map((item, i) => make(item, first + i)),
34
+ spacer("after", all.length - end)
35
+ ])];
36
+ };
37
+ }
38
+ function keyed(key, nodes) {
39
+ return nodes.flat(Infinity).map((node, i) => node && typeof node === "object" && "props" in node ? { ...node, props: { ...node.props, key: `${String(key)}:${i}` } } : node);
40
+ }
41
+ export {
42
+ createList,
43
+ keyed
44
+ };
@@ -3,6 +3,8 @@
3
3
  package dev.orvyn.runtime
4
4
 
5
5
  import android.app.Activity
6
+ import android.content.Intent
7
+ import android.content.pm.ApplicationInfo
6
8
  import android.graphics.Color
7
9
  import android.os.Bundle
8
10
  import android.os.Handler
@@ -17,13 +19,14 @@ class MainActivity : Activity() {
17
19
  private lateinit var engine: OrvynEngine
18
20
  private lateinit var renderer: OrvynRenderer
19
21
  private lateinit var container: FrameLayout
22
+ private lateinit var scroll: ScrollView
20
23
  private var lastTree: JSONObject? = null
21
24
 
22
25
  override fun onCreate(savedInstanceState: Bundle?) {
23
26
  super.onCreate(savedInstanceState)
24
27
 
25
28
  container = FrameLayout(this)
26
- val scroll = ScrollView(this).apply {
29
+ scroll = ScrollView(this).apply {
27
30
  fitsSystemWindows = true
28
31
  setBackgroundColor(Color.WHITE)
29
32
  addView(container, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
@@ -32,15 +35,51 @@ class MainActivity : Activity() {
32
35
 
33
36
  renderer = OrvynRenderer(this) { handler, value -> engine.fire(handler, value) }
34
37
  engine = OrvynEngine(this, ::showTree, ::showError)
35
- engine.start()
38
+ // Test and live reload hooks work in debug builds only: any app can send
39
+ // intent extras, so a released app must ignore them.
40
+ val debuggable = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
41
+ engine.start(intent?.dataString, if (debuggable) intent?.getStringExtra("orvynDevServer") else null)
36
42
 
37
- intent.getStringExtra("orvynTest")?.let { runTestScript(it) }
43
+ if (debuggable) intent.getStringExtra("orvynTest")?.let { runTestScript(it) }
44
+ }
45
+
46
+ @Deprecated("Deprecated in Java")
47
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
48
+ @Suppress("DEPRECATION")
49
+ super.onActivityResult(requestCode, resultCode, data)
50
+ engine.device.result(requestCode, resultCode, data)
51
+ }
52
+
53
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
54
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
55
+ engine.device.permission(requestCode, grantResults)
56
+ }
57
+
58
+ override fun onNewIntent(intent: Intent) {
59
+ super.onNewIntent(intent)
60
+ intent.dataString?.let { engine.openUrl(it) }
61
+ }
62
+
63
+ @Deprecated("Deprecated in Java")
64
+ override fun onBackPressed() {
65
+ if (lastTree?.optBoolean("canGoBack", false) == true) {
66
+ engine.goBack()
67
+ return
68
+ }
69
+ @Suppress("DEPRECATION")
70
+ super.onBackPressed()
38
71
  }
39
72
 
40
73
  private fun showTree(tree: JSONObject) {
41
74
  lastTree = tree
75
+ val theme = tree.optJSONObject("theme")
76
+ renderer.setTheme(theme)
77
+ theme?.optString("bg")?.let { bg ->
78
+ try { scroll.setBackgroundColor(Color.parseColor(bg)) } catch (_: Exception) {}
79
+ }
80
+ val availableWidth = if (container.width > 0) container.width else resources.displayMetrics.widthPixels
42
81
  val existing = if (container.childCount > 0) container.getChildAt(0) else null
43
- val view = renderer.render(tree, existing, parentType = "root")
82
+ val view = renderer.render(tree, existing, parentType = "root", availableWidthPx = availableWidth)
44
83
  if (view !== existing) {
45
84
  container.removeAllViews()
46
85
  container.addView(view)
@@ -0,0 +1,163 @@
1
+ // Generated by Orvyn. Do not edit; rebuild with `orvyn build android app.orv`.
2
+ //
3
+ // Camera, photos, files and location. One request at a time.
4
+
5
+ package dev.orvyn.runtime
6
+
7
+ import android.Manifest
8
+ import android.app.Activity
9
+ import android.content.ActivityNotFoundException
10
+ import android.content.Intent
11
+ import android.content.pm.PackageManager
12
+ import android.graphics.Bitmap
13
+ import android.graphics.BitmapFactory
14
+ import android.location.Location
15
+ import android.location.LocationListener
16
+ import android.location.LocationManager
17
+ import android.os.Handler
18
+ import android.os.Looper
19
+ import android.provider.MediaStore
20
+ import android.provider.OpenableColumns
21
+ import android.util.Base64
22
+ import org.json.JSONObject
23
+ import java.io.ByteArrayOutputStream
24
+ import kotlin.concurrent.thread
25
+
26
+ class OrvynDevice(private val activity: Activity, private val done: (Int, String, String) -> Unit) {
27
+ private val main = Handler(Looper.getMainLooper())
28
+ private var waiting: Int? = null
29
+ private var kind = ""
30
+
31
+ private val pickCode = 7001
32
+ private val cameraCode = 7002
33
+ private val permissionCode = 7003
34
+
35
+ fun ask(id: Int, what: String) {
36
+ if (waiting != null) return done(id, "", "Already waiting for another choice")
37
+ waiting = id
38
+ kind = what
39
+ when (what) {
40
+ "photo", "file" -> open(Intent(Intent.ACTION_GET_CONTENT).apply {
41
+ type = if (what == "photo") "image/*" else "*/*"
42
+ addCategory(Intent.CATEGORY_OPENABLE)
43
+ }, pickCode)
44
+ "camera" -> withPermission(Manifest.permission.CAMERA)
45
+ "location" -> withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
46
+ else -> finish(error = "Unknown request: $what")
47
+ }
48
+ }
49
+
50
+ private fun withPermission(permission: String) {
51
+ if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) return go()
52
+ val wanted = if (kind == "location") {
53
+ arrayOf(permission, Manifest.permission.ACCESS_COARSE_LOCATION)
54
+ } else arrayOf(permission)
55
+ activity.requestPermissions(wanted, permissionCode)
56
+ }
57
+
58
+ fun permission(code: Int, results: IntArray) {
59
+ if (code != permissionCode || waiting == null) return
60
+ if (results.any { it == PackageManager.PERMISSION_GRANTED }) go()
61
+ else finish(error = if (kind == "camera") "The camera was not allowed" else "Location was not allowed")
62
+ }
63
+
64
+ private fun go() {
65
+ // the camera hands back a small preview picture
66
+ if (kind == "camera") return open(Intent(MediaStore.ACTION_IMAGE_CAPTURE), cameraCode)
67
+ locate()
68
+ }
69
+
70
+ private fun open(intent: Intent, code: Int) {
71
+ try {
72
+ @Suppress("DEPRECATION")
73
+ activity.startActivityForResult(intent, code)
74
+ } catch (_: ActivityNotFoundException) {
75
+ finish(error = "No app on this phone can do that")
76
+ }
77
+ }
78
+
79
+ @Suppress("MissingPermission")
80
+ private fun locate() {
81
+ val manager = activity.getSystemService(Activity.LOCATION_SERVICE) as LocationManager
82
+ val provider = listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)
83
+ .firstOrNull { manager.isProviderEnabled(it) } ?: return finish(error = "Turn on location on this phone")
84
+ val id = waiting
85
+ val listener = object : LocationListener {
86
+ override fun onLocationChanged(place: Location) {
87
+ manager.removeUpdates(this)
88
+ if (waiting != id) return
89
+ finish(JSONObject().put("latitude", place.latitude).put("longitude", place.longitude)
90
+ .put("accuracy", place.accuracy.toDouble()).toString())
91
+ }
92
+
93
+ @Deprecated("Deprecated in Java")
94
+ override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
95
+ override fun onProviderEnabled(provider: String) {}
96
+ override fun onProviderDisabled(provider: String) {}
97
+ }
98
+ try {
99
+ manager.requestLocationUpdates(provider, 0L, 0f, listener, Looper.getMainLooper())
100
+ } catch (_: SecurityException) {
101
+ return finish(error = "Location was not allowed")
102
+ }
103
+ main.postDelayed({
104
+ if (waiting == id) {
105
+ manager.removeUpdates(listener)
106
+ finish(error = "Could not get the location")
107
+ }
108
+ }, 15000)
109
+ }
110
+
111
+ fun result(code: Int, resultCode: Int, data: Intent?) {
112
+ if ((code != pickCode && code != cameraCode) || waiting == null) return
113
+ if (resultCode != Activity.RESULT_OK) return finish()
114
+ if (code == cameraCode) {
115
+ @Suppress("DEPRECATION")
116
+ val picture = data?.extras?.get("data") as? Bitmap ?: return finish(error = "The camera gave no picture")
117
+ return finish(jpeg(picture))
118
+ }
119
+ val uri = data?.data ?: return finish()
120
+ val photo = kind == "photo"
121
+ thread {
122
+ try {
123
+ val bytes = activity.contentResolver.openInputStream(uri)!!.use { it.readBytes() }
124
+ val result = if (photo) {
125
+ // large photos are scaled down so the app stays quick
126
+ val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
127
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, size)
128
+ val options = BitmapFactory.Options().apply {
129
+ inSampleSize = 1
130
+ while (maxOf(size.outWidth, size.outHeight) / inSampleSize > 1600) inSampleSize *= 2
131
+ }
132
+ jpeg(BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)!!)
133
+ } else {
134
+ var name = "file"
135
+ activity.contentResolver.query(uri, null, null, null, null)?.use {
136
+ val column = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
137
+ if (column >= 0 && it.moveToFirst()) name = it.getString(column)
138
+ }
139
+ file(name, activity.contentResolver.getType(uri) ?: "application/octet-stream", bytes)
140
+ }
141
+ main.post { finish(result) }
142
+ } catch (_: Throwable) {
143
+ main.post { finish(error = "Could not read the file") }
144
+ }
145
+ }
146
+ }
147
+
148
+ private fun jpeg(picture: Bitmap): String {
149
+ val out = ByteArrayOutputStream()
150
+ picture.compress(Bitmap.CompressFormat.JPEG, 85, out)
151
+ return file("photo.jpg", "image/jpeg", out.toByteArray())
152
+ }
153
+
154
+ private fun file(name: String, type: String, bytes: ByteArray): String =
155
+ JSONObject().put("name", name).put("type", type).put("size", bytes.size)
156
+ .put("dataUrl", "data:$type;base64," + Base64.encodeToString(bytes, Base64.NO_WRAP)).toString()
157
+
158
+ private fun finish(json: String = "", error: String = "") {
159
+ val id = waiting ?: return
160
+ waiting = null
161
+ done(id, json, error)
162
+ }
163
+ }
@@ -9,6 +9,9 @@ import android.annotation.SuppressLint
9
9
  import android.app.Activity
10
10
  import android.os.Handler
11
11
  import android.os.Looper
12
+ import android.security.keystore.KeyGenParameterSpec
13
+ import android.security.keystore.KeyProperties
14
+ import android.util.Base64
12
15
  import android.util.Log
13
16
  import android.webkit.ConsoleMessage
14
17
  import android.webkit.JavascriptInterface
@@ -17,6 +20,12 @@ import android.webkit.WebView
17
20
  import org.json.JSONObject
18
21
  import java.net.HttpURLConnection
19
22
  import java.net.URL
23
+ import java.security.KeyStore
24
+ import java.util.concurrent.ConcurrentHashMap
25
+ import javax.crypto.Cipher
26
+ import javax.crypto.KeyGenerator
27
+ import javax.crypto.SecretKey
28
+ import javax.crypto.spec.GCMParameterSpec
20
29
  import kotlin.concurrent.thread
21
30
 
22
31
  class OrvynEngine(
@@ -25,12 +34,54 @@ class OrvynEngine(
25
34
  private val onError: (String) -> Unit
26
35
  ) {
27
36
  private val webView = WebView(activity)
37
+ val device = OrvynDevice(activity) { id, json, error ->
38
+ js("__orvynDeviceDone($id, ${JSONObject.quote(json)}, ${JSONObject.quote(error)})")
39
+ }
28
40
  // saved state → SharedPreferences (kept after the app closes)
29
41
  private val storage = activity.getSharedPreferences("orvyn", android.content.Context.MODE_PRIVATE)
42
+ // secure credentials → KeyStore-encrypted SharedPreferences (separate from saved state)
43
+ private val secureStorage = activity.getSharedPreferences("orvyn_secure", android.content.Context.MODE_PRIVATE)
30
44
  private val main = Handler(Looper.getMainLooper())
45
+ private val fetchConnections = ConcurrentHashMap<Int, HttpURLConnection>()
46
+
47
+ private fun secretKey(): SecretKey {
48
+ val alias = "orvyn_secure_key"
49
+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
50
+ (ks.getKey(alias, null) as? SecretKey)?.let { return it }
51
+ val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
52
+ gen.init(
53
+ KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
54
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
55
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
56
+ .setKeySize(256)
57
+ .build()
58
+ )
59
+ return gen.generateKey()
60
+ }
61
+
62
+ private fun encryptSecret(plain: String): String {
63
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
64
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey())
65
+ val iv = cipher.iv
66
+ val encrypted = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
67
+ val combined = ByteArray(iv.size + encrypted.size)
68
+ System.arraycopy(iv, 0, combined, 0, iv.size)
69
+ System.arraycopy(encrypted, 0, combined, iv.size, encrypted.size)
70
+ return Base64.encodeToString(combined, Base64.NO_WRAP)
71
+ }
72
+
73
+ private fun decryptSecret(encoded: String): String? {
74
+ val combined = Base64.decode(encoded, Base64.NO_WRAP)
75
+ if (combined.size <= 12) return null
76
+ val iv = combined.copyOfRange(0, 12)
77
+ val encrypted = combined.copyOfRange(12, combined.size)
78
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
79
+ cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, iv))
80
+ return String(cipher.doFinal(encrypted), Charsets.UTF_8)
81
+ }
31
82
 
32
83
  @SuppressLint("SetJavaScriptEnabled")
33
- fun start() {
84
+ fun start(initialUrl: String? = null, devServer: String? = null) {
34
85
  webView.settings.javaScriptEnabled = true
35
86
  webView.addJavascriptInterface(Bridge(), "OrvynHost")
36
87
  webView.webChromeClient = object : WebChromeClient() {
@@ -40,16 +91,58 @@ class OrvynEngine(
40
91
  }
41
92
  }
42
93
 
43
- val app = activity.assets.open("app.js").bufferedReader().use { it.readText() }
44
- .replace("</script", "<\\/script")
94
+ if (devServer == null) {
95
+ load(activity.assets.open("app.js").bufferedReader().use { it.readText() }, initialUrl)
96
+ } else {
97
+ watchDevServer(devServer, initialUrl)
98
+ }
99
+ }
100
+
101
+ // `orvyn dev android`: load code from the computer and reload when it changes
102
+ private fun watchDevServer(server: String, initialUrl: String?) {
103
+ thread(isDaemon = true) {
104
+ var loaded: String? = null
105
+ while (!activity.isDestroyed) {
106
+ try {
107
+ val version = URL("$server/version").readText()
108
+ if (version != loaded) {
109
+ val code = URL("$server/app.js").readText()
110
+ loaded = version
111
+ main.post { load(code, initialUrl) }
112
+ }
113
+ } catch (error: Exception) {
114
+ if (loaded == null) {
115
+ loaded = ""
116
+ main.post { onError("Can't reach the Orvyn dev server. Is `orvyn dev android` still running?") }
117
+ }
118
+ }
119
+ Thread.sleep(1000)
120
+ }
121
+ }
122
+ }
123
+
124
+ // a fresh page, so nothing from the previous version keeps running
125
+ private fun load(code: String, initialUrl: String?) {
126
+ val app = code.replace("</script", "<\\/script")
45
127
 
128
+ val initialUrlJs = if (initialUrl != null) "window.__orvynInitialUrl = ${JSONObject.quote(initialUrl)};" else ""
46
129
  val shim = """
130
+ $initialUrlJs
47
131
  window.__orvynRender = function (json) { OrvynHost.render(json) };
132
+ window.__orvynDevice = function (id, kind) { OrvynHost.device(id, kind) };
48
133
  window.__orvynFetch = function (id, url, method, body, headers) {
49
134
  OrvynHost.fetch(id, url, method, body == null ? null : String(body), headers)
50
135
  };
136
+ window.__orvynAbortFetch = function (id) {
137
+ OrvynHost.abortFetch(id)
138
+ };
51
139
  window.__orvynStorageGet = function (key) { return OrvynHost.storageGet(key) };
52
- window.__orvynStorageSet = function (key, value) { OrvynHost.storageSet(key, value) };
140
+ window.__orvynStorageSet = function (key, value) { return OrvynHost.storageSet(key, value) };
141
+ window.__orvynStorageRemove = function (key) { return OrvynHost.storageRemove(key) };
142
+ window.__orvynSecureGet = function (key) { return OrvynHost.secureGet(key) };
143
+ window.__orvynSecureSet = function (key, value) { return OrvynHost.secureSet(key, value) };
144
+ window.__orvynSecureRemove = function (key) { return OrvynHost.secureRemove(key) };
145
+ window.__orvynSecureClear = function () { return OrvynHost.secureClear() };
53
146
  window.onerror = function (message) { OrvynHost.error(String(message)) };
54
147
  window.addEventListener("unhandledrejection", function (event) {
55
148
  OrvynHost.error(String(event.reason && event.reason.message || event.reason))
@@ -60,6 +153,14 @@ class OrvynEngine(
60
153
  webView.loadDataWithBaseURL("https://orvyn.local/", html, "text/html", "utf-8", null)
61
154
  }
62
155
 
156
+ fun openUrl(url: String) {
157
+ js("window.__orvynDeepLink && window.__orvynDeepLink(${JSONObject.quote(url)})")
158
+ }
159
+
160
+ fun goBack() {
161
+ js("window.__orvynBack && window.__orvynBack()")
162
+ }
163
+
63
164
  fun fire(handler: Int, value: String?) {
64
165
  if (value == null) {
65
166
  js("__orvynEvent($handler)")
@@ -79,12 +180,48 @@ class OrvynEngine(
79
180
  main.post { onRender(tree) }
80
181
  }
81
182
 
183
+ @JavascriptInterface
184
+ fun device(id: Int, kind: String) {
185
+ main.post { this@OrvynEngine.device.ask(id, kind) }
186
+ }
187
+
82
188
  @JavascriptInterface
83
189
  fun storageGet(key: String): String? = storage.getString(key, null)
84
190
 
85
191
  @JavascriptInterface
86
- fun storageSet(key: String, value: String) {
87
- storage.edit().putString(key, value).apply()
192
+ fun storageSet(key: String, value: String): String? {
193
+ return if (storage.edit().putString(key, value).commit()) null else "Storage write failed"
194
+ }
195
+
196
+ @JavascriptInterface
197
+ fun storageRemove(key: String): String? {
198
+ return if (storage.edit().remove(key).commit()) null else "Storage delete failed"
199
+ }
200
+
201
+ @JavascriptInterface
202
+ fun secureGet(key: String): String? {
203
+ val encoded = secureStorage.getString(key, null) ?: return null
204
+ return try { decryptSecret(encoded) } catch (_: Exception) { null }
205
+ }
206
+
207
+ @JavascriptInterface
208
+ fun secureSet(key: String, value: String): String? {
209
+ return try {
210
+ val encoded = encryptSecret(value)
211
+ if (secureStorage.edit().putString(key, encoded).commit()) null else "Secure storage write failed"
212
+ } catch (error: Exception) {
213
+ error.message ?: "Secure storage failed"
214
+ }
215
+ }
216
+
217
+ @JavascriptInterface
218
+ fun secureRemove(key: String): String? {
219
+ return if (secureStorage.edit().remove(key).commit()) null else "Secure storage delete failed"
220
+ }
221
+
222
+ @JavascriptInterface
223
+ fun secureClear(): String? {
224
+ return if (secureStorage.edit().clear().commit()) null else "Secure storage clear failed"
88
225
  }
89
226
 
90
227
  @JavascriptInterface
@@ -93,14 +230,21 @@ class OrvynEngine(
93
230
  main.post { onError(message) }
94
231
  }
95
232
 
233
+ @JavascriptInterface
234
+ fun abortFetch(id: Int) {
235
+ fetchConnections.remove(id)?.disconnect()
236
+ }
237
+
96
238
  @JavascriptInterface
97
239
  fun fetch(id: Int, url: String, method: String, body: String?, headers: String) {
98
240
  thread {
99
241
  var status = 0
100
242
  var text: String
101
243
  var contentType = ""
244
+ var connection: HttpURLConnection? = null
102
245
  try {
103
- val connection = URL(url).openConnection() as HttpURLConnection
246
+ connection = URL(url).openConnection() as HttpURLConnection
247
+ fetchConnections[id] = connection
104
248
  connection.requestMethod = method
105
249
  val headerJson = JSONObject(headers)
106
250
  for (key in headerJson.keys()) {
@@ -117,6 +261,9 @@ class OrvynEngine(
117
261
  } catch (error: Exception) {
118
262
  status = 0
119
263
  text = error.message ?: "Network error"
264
+ } finally {
265
+ fetchConnections.remove(id)
266
+ connection?.disconnect()
120
267
  }
121
268
  main.post {
122
269
  js("__orvynFetchDone($id, $status, ${JSONObject.quote(text)}, ${JSONObject.quote(contentType)})")