@blotch/angular-lynx-native 22.2.21 → 22.2.23
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.
- package/README.md +4 -0
- package/dist/android/build.d.ts +6 -1
- package/dist/android/build.d.ts.map +1 -1
- package/dist/android/build.js +14 -3
- package/dist/android/run.d.ts +10 -1
- package/dist/android/run.d.ts.map +1 -1
- package/dist/android/run.js +46 -1
- package/dist/dev-build.d.ts +16 -0
- package/dist/dev-build.d.ts.map +1 -0
- package/dist/dev-build.js +44 -0
- package/dist/generate.d.ts +24 -5
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +14 -6
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +65 -9
- package/dist/ios/build.d.ts +14 -1
- package/dist/ios/build.d.ts.map +1 -1
- package/dist/ios/build.js +15 -6
- package/dist/ios/iphone.d.ts +1 -1
- package/dist/ios/iphone.d.ts.map +1 -1
- package/dist/ios/iphone.js +21 -4
- package/dist/ios/project.d.ts +8 -1
- package/dist/ios/project.d.ts.map +1 -1
- package/dist/ios/project.js +17 -3
- package/dist/ios/run.d.ts +1 -1
- package/dist/ios/run.d.ts.map +1 -1
- package/dist/ios/run.js +4 -1
- package/dist/run.d.ts +42 -2
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +16 -1
- package/package.json +1 -1
- package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +159 -0
- package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServerModules.kt +163 -0
- package/templates/android/app/src/debug/res/xml/network_security_config.xml +13 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +22 -0
- package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +8 -1
- package/templates/android/app/src/main/java/dev/angularlynx/shell/ResourceFetchers.kt +12 -6
- package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +24 -0
- package/templates/ios/App/AssetsModule.swift +21 -3
- package/templates/ios/App/BundleResourceFetcher.swift +46 -2
- package/templates/ios/App/DevServer.swift +190 -0
- package/templates/ios/App/DevServerModules.swift +223 -0
- package/templates/ios/App/LynxViewController.swift +9 -1
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
package dev.angularlynx.shell
|
|
2
|
+
|
|
3
|
+
import com.lynx.jsbridge.LynxContextModule
|
|
4
|
+
import com.lynx.jsbridge.LynxMethod
|
|
5
|
+
import com.lynx.jsbridge.LynxModule
|
|
6
|
+
import com.lynx.react.bridge.Callback
|
|
7
|
+
import com.lynx.react.bridge.JavaOnlyArray
|
|
8
|
+
import com.lynx.react.bridge.JavaOnlyMap
|
|
9
|
+
import com.lynx.react.bridge.ReadableArray
|
|
10
|
+
import com.lynx.react.bridge.ReadableMap
|
|
11
|
+
import com.lynx.tasm.behavior.LynxContext
|
|
12
|
+
import okhttp3.OkHttpClient
|
|
13
|
+
import okhttp3.Request
|
|
14
|
+
import okhttp3.Response
|
|
15
|
+
import okhttp3.WebSocket
|
|
16
|
+
import okhttp3.WebSocketListener
|
|
17
|
+
import okio.ByteString
|
|
18
|
+
import org.json.JSONObject
|
|
19
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
20
|
+
import java.util.concurrent.TimeUnit
|
|
21
|
+
|
|
22
|
+
/*
|
|
23
|
+
* The two native modules rspeedy's live reload needs, in the debug build
|
|
24
|
+
* only (see DevServer.kt). Lynx Explorer has them from Lynx DevTool, which
|
|
25
|
+
* the shell doesn't include: the dev server's client, which rspeedy puts in
|
|
26
|
+
* every development bundle, talks to the server over
|
|
27
|
+
* `NativeModules.LynxWebSocketModule` (through @lynx-js/websocket) and
|
|
28
|
+
* reloads the page with `NativeModules.LynxDevToolSetModule.invokeCdp`, a
|
|
29
|
+
* DevTool protocol `Page.reload`. These answer to the same names and calls,
|
|
30
|
+
* so the bundle runs here as it does in Lynx Explorer.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `NativeModules.LynxWebSocketModule`, as Lynx DevTool's
|
|
35
|
+
* (LynxWebSocket.java): `connect`, `send`, `ping` and `close`, each with the
|
|
36
|
+
* socket's ID, and the `websocketOpen`, `websocketMessage`, `websocketClosed`
|
|
37
|
+
* and `websocketFailed` global events @lynx-js/websocket listens for.
|
|
38
|
+
*/
|
|
39
|
+
class DevWebSocketModule : LynxContextModule {
|
|
40
|
+
// Lynx creates a module through whichever of its constructors it finds.
|
|
41
|
+
constructor(context: LynxContext) : super(context)
|
|
42
|
+
constructor(context: LynxContext, param: Any?) : super(context, param)
|
|
43
|
+
|
|
44
|
+
private val sockets = ConcurrentHashMap<Int, WebSocket>()
|
|
45
|
+
|
|
46
|
+
// No read timeout: the dev server only writes when there's a new build.
|
|
47
|
+
private val client = OkHttpClient.Builder()
|
|
48
|
+
.connectTimeout(10, TimeUnit.SECONDS)
|
|
49
|
+
.readTimeout(0, TimeUnit.MILLISECONDS)
|
|
50
|
+
.build()
|
|
51
|
+
|
|
52
|
+
@LynxMethod
|
|
53
|
+
fun connect(url: String, protocols: ReadableArray?, options: ReadableMap?, socketID: Double) {
|
|
54
|
+
val id = socketID.toInt()
|
|
55
|
+
val request = Request.Builder()
|
|
56
|
+
// The address the bundle was built with reaches this device's
|
|
57
|
+
// localhost through adb reverse.
|
|
58
|
+
.url(DevServer.remoteUrl(url) ?: url)
|
|
59
|
+
.apply {
|
|
60
|
+
val names = (0 until (protocols?.size() ?: 0)).mapNotNull { protocols?.getString(it)?.trim() }
|
|
61
|
+
.filter { it.isNotEmpty() && !it.contains(',') }
|
|
62
|
+
if (names.isNotEmpty()) addHeader("Sec-WebSocket-Protocol", names.joinToString(","))
|
|
63
|
+
}
|
|
64
|
+
.build()
|
|
65
|
+
client.newWebSocket(request, object : WebSocketListener() {
|
|
66
|
+
override fun onOpen(webSocket: WebSocket, response: Response) {
|
|
67
|
+
sockets[id] = webSocket
|
|
68
|
+
emit("websocketOpen", "id" to id, "protocol" to (response.header("Sec-WebSocket-Protocol") ?: ""))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
override fun onMessage(webSocket: WebSocket, text: String) =
|
|
72
|
+
emit("websocketMessage", "id" to id, "type" to "text", "data" to text)
|
|
73
|
+
|
|
74
|
+
override fun onMessage(webSocket: WebSocket, bytes: ByteString) =
|
|
75
|
+
emit("websocketMessage", "id" to id, "type" to "binary", "data" to bytes.base64())
|
|
76
|
+
|
|
77
|
+
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
|
|
78
|
+
webSocket.close(code, reason)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
|
82
|
+
sockets.remove(id)
|
|
83
|
+
emit("websocketClosed", "id" to id, "code" to code, "reason" to reason)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The connection failed or dropped (the server stopped): the dev
|
|
87
|
+
// server's client then tries again, with a growing delay.
|
|
88
|
+
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
|
89
|
+
sockets.remove(id)
|
|
90
|
+
emit("websocketFailed", "id" to id, "message" to (t.message ?: t.toString()))
|
|
91
|
+
emit("websocketClosed", "id" to id, "code" to 1006, "reason" to (t.message ?: ""))
|
|
92
|
+
}
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
@LynxMethod
|
|
97
|
+
fun send(message: String, socketID: Double) {
|
|
98
|
+
sockets[socketID.toInt()]?.send(message)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@LynxMethod
|
|
102
|
+
fun ping(socketID: Double) {
|
|
103
|
+
sockets[socketID.toInt()]?.send(ByteString.EMPTY)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
@LynxMethod
|
|
107
|
+
fun close(code: Double, reason: String, socketID: Double) {
|
|
108
|
+
sockets.remove(socketID.toInt())?.close(code.toInt(), reason)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
override fun destroy() {
|
|
112
|
+
sockets.values.forEach { it.close(1001, "The page closed") }
|
|
113
|
+
sockets.clear()
|
|
114
|
+
super.destroy()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private fun emit(event: String, vararg params: Pair<String, Any>) {
|
|
118
|
+
val map = JavaOnlyMap()
|
|
119
|
+
for ((key, value) in params) {
|
|
120
|
+
when (value) {
|
|
121
|
+
is Int -> map.putInt(key, value)
|
|
122
|
+
else -> map.putString(key, value.toString())
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
mLynxContext.sendGlobalEvent(event, JavaOnlyArray().apply { pushMap(map) })
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
companion object {
|
|
129
|
+
const val NAME = "LynxWebSocketModule"
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* `NativeModules.LynxDevToolSetModule`, as far as rspeedy's live reload uses
|
|
135
|
+
* Lynx DevTool's: `invokeCdp` with a `Page.reload`, which renders the bundle
|
|
136
|
+
* from the dev server again, as Lynx DevTool's page reload does. It answers
|
|
137
|
+
* any other DevTool method with an error.
|
|
138
|
+
*/
|
|
139
|
+
class DevReloadModule(context: android.content.Context, param: Any?) : LynxModule(context, param) {
|
|
140
|
+
@LynxMethod
|
|
141
|
+
fun invokeCdp(message: String, callback: Callback?) {
|
|
142
|
+
val request = runCatching { JSONObject(message) }.getOrDefault(JSONObject())
|
|
143
|
+
val id = request.opt("id") ?: 0
|
|
144
|
+
val method = request.optString("method")
|
|
145
|
+
val reply = JSONObject().put("id", id)
|
|
146
|
+
if (method == "Page.reload") {
|
|
147
|
+
DevServer.reloadBundle()
|
|
148
|
+
reply.put("result", JSONObject())
|
|
149
|
+
} else {
|
|
150
|
+
reply.put(
|
|
151
|
+
"error",
|
|
152
|
+
JSONObject()
|
|
153
|
+
.put("code", -32601)
|
|
154
|
+
.put("message", "$method needs Lynx DevTool, which this app doesn't have."),
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
callback?.invoke(reply.toString())
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
companion object {
|
|
161
|
+
const val NAME = "LynxDevToolSetModule"
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="utf-8"?>
|
|
2
|
+
<!--
|
|
3
|
+
The debug build's network security config, in place of src/main's: plain
|
|
4
|
+
HTTP to any host. Only `ng serve` builds the debug build type (with the
|
|
5
|
+
platform option set to android). The dev
|
|
6
|
+
server is plain HTTP, and a development bundle names it by the computer's
|
|
7
|
+
address on the local network (rspeedy's dev.assetPrefix), which the app's
|
|
8
|
+
own fetch() of an imported file goes to directly. The release build keeps
|
|
9
|
+
src/main's, which allows plain HTTP to localhost alone.
|
|
10
|
+
-->
|
|
11
|
+
<network-security-config>
|
|
12
|
+
<base-config cleartextTrafficPermitted="true" />
|
|
13
|
+
</network-security-config>
|
|
@@ -4,8 +4,11 @@ import android.content.Context
|
|
|
4
4
|
import com.lynx.jsbridge.LynxMethod
|
|
5
5
|
import com.lynx.jsbridge.LynxModule
|
|
6
6
|
import com.lynx.react.bridge.JavaOnlyArray
|
|
7
|
+
import com.lynx.tasm.core.LynxThreadPool
|
|
8
|
+
import okhttp3.Request
|
|
7
9
|
import java.io.IOException
|
|
8
10
|
import java.nio.ByteBuffer
|
|
11
|
+
import java.util.concurrent.FutureTask
|
|
9
12
|
|
|
10
13
|
/**
|
|
11
14
|
* The `AngularLynxAssets` module: a file the app bundles (`/static/...`),
|
|
@@ -26,6 +29,7 @@ class AssetsModule(context: Context, param: Any?) : LynxModule(context, param) {
|
|
|
26
29
|
*/
|
|
27
30
|
@LynxMethod
|
|
28
31
|
fun read(url: String): JavaOnlyArray? {
|
|
32
|
+
DevServer.remoteUrl(url)?.let { return readRemote(it) }
|
|
29
33
|
val path = BundleAssets.assetPath(url) ?: return null
|
|
30
34
|
return try {
|
|
31
35
|
val bytes = BundleAssets.read(mContext, path)
|
|
@@ -35,6 +39,24 @@ class AssetsModule(context: Context, param: Any?) : LynxModule(context, param) {
|
|
|
35
39
|
}
|
|
36
40
|
}
|
|
37
41
|
|
|
42
|
+
/**
|
|
43
|
+
* The file on the dev server, in the debug build `ng serve --platform
|
|
44
|
+
* android` runs, which has the current copy. The call is synchronous, so
|
|
45
|
+
* the request is too, but on a thread of its own: Android doesn't allow
|
|
46
|
+
* network requests on the UI thread, where Lynx may call this.
|
|
47
|
+
*/
|
|
48
|
+
private fun readRemote(url: String): JavaOnlyArray? = try {
|
|
49
|
+
val download = FutureTask {
|
|
50
|
+
http.newCall(Request.Builder().url(url).build()).execute().use { response ->
|
|
51
|
+
if (response.isSuccessful) response.body?.bytes() else null
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
LynxThreadPool.getBriefIOExecutor().execute(download)
|
|
55
|
+
download.get()?.let { wordsFromBytes(ByteBuffer.wrap(it), it.size) }
|
|
56
|
+
} catch (_: Exception) {
|
|
57
|
+
null
|
|
58
|
+
}
|
|
59
|
+
|
|
38
60
|
companion object {
|
|
39
61
|
const val NAME = "AngularLynxAssets"
|
|
40
62
|
}
|
|
@@ -100,6 +100,9 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
|
|
|
100
100
|
enableEdgeToEdge()
|
|
101
101
|
super.onCreate(savedInstanceState)
|
|
102
102
|
|
|
103
|
+
// The bundle in the app's assets, or in the debug build `ng serve
|
|
104
|
+
// --platform android` runs, the dev server's (DevServer.kt).
|
|
105
|
+
val bundleUrl = DevServer.bundleUrl(this) ?: BundleAssets.MAIN_BUNDLE
|
|
103
106
|
lynxView = LynxViewBuilder().apply {
|
|
104
107
|
setTemplateProvider(AssetTemplateProvider(this@MainActivity))
|
|
105
108
|
setTemplateResourceFetcher(AssetTemplateResourceFetcher(this@MainActivity))
|
|
@@ -137,6 +140,9 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
|
|
|
137
140
|
if (edgeToEdge) addBehavior(EdgeToEdgeOverlay.behavior())
|
|
138
141
|
// The shell's own <canvas> (CanvasUI.kt): Lynx has none.
|
|
139
142
|
addBehavior(CanvasUI.behavior())
|
|
143
|
+
// Live reload, in the debug build: it renders the bundle again
|
|
144
|
+
// after every edit.
|
|
145
|
+
DevServer.register(this) { lynxView.renderTemplateUrl(bundleUrl, "") }
|
|
140
146
|
}.build(this)
|
|
141
147
|
// The LynxView is focusable, so it takes focus whenever the window
|
|
142
148
|
// isn't in touch mode: after any key press, from a hardware keyboard,
|
|
@@ -195,6 +201,7 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
|
|
|
195
201
|
}
|
|
196
202
|
WindowInsetsCompat.CONSUMED
|
|
197
203
|
}
|
|
204
|
+
DevServer.attach(container)
|
|
198
205
|
setContentView(container)
|
|
199
206
|
|
|
200
207
|
contentResolver.registerContentObserver(
|
|
@@ -218,7 +225,7 @@ class MainActivity : ComponentActivity(), ShellModule.Host, WebAuthModule.Host {
|
|
|
218
225
|
// Sent before the bundle loads, so the app starts with the theme and
|
|
219
226
|
// the language. The insets follow once the window reports them.
|
|
220
227
|
lynxView.updateGlobalProps(globalProps(resources.configuration))
|
|
221
|
-
lynxView.renderTemplateUrl(
|
|
228
|
+
lynxView.renderTemplateUrl(bundleUrl, "")
|
|
222
229
|
}
|
|
223
230
|
|
|
224
231
|
override fun setBackHandlerEnabled(enabled: Boolean) {
|
|
@@ -16,11 +16,12 @@ import okhttp3.Request
|
|
|
16
16
|
/**
|
|
17
17
|
* Lynx can't load anything by itself: the host app supplies loaders for
|
|
18
18
|
* bundles, images and other resources. Ours read the copy of dist/ inside the
|
|
19
|
-
* APK and fall back to HTTP for absolute http(s) URLs (an API, a CDN
|
|
20
|
-
*
|
|
19
|
+
* APK and fall back to HTTP for absolute http(s) URLs (an API, a CDN). The
|
|
20
|
+
* debug build `ng serve --platform android` runs has no copy: it loads what
|
|
21
|
+
* the bundle names from the dev server instead (DevServer.kt).
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
|
-
|
|
24
|
+
internal val http by lazy { OkHttpClient() }
|
|
24
25
|
|
|
25
26
|
// LynxResourceResponse.onFailed is declared without a type parameter, so
|
|
26
27
|
// Kotlin sees a raw type; this gives it the one each callback expects.
|
|
@@ -37,17 +38,21 @@ private fun load(
|
|
|
37
38
|
) {
|
|
38
39
|
LynxThreadPool.getBriefIOExecutor().execute {
|
|
39
40
|
try {
|
|
40
|
-
val
|
|
41
|
+
val remote = DevServer.remoteUrl(url)
|
|
42
|
+
val asset = if (remote == null) BundleAssets.assetPath(url) else null
|
|
41
43
|
val bytes = if (asset != null) {
|
|
42
44
|
BundleAssets.read(context, asset)
|
|
43
45
|
} else {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
+
val address = remote ?: url
|
|
47
|
+
http.newCall(Request.Builder().url(address).build()).execute().use { response ->
|
|
48
|
+
check(response.isSuccessful) { "HTTP ${response.code} for $address" }
|
|
46
49
|
response.body!!.bytes()
|
|
47
50
|
}
|
|
48
51
|
}
|
|
52
|
+
DevServer.loaded(url, null)
|
|
49
53
|
onSuccess(bytes)
|
|
50
54
|
} catch (error: Throwable) {
|
|
55
|
+
DevServer.loaded(url, error)
|
|
51
56
|
onFailure(Exception("Couldn't load $url: ${error.message}", error))
|
|
52
57
|
}
|
|
53
58
|
}
|
|
@@ -90,6 +95,7 @@ class AssetTemplateResourceFetcher(context: Context) : LynxTemplateResourceFetch
|
|
|
90
95
|
*/
|
|
91
96
|
class AssetMediaResourceFetcher : LynxMediaResourceFetcher() {
|
|
92
97
|
override fun shouldRedirectUrl(request: LynxResourceRequest): String {
|
|
98
|
+
DevServer.remoteUrl(request.url)?.let { return it }
|
|
93
99
|
val asset = BundleAssets.assetPath(request.url) ?: return request.url
|
|
94
100
|
return "asset:///$asset"
|
|
95
101
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
package dev.angularlynx.shell
|
|
2
|
+
|
|
3
|
+
import android.app.Activity
|
|
4
|
+
import android.widget.FrameLayout
|
|
5
|
+
import com.lynx.tasm.LynxViewBuilder
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The release build's DevServer: nothing. Only the debug build type, which
|
|
9
|
+
* `ng serve --platform android` builds, has the dev server support
|
|
10
|
+
* (src/debug/.../DevServer.kt), so nothing can point a release build at
|
|
11
|
+
* another server: its bundle is always the one in its assets. The two files
|
|
12
|
+
* keep the same functions, which MainActivity and the loaders call.
|
|
13
|
+
*/
|
|
14
|
+
object DevServer {
|
|
15
|
+
fun bundleUrl(activity: Activity): String? = null
|
|
16
|
+
|
|
17
|
+
fun register(builder: LynxViewBuilder, reload: () -> Unit) = Unit
|
|
18
|
+
|
|
19
|
+
fun attach(container: FrameLayout) = Unit
|
|
20
|
+
|
|
21
|
+
fun remoteUrl(url: String): String? = null
|
|
22
|
+
|
|
23
|
+
fun loaded(url: String, error: Throwable?) = Unit
|
|
24
|
+
}
|
|
@@ -31,9 +31,7 @@ final class AssetsModule: NSObject, LynxModule {
|
|
|
31
31
|
/// in the runtime's webgl-bridge.ts: Lynx's bridge carries no binary), or
|
|
32
32
|
/// nil when the app doesn't bundle it.
|
|
33
33
|
@objc func read(_ url: String) -> [NSNumber]? {
|
|
34
|
-
guard let
|
|
35
|
-
let data = try? Data(contentsOf: file)
|
|
36
|
-
else { return nil }
|
|
34
|
+
guard let data = Self.contents(of: url) else { return nil }
|
|
37
35
|
var words = [NSNumber]()
|
|
38
36
|
words.reserveCapacity(data.count / 4 + 2)
|
|
39
37
|
data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
|
|
@@ -50,4 +48,24 @@ final class AssetsModule: NSObject, LynxModule {
|
|
|
50
48
|
words.append(NSNumber(value: data.count))
|
|
51
49
|
return words
|
|
52
50
|
}
|
|
51
|
+
|
|
52
|
+
/// The file in LynxBundle, or in the development build, on the dev server,
|
|
53
|
+
/// which has the current copy. The call is synchronous, so that request is
|
|
54
|
+
/// too; URLSession answers on its own queue, so waiting here can't block it.
|
|
55
|
+
private static func contents(of url: String) -> Data? {
|
|
56
|
+
if let remote = DevServer.shared.remoteURL(for: url) {
|
|
57
|
+
var result: Data?
|
|
58
|
+
let done = DispatchSemaphore(value: 0)
|
|
59
|
+
URLSession.shared.dataTask(
|
|
60
|
+
with: URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
|
|
61
|
+
) { data, response, _ in
|
|
62
|
+
if (response as? HTTPURLResponse)?.statusCode == 200 { result = data }
|
|
63
|
+
done.signal()
|
|
64
|
+
}.resume()
|
|
65
|
+
done.wait()
|
|
66
|
+
return result
|
|
67
|
+
}
|
|
68
|
+
guard let file = BundleResourceFetcher.shared.localFile(for: url) else { return nil }
|
|
69
|
+
return try? Data(contentsOf: file)
|
|
70
|
+
}
|
|
53
71
|
}
|
|
@@ -3,7 +3,9 @@ import Lynx
|
|
|
3
3
|
|
|
4
4
|
/// Serves the app's Lynx bundles and assets from the `LynxBundle` folder that
|
|
5
5
|
/// the generator copies `dist/` into, and falls back to the network for
|
|
6
|
-
/// anything else (remote images,
|
|
6
|
+
/// anything else (remote images, an API). The development build that
|
|
7
|
+
/// `ng serve --platform ios` runs has no LynxBundle: it loads everything the
|
|
8
|
+
/// bundle names from the dev server instead (see DevServer).
|
|
7
9
|
///
|
|
8
10
|
/// One class covers every loader Lynx asks for: the global template provider
|
|
9
11
|
/// (`LynxTemplateProvider`), and the per-view template, generic and media
|
|
@@ -54,6 +56,24 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
|
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
private func load(_ url: String, completion: @escaping (Data?, Error?) -> Void) {
|
|
59
|
+
if let remote = DevServer.shared.remoteURL(for: url) {
|
|
60
|
+
// Never from URLSession's cache: the server has a new build after
|
|
61
|
+
// every edit, under the same URL.
|
|
62
|
+
let request = URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
|
|
63
|
+
URLSession.shared.dataTask(with: request) { data, response, error in
|
|
64
|
+
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
|
|
65
|
+
let failure =
|
|
66
|
+
error
|
|
67
|
+
?? (status >= 400
|
|
68
|
+
? NSError(
|
|
69
|
+
domain: "AngularLynx", code: status,
|
|
70
|
+
userInfo: [NSLocalizedDescriptionKey: "The dev server answered \(status) for \(remote)."])
|
|
71
|
+
: nil)
|
|
72
|
+
DevServer.shared.loaded(url, error: failure)
|
|
73
|
+
completion(failure == nil ? data : nil, failure)
|
|
74
|
+
}.resume()
|
|
75
|
+
return
|
|
76
|
+
}
|
|
57
77
|
if let file = localFile(for: url) {
|
|
58
78
|
do {
|
|
59
79
|
completion(try Data(contentsOf: file), nil)
|
|
@@ -114,6 +134,29 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
|
|
|
114
134
|
_ request: LynxResourceRequest,
|
|
115
135
|
onComplete callback: @escaping LynxGenericResourcePathCompletionBlock
|
|
116
136
|
) -> () -> Void {
|
|
137
|
+
if let remote = DevServer.shared.remoteURL(for: request.url) {
|
|
138
|
+
// A file the bundle loads by path is on the dev server, so it's
|
|
139
|
+
// downloaded to a file first.
|
|
140
|
+
let task = URLSession.shared.downloadTask(
|
|
141
|
+
with: URLRequest(url: remote, cachePolicy: .reloadIgnoringLocalCacheData)
|
|
142
|
+
) { location, _, error in
|
|
143
|
+
guard let location else {
|
|
144
|
+
callback(nil, error)
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
let file = FileManager.default.temporaryDirectory
|
|
148
|
+
.appendingPathComponent(UUID().uuidString)
|
|
149
|
+
.appendingPathExtension(remote.pathExtension)
|
|
150
|
+
do {
|
|
151
|
+
try FileManager.default.moveItem(at: location, to: file)
|
|
152
|
+
callback(file.path, nil)
|
|
153
|
+
} catch {
|
|
154
|
+
callback(nil, error)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
task.resume()
|
|
158
|
+
return { task.cancel() }
|
|
159
|
+
}
|
|
117
160
|
if let file = localFile(for: request.url) {
|
|
118
161
|
callback(file.path, nil)
|
|
119
162
|
} else {
|
|
@@ -131,6 +174,7 @@ final class BundleResourceFetcher: NSObject, LynxTemplateProvider,
|
|
|
131
174
|
/// Images load through LynxService's SDWebImage service, which reads
|
|
132
175
|
/// `file://` URLs itself, so local images only need their URL rewritten.
|
|
133
176
|
func shouldRedirectUrl(_ request: LynxResourceRequest) -> String {
|
|
134
|
-
|
|
177
|
+
DevServer.shared.remoteURL(for: request.url)?.absoluteString
|
|
178
|
+
?? localFile(for: request.url)?.absoluteString ?? request.url
|
|
135
179
|
}
|
|
136
180
|
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Lynx
|
|
3
|
+
import UIKit
|
|
4
|
+
|
|
5
|
+
/// `ng serve --platform ios`: the development app loads its bundle from the
|
|
6
|
+
/// dev server rather than from the copy in LynxBundle (which it doesn't
|
|
7
|
+
/// have), and reloads it on every edit, as Lynx Explorer does.
|
|
8
|
+
///
|
|
9
|
+
/// Only the Debug configuration, which `ng serve --platform ios` builds,
|
|
10
|
+
/// compiles any of it in. A Release build (`ng build --platform ios`, the App
|
|
11
|
+
/// Store's) gets the stubs at the bottom, so nothing can point it at another
|
|
12
|
+
/// server: its bundle is always the one inside it.
|
|
13
|
+
///
|
|
14
|
+
/// The builder opens the app with the bundle's URL as a launch argument,
|
|
15
|
+
/// `-AngularLynxDevServer <url>`, which iOS puts in UserDefaults' argument
|
|
16
|
+
/// domain. It's kept, so opening the app from the home screen later loads
|
|
17
|
+
/// from the same server.
|
|
18
|
+
final class DevServer {
|
|
19
|
+
static let shared = DevServer()
|
|
20
|
+
|
|
21
|
+
#if DEBUG
|
|
22
|
+
private static let argument = "AngularLynxDevServer"
|
|
23
|
+
private static let lastServerKey = "AngularLynxDevServerLast"
|
|
24
|
+
|
|
25
|
+
/// The bundle on the dev server, e.g. `http://192.168.1.20:3000/main.lynx.bundle`.
|
|
26
|
+
private let bundle: URL?
|
|
27
|
+
|
|
28
|
+
/// The folder it's in, which every relative URL the bundle asks for
|
|
29
|
+
/// resolves against: lazy bundles, images, files it fetches.
|
|
30
|
+
private let base: URL?
|
|
31
|
+
|
|
32
|
+
/// Reloads the LynxView, which LynxViewController sets.
|
|
33
|
+
private var reload: (() -> Void)?
|
|
34
|
+
|
|
35
|
+
/// Tells the person the dev server can't be reached, over the page.
|
|
36
|
+
private var status: UILabel?
|
|
37
|
+
private var statusScreen: UIView?
|
|
38
|
+
private var retry: DispatchWorkItem?
|
|
39
|
+
|
|
40
|
+
private init() {
|
|
41
|
+
let defaults = UserDefaults.standard
|
|
42
|
+
let launched = defaults.volatileDomain(forName: UserDefaults.argumentDomain)[
|
|
43
|
+
Self.argument] as? String
|
|
44
|
+
if let launched {
|
|
45
|
+
defaults.set(launched, forKey: Self.lastServerKey)
|
|
46
|
+
}
|
|
47
|
+
bundle = (launched ?? defaults.string(forKey: Self.lastServerKey)).flatMap(URL.init(string:))
|
|
48
|
+
base = bundle?.deletingLastPathComponent()
|
|
49
|
+
}
|
|
50
|
+
#endif
|
|
51
|
+
|
|
52
|
+
/// The URL the LynxView loads: the dev server's bundle in a development
|
|
53
|
+
/// build, else the one inside the app.
|
|
54
|
+
var templateURL: String {
|
|
55
|
+
#if DEBUG
|
|
56
|
+
return bundle?.absoluteString ?? "main.lynx.bundle"
|
|
57
|
+
#else
|
|
58
|
+
return "main.lynx.bundle"
|
|
59
|
+
#endif
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// Where a URL the bundle asks for is on the dev server, or nil when the
|
|
63
|
+
/// app isn't loading from one, or the URL is somewhere else (an API, a
|
|
64
|
+
/// CDN, a data: URL, a file the app wrote).
|
|
65
|
+
///
|
|
66
|
+
/// rspeedy builds a development bundle with the server's address in its
|
|
67
|
+
/// asset URLs, so most arrive absolute already; anything relative is
|
|
68
|
+
/// relative to the server, as it would be to LynxBundle in a release build.
|
|
69
|
+
func remoteURL(for url: String) -> URL? {
|
|
70
|
+
#if DEBUG
|
|
71
|
+
guard let base else { return nil }
|
|
72
|
+
if url.hasPrefix(base.absoluteString) {
|
|
73
|
+
return URL(string: url)
|
|
74
|
+
}
|
|
75
|
+
if url.hasPrefix("http://") || url.hasPrefix("https://") || url.hasPrefix("data:")
|
|
76
|
+
|| url.hasPrefix("file://")
|
|
77
|
+
{
|
|
78
|
+
return nil
|
|
79
|
+
}
|
|
80
|
+
var path = url
|
|
81
|
+
for prefix in ["asset:///", "asset://"] where path.hasPrefix(prefix) {
|
|
82
|
+
path = String(path.dropFirst(prefix.count))
|
|
83
|
+
break
|
|
84
|
+
}
|
|
85
|
+
while path.hasPrefix("./") { path.removeFirst(2) }
|
|
86
|
+
while path.hasPrefix("/") { path.removeFirst() }
|
|
87
|
+
return URL(string: path, relativeTo: base)?.absoluteURL
|
|
88
|
+
#else
|
|
89
|
+
return nil
|
|
90
|
+
#endif
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// Adds the dev server's modules to the LynxView's config: the WebSocket
|
|
94
|
+
/// that rspeedy's live reload listens on, and the reload it asks for.
|
|
95
|
+
func register(in config: LynxConfig) {
|
|
96
|
+
#if DEBUG
|
|
97
|
+
guard bundle != nil else { return }
|
|
98
|
+
config.register(DevWebSocketModule.self)
|
|
99
|
+
config.register(DevReloadModule.self)
|
|
100
|
+
#endif
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// Gives the dev server the view to show its status over and the
|
|
104
|
+
/// LynxView's reload.
|
|
105
|
+
func attach(to view: UIView, reload: @escaping () -> Void) {
|
|
106
|
+
#if DEBUG
|
|
107
|
+
self.reload = reload
|
|
108
|
+
// A screen over the page, with the message in the middle.
|
|
109
|
+
let screen = UIView()
|
|
110
|
+
screen.backgroundColor = .systemBackground
|
|
111
|
+
screen.isHidden = true
|
|
112
|
+
screen.translatesAutoresizingMaskIntoConstraints = false
|
|
113
|
+
let label = UILabel()
|
|
114
|
+
label.numberOfLines = 0
|
|
115
|
+
label.textAlignment = .center
|
|
116
|
+
label.font = .preferredFont(forTextStyle: .body)
|
|
117
|
+
label.textColor = .label
|
|
118
|
+
label.translatesAutoresizingMaskIntoConstraints = false
|
|
119
|
+
screen.addSubview(label)
|
|
120
|
+
view.addSubview(screen)
|
|
121
|
+
NSLayoutConstraint.activate([
|
|
122
|
+
screen.leadingAnchor.constraint(equalTo: view.leadingAnchor),
|
|
123
|
+
screen.trailingAnchor.constraint(equalTo: view.trailingAnchor),
|
|
124
|
+
screen.topAnchor.constraint(equalTo: view.topAnchor),
|
|
125
|
+
screen.bottomAnchor.constraint(equalTo: view.bottomAnchor),
|
|
126
|
+
label.leadingAnchor.constraint(equalTo: screen.layoutMarginsGuide.leadingAnchor, constant: 8),
|
|
127
|
+
label.trailingAnchor.constraint(equalTo: screen.layoutMarginsGuide.trailingAnchor, constant: -8),
|
|
128
|
+
label.centerYAnchor.constraint(equalTo: screen.centerYAnchor),
|
|
129
|
+
])
|
|
130
|
+
status = label
|
|
131
|
+
statusScreen = screen
|
|
132
|
+
if bundle == nil {
|
|
133
|
+
show(
|
|
134
|
+
"This is the development build of the app, which loads the app from `ng serve`.\n\nRun `ng serve --platform ios` to open it."
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
#endif
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// Reloads the bundle from the dev server, from any thread.
|
|
141
|
+
func reloadBundle() {
|
|
142
|
+
#if DEBUG
|
|
143
|
+
DispatchQueue.main.async { self.reload?() }
|
|
144
|
+
#endif
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/// Called with the outcome of each load. When the bundle itself didn't
|
|
148
|
+
/// load (the server is stopped, or on another network), the app says so
|
|
149
|
+
/// rather than show nothing, and tries again every two seconds.
|
|
150
|
+
func loaded(_ url: String, error: Error?) {
|
|
151
|
+
#if DEBUG
|
|
152
|
+
guard let bundle, url == bundle.absoluteString else { return }
|
|
153
|
+
DispatchQueue.main.async {
|
|
154
|
+
self.retry?.cancel()
|
|
155
|
+
guard let error else {
|
|
156
|
+
self.statusScreen?.isHidden = true
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
self.show(
|
|
160
|
+
"Can't reach the dev server at \(bundle.host ?? "")\(bundle.port.map { ":\($0)" } ?? "").\n\n\(error.localizedDescription)\n\nIs `ng serve --platform ios` running, and is this device on the same network?\(Self.localNetworkHint) Trying again…"
|
|
161
|
+
)
|
|
162
|
+
let retry = DispatchWorkItem { [weak self] in self?.reload?() }
|
|
163
|
+
self.retry = retry
|
|
164
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: retry)
|
|
165
|
+
}
|
|
166
|
+
#endif
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
#if DEBUG
|
|
170
|
+
/// On an iPhone, iOS blocks the dev server until the person allows the
|
|
171
|
+
/// app on the local network, which it asks about the first time. Tapping
|
|
172
|
+
/// Don't Allow leaves the app failing like this, with nothing to say why,
|
|
173
|
+
/// so it says where to turn it back on. The simulator never asks.
|
|
174
|
+
private static var localNetworkHint: String {
|
|
175
|
+
#if targetEnvironment(simulator)
|
|
176
|
+
return ""
|
|
177
|
+
#else
|
|
178
|
+
return
|
|
179
|
+
" If you tapped Don't Allow when iOS asked to find devices on your local network, turn on this app in Settings > Privacy & Security > Local Network."
|
|
180
|
+
#endif
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private func show(_ message: String) {
|
|
184
|
+
guard let status, let statusScreen else { return }
|
|
185
|
+
status.text = message
|
|
186
|
+
statusScreen.isHidden = false
|
|
187
|
+
statusScreen.superview?.bringSubviewToFront(statusScreen)
|
|
188
|
+
}
|
|
189
|
+
#endif
|
|
190
|
+
}
|