@blotch/angular-lynx-native 22.2.21 → 22.2.22
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 +10 -6
- package/dist/ios/iphone.d.ts +1 -1
- package/dist/ios/iphone.d.ts.map +1 -1
- package/dist/ios/iphone.js +4 -1
- 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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// The two native modules rspeedy's live reload needs, in the development
|
|
2
|
+
// build only (see DevServer.swift). Lynx Explorer has them from Lynx DevTool,
|
|
3
|
+
// which the shell doesn't link: the dev server's client, which rspeedy puts
|
|
4
|
+
// in every development bundle, talks to the server over
|
|
5
|
+
// `NativeModules.LynxWebSocketModule` (through @lynx-js/websocket) and reloads
|
|
6
|
+
// the page with `NativeModules.LynxDevToolSetModule.invokeCdp`, a DevTool
|
|
7
|
+
// protocol `Page.reload`. These answer to the same names and calls, so the
|
|
8
|
+
// bundle runs here as it does in Lynx Explorer.
|
|
9
|
+
#if DEBUG
|
|
10
|
+
import Foundation
|
|
11
|
+
import Lynx
|
|
12
|
+
|
|
13
|
+
/// `NativeModules.LynxWebSocketModule`, as Lynx DevTool's
|
|
14
|
+
/// (LynxWebSocketModule.mm): `connect`, `send`, `ping` and `close`, each
|
|
15
|
+
/// with the socket's ID, and the `websocketOpen`, `websocketMessage`,
|
|
16
|
+
/// `websocketClosed` and `websocketFailed` global events @lynx-js/websocket
|
|
17
|
+
/// listens for.
|
|
18
|
+
final class DevWebSocketModule: NSObject, LynxContextModule, URLSessionWebSocketDelegate {
|
|
19
|
+
static var name: String { "LynxWebSocketModule" }
|
|
20
|
+
|
|
21
|
+
static var methodLookup: [String: String] {
|
|
22
|
+
[
|
|
23
|
+
"connect": NSStringFromSelector(#selector(connect(_:protocols:options:socketID:))),
|
|
24
|
+
"send": NSStringFromSelector(#selector(send(_:socketID:))),
|
|
25
|
+
"ping": NSStringFromSelector(#selector(ping(_:))),
|
|
26
|
+
"close": NSStringFromSelector(#selector(close(_:reason:socketID:))),
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private weak var context: LynxContext?
|
|
31
|
+
private var sockets: [Int: URLSessionWebSocketTask] = [:]
|
|
32
|
+
private let lock = NSLock()
|
|
33
|
+
private lazy var session = URLSession(
|
|
34
|
+
configuration: .default, delegate: self, delegateQueue: nil)
|
|
35
|
+
|
|
36
|
+
override init() {
|
|
37
|
+
super.init()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Swift can't import an optional initializer as optional, so Lynx's
|
|
41
|
+
// initWithParam: and initWithLynxContext:WithParam: are required here.
|
|
42
|
+
init(param: Any) {
|
|
43
|
+
super.init()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
init(lynxContext context: LynxContext) {
|
|
47
|
+
self.context = context
|
|
48
|
+
super.init()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
init(lynxContext context: LynxContext, withParam param: Any) {
|
|
52
|
+
self.context = context
|
|
53
|
+
super.init()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
func destroy() {
|
|
57
|
+
lock.lock()
|
|
58
|
+
let open = Array(sockets.values)
|
|
59
|
+
sockets.removeAll()
|
|
60
|
+
lock.unlock()
|
|
61
|
+
open.forEach { $0.cancel(with: .goingAway, reason: nil) }
|
|
62
|
+
session.invalidateAndCancel()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
@objc func connect(
|
|
66
|
+
_ url: String, protocols: [String]?, options: [String: Any]?, socketID: Double
|
|
67
|
+
) {
|
|
68
|
+
let id = Int(socketID)
|
|
69
|
+
// The address the bundle was built with may not be the one this
|
|
70
|
+
// device reaches the server at.
|
|
71
|
+
let address = DevServer.shared.remoteURL(for: url.replacingOccurrences(
|
|
72
|
+
of: "^ws", with: "http", options: .regularExpression))
|
|
73
|
+
.map { $0.absoluteString.replacingOccurrences(
|
|
74
|
+
of: "^http", with: "ws", options: .regularExpression) } ?? url
|
|
75
|
+
guard let target = URL(string: address) else {
|
|
76
|
+
send("websocketFailed", ["id": id, "message": "\(url) is not a valid URL."])
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
// With an empty list, URLSession still sends an empty
|
|
80
|
+
// Sec-WebSocket-Protocol header, which the dev server rejects.
|
|
81
|
+
let names = (protocols ?? []).filter { !$0.isEmpty }
|
|
82
|
+
let task =
|
|
83
|
+
names.isEmpty
|
|
84
|
+
? session.webSocketTask(with: target)
|
|
85
|
+
: session.webSocketTask(with: target, protocols: names)
|
|
86
|
+
task.taskDescription = String(id)
|
|
87
|
+
lock.lock()
|
|
88
|
+
sockets[id] = task
|
|
89
|
+
lock.unlock()
|
|
90
|
+
task.resume()
|
|
91
|
+
receive(task, id: id)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
@objc func send(_ message: String, socketID: Double) {
|
|
95
|
+
socket(socketID)?.send(.string(message)) { [weak self] error in
|
|
96
|
+
if let error {
|
|
97
|
+
self?.send("websocketFailed", ["id": Int(socketID), "message": error.localizedDescription])
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
@objc func ping(_ socketID: Double) {
|
|
103
|
+
socket(socketID)?.sendPing { _ in }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
@objc func close(_ code: Double, reason: String, socketID: Double) {
|
|
107
|
+
let id = Int(socketID)
|
|
108
|
+
lock.lock()
|
|
109
|
+
let task = sockets.removeValue(forKey: id)
|
|
110
|
+
lock.unlock()
|
|
111
|
+
task?.cancel(
|
|
112
|
+
with: URLSessionWebSocketTask.CloseCode(rawValue: Int(code)) ?? .normalClosure,
|
|
113
|
+
reason: reason.data(using: .utf8))
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private func socket(_ socketID: Double) -> URLSessionWebSocketTask? {
|
|
117
|
+
lock.lock()
|
|
118
|
+
defer { lock.unlock() }
|
|
119
|
+
return sockets[Int(socketID)]
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// Reads one message, sends it on, and waits for the next, for as long as
|
|
123
|
+
/// the socket is open.
|
|
124
|
+
private func receive(_ task: URLSessionWebSocketTask, id: Int) {
|
|
125
|
+
task.receive { [weak self] result in
|
|
126
|
+
guard let self else { return }
|
|
127
|
+
switch result {
|
|
128
|
+
case .success(.string(let text)):
|
|
129
|
+
self.send("websocketMessage", ["id": id, "type": "text", "data": text])
|
|
130
|
+
case .success(.data(let data)):
|
|
131
|
+
self.send(
|
|
132
|
+
"websocketMessage", ["id": id, "type": "binary", "data": data.base64EncodedString()])
|
|
133
|
+
case .success:
|
|
134
|
+
break
|
|
135
|
+
case .failure:
|
|
136
|
+
// The delegate reports why the socket ended.
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
self.receive(task, id: id)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private func send(_ event: String, _ params: [String: Any]) {
|
|
144
|
+
context?.sendGlobalEvent(event, withParams: [params])
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
func urlSession(
|
|
148
|
+
_ session: URLSession, webSocketTask: URLSessionWebSocketTask,
|
|
149
|
+
didOpenWithProtocol protocolName: String?
|
|
150
|
+
) {
|
|
151
|
+
guard let id = webSocketTask.taskDescription.flatMap(Int.init) else { return }
|
|
152
|
+
send("websocketOpen", ["id": id, "protocol": protocolName ?? ""])
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
func urlSession(
|
|
156
|
+
_ session: URLSession, webSocketTask: URLSessionWebSocketTask,
|
|
157
|
+
didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?
|
|
158
|
+
) {
|
|
159
|
+
guard let id = webSocketTask.taskDescription.flatMap(Int.init) else { return }
|
|
160
|
+
lock.lock()
|
|
161
|
+
sockets.removeValue(forKey: id)
|
|
162
|
+
lock.unlock()
|
|
163
|
+
send(
|
|
164
|
+
"websocketClosed",
|
|
165
|
+
[
|
|
166
|
+
"id": id, "code": closeCode.rawValue,
|
|
167
|
+
"reason": reason.flatMap { String(data: $0, encoding: .utf8) } ?? "",
|
|
168
|
+
])
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// The connection failed or dropped (the server stopped): the dev
|
|
172
|
+
/// server's client then tries again, with a growing delay.
|
|
173
|
+
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
|
|
174
|
+
{
|
|
175
|
+
guard let error, let id = task.taskDescription.flatMap(Int.init) else { return }
|
|
176
|
+
lock.lock()
|
|
177
|
+
let known = sockets.removeValue(forKey: id) != nil
|
|
178
|
+
lock.unlock()
|
|
179
|
+
guard known else { return }
|
|
180
|
+
send("websocketFailed", ["id": id, "message": error.localizedDescription])
|
|
181
|
+
send("websocketClosed", ["id": id, "code": 1006, "reason": error.localizedDescription])
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/// `NativeModules.LynxDevToolSetModule`, as far as rspeedy's live reload
|
|
186
|
+
/// uses Lynx DevTool's: `invokeCdp` with a `Page.reload`, which loads the
|
|
187
|
+
/// bundle from the dev server again, as Lynx DevTool's LynxPageReloadHelper
|
|
188
|
+
/// does. It answers any other DevTool method with an error.
|
|
189
|
+
final class DevReloadModule: NSObject, LynxModule {
|
|
190
|
+
static var name: String { "LynxDevToolSetModule" }
|
|
191
|
+
|
|
192
|
+
static var methodLookup: [String: String] {
|
|
193
|
+
["invokeCdp": NSStringFromSelector(#selector(invokeCdp(_:callback:)))]
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
override init() {
|
|
197
|
+
super.init()
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
init(param: Any) {
|
|
201
|
+
super.init()
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
@objc func invokeCdp(_ message: String, callback: LynxCallbackBlock?) {
|
|
205
|
+
let request =
|
|
206
|
+
(try? JSONSerialization.jsonObject(with: Data(message.utf8))) as? [String: Any] ?? [:]
|
|
207
|
+
let id = request["id"] ?? 0
|
|
208
|
+
let method = request["method"] as? String ?? ""
|
|
209
|
+
let reply: [String: Any]
|
|
210
|
+
if method == "Page.reload" {
|
|
211
|
+
DevServer.shared.reloadBundle()
|
|
212
|
+
reply = ["id": id, "result": [String: Any]()]
|
|
213
|
+
} else {
|
|
214
|
+
reply = [
|
|
215
|
+
"id": id,
|
|
216
|
+
"error": ["code": -32601, "message": "\(method) needs Lynx DevTool, which this app doesn't have."],
|
|
217
|
+
]
|
|
218
|
+
}
|
|
219
|
+
let data = (try? JSONSerialization.data(withJSONObject: reply)) ?? Data()
|
|
220
|
+
callback?(String(data: data, encoding: .utf8) ?? "{}")
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
#endif
|