@nativue/core 0.18.0 → 0.20.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.
- package/AGENTS.md +14 -2
- package/android/build.gradle.kts +2 -0
- package/android/src/main/java/dev/nativue/Bridge.kt +3 -1
- package/android/src/main/java/dev/nativue/NativueActivity.kt +2 -1
- package/cli/hot-client.js +63 -0
- package/cli/nativue.mjs +90 -10
- package/ios/Bridge.swift +45 -1
- package/package.json +2 -2
- package/src/console.ts +249 -0
- package/src/globals.ts +4 -6
- package/src/prelude.ts +7 -5
- package/src/types.ts +2 -1
package/AGENTS.md
CHANGED
|
@@ -99,7 +99,8 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
99
99
|
`clear`; promise-based, string values. Store objects as JSON. For large data or queries, use
|
|
100
100
|
`@nativue/sqlite`.
|
|
101
101
|
- `fetch`, `XMLHttpRequest`, `Blob`, `FileReader`, `URL`, `URLSearchParams`, timers and `console`
|
|
102
|
-
work as on the web, with no import.
|
|
102
|
+
work as on the web, with no import. Release builds leave out `console.log`, `info`, `debug`,
|
|
103
|
+
`trace`, `table`, `dir` and `group` calls; `warn`, `error` and `assert` stay.
|
|
103
104
|
- Accessibility: `role` and `aria-*` attributes (`aria-label`, `aria-hidden`...) on any component.
|
|
104
105
|
|
|
105
106
|
## Project
|
|
@@ -113,7 +114,18 @@ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `Lay
|
|
|
113
114
|
`@nativue/image-picker` (`ImagePicker.pick({ limit, mediaTypes })`,
|
|
114
115
|
`openCamera({ mediaTypes, videoMaxDuration, videoQuality })`; call `getPendingResult()` on start, for
|
|
115
116
|
what was picked or taken while Android closed the app),
|
|
116
|
-
`@nativue/secure-store` (secrets: `SecureStore.setItem(key, value)`, `getItem`, `deleteItem`)
|
|
117
|
+
`@nativue/secure-store` (secrets: `SecureStore.setItem(key, value)`, `getItem`, `deleteItem`),
|
|
118
|
+
`@nativue/file-system` (`FileSystem.readText`/`writeText`/`download`/`upload` with `file://` URIs from
|
|
119
|
+
`Paths.document` and `Paths.cache`),
|
|
120
|
+
`@nativue/network` (`useNetworkState()`: `{ isConnected, isInternetReachable, type, isExpensive }`, live),
|
|
121
|
+
`@nativue/share` (`Share.share({ text, url, files })` opens the system's share sheet),
|
|
122
|
+
`@nativue/auth-session` (OAuth: `AuthSession.open(url, 'myapp://oauth')` with `createPKCE()`; keep tokens in secure-store),
|
|
123
|
+
`@nativue/biometrics` (`Biometrics.authenticate({ reason })` resolves `{ success }` or `{ success: false, error }`),
|
|
124
|
+
`@nativue/location` (`usePermission(Location.getPermission, Location.requestPermission)`, then
|
|
125
|
+
`Location.getCurrentPosition({ accuracy })` or `Location.watchPosition(options, onPosition)`; iOS texts and
|
|
126
|
+
`background` in `location({...})` from `@nativue/location/plugin`),
|
|
127
|
+
`@nativue/webview` (`<WebView :source="{ uri }" @message>`, sized by its style; a ref has `goBack`, `reload`,
|
|
128
|
+
`evaluateJavaScript(expression)`, `postMessage(data)`; the page posts with `window.nativueWebView.postMessage`).
|
|
117
129
|
A package with native code needs the app
|
|
118
130
|
rebuilt with `npm run ios` or `npm run android`, not just a reload.
|
|
119
131
|
- Notifications: `Notifications.schedule({ title, body, data }, { seconds } | { date } | { hour, minute } | null)`
|
package/android/build.gradle.kts
CHANGED
|
@@ -75,6 +75,8 @@ dependencies {
|
|
|
75
75
|
implementation("androidx.core:core:1.16.0")
|
|
76
76
|
// ComponentActivity: activity-result launchers and new-intent listeners for plugins.
|
|
77
77
|
api("androidx.activity:activity:1.13.0")
|
|
78
|
+
// FragmentActivity, which NativueActivity is, as SDKs ask for: androidx.biometric's prompt, payment sheets.
|
|
79
|
+
api("androidx.fragment:fragment:1.9.1")
|
|
78
80
|
// AppState: whether the app, not one activity, is in front.
|
|
79
81
|
implementation("androidx.lifecycle:lifecycle-process:2.11.1")
|
|
80
82
|
}
|
|
@@ -382,7 +382,7 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
|
|
|
382
382
|
}
|
|
383
383
|
|
|
384
384
|
private fun nativeFunctions(): Map<String, NativeFunction> = buildMap {
|
|
385
|
-
put("log") { arguments -> Log.
|
|
385
|
+
put("log") { arguments -> Log.println(LOG_PRIORITIES[arguments[1]] ?: Log.INFO, TAG, "[JS] ${arguments[0]}") }
|
|
386
386
|
put("reportError") { arguments -> reportError(arguments[0] as String, arguments[1] as String) }
|
|
387
387
|
put("windowSize") { _ -> windowSize }
|
|
388
388
|
put("platform") { _ -> "android" }
|
|
@@ -1168,6 +1168,8 @@ class Bridge(private val activity: ComponentActivity, private val rootView: Root
|
|
|
1168
1168
|
|
|
1169
1169
|
private companion object {
|
|
1170
1170
|
const val TAG = "nativue"
|
|
1171
|
+
/** The console's levels as logcat's; log and info are INFO. */
|
|
1172
|
+
val LOG_PRIORITIES = mapOf("debug" to Log.DEBUG, "warn" to Log.WARN, "error" to Log.ERROR)
|
|
1171
1173
|
const val JAVASCRIPT_STACK_SIZE = 8L * 1024 * 1024
|
|
1172
1174
|
const val SYMBOLICATE_TIMEOUT_MS = 2000
|
|
1173
1175
|
const val RECONNECT_DELAY_MS = 2000L
|
|
@@ -13,10 +13,11 @@ import android.window.OnBackInvokedCallback
|
|
|
13
13
|
import android.window.OnBackInvokedDispatcher
|
|
14
14
|
import androidx.activity.ComponentActivity
|
|
15
15
|
import androidx.annotation.RequiresApi
|
|
16
|
+
import androidx.fragment.app.FragmentActivity
|
|
16
17
|
import com.facebook.soloader.SoLoader
|
|
17
18
|
|
|
18
19
|
/** The app's activity: runs assets/main.bundle.js (or, in debug builds, the dev server's bundle). */
|
|
19
|
-
open class NativueActivity :
|
|
20
|
+
open class NativueActivity : FragmentActivity() {
|
|
20
21
|
private lateinit var bridge: Bridge
|
|
21
22
|
private var lastRKeyTime = 0L
|
|
22
23
|
|
package/cli/hot-client.js
CHANGED
|
@@ -18,6 +18,69 @@
|
|
|
18
18
|
}).catch(() => {})
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
// What the console prints, also in the dev server's terminal: one request at a time, so it keeps
|
|
22
|
+
// the order, with what was printed meanwhile. Each stays well under what the server reads
|
|
23
|
+
// (MAX_POST_LENGTH), escaping included.
|
|
24
|
+
const MAX_LOG_LENGTH = 100_000
|
|
25
|
+
const MAX_BATCH_LENGTH = 300_000
|
|
26
|
+
const pendingLogs = []
|
|
27
|
+
let isSendingLogs = false
|
|
28
|
+
let isCallingFetch = false
|
|
29
|
+
|
|
30
|
+
function nextBatch() {
|
|
31
|
+
let length = 0
|
|
32
|
+
let count = 0
|
|
33
|
+
|
|
34
|
+
while (
|
|
35
|
+
count < pendingLogs.length &&
|
|
36
|
+
length + pendingLogs[count].text.length <= MAX_BATCH_LENGTH
|
|
37
|
+
) {
|
|
38
|
+
length += pendingLogs[count].text.length
|
|
39
|
+
count++
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return pendingLogs.splice(0, count)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// An app that wraps fetch to log its requests would log this one, and send that log, forever: what's
|
|
46
|
+
// printed while it's called stays on the device.
|
|
47
|
+
function postLogs(entries) {
|
|
48
|
+
isCallingFetch = true
|
|
49
|
+
try {
|
|
50
|
+
return fetch(`${serverURL}/log`, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
body: JSON.stringify({ platform: __native.platform(), entries }),
|
|
53
|
+
})
|
|
54
|
+
} finally {
|
|
55
|
+
isCallingFetch = false
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sendLogs() {
|
|
60
|
+
if (isSendingLogs || pendingLogs.length === 0) return
|
|
61
|
+
|
|
62
|
+
isSendingLogs = true
|
|
63
|
+
Promise.resolve()
|
|
64
|
+
.then(() => postLogs(nextBatch()))
|
|
65
|
+
.catch(() => {})
|
|
66
|
+
.finally(() => {
|
|
67
|
+
isSendingLogs = false
|
|
68
|
+
sendLogs()
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
globalThis.__nativueOnLog = (level, text) => {
|
|
73
|
+
if (isCallingFetch) return
|
|
74
|
+
|
|
75
|
+
const hidden = text.length - MAX_LOG_LENGTH
|
|
76
|
+
|
|
77
|
+
pendingLogs.push({
|
|
78
|
+
level,
|
|
79
|
+
text: hidden > 0 ? `${text.slice(0, MAX_LOG_LENGTH)}... ${hidden} more characters` : text,
|
|
80
|
+
})
|
|
81
|
+
sendLogs()
|
|
82
|
+
}
|
|
83
|
+
|
|
21
84
|
function requestReload(reason) {
|
|
22
85
|
if (isReloadPending) return
|
|
23
86
|
|
package/cli/nativue.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, watch }
|
|
|
19
19
|
import { randomUUID } from 'node:crypto'
|
|
20
20
|
import { relative } from 'node:path'
|
|
21
21
|
import { fileURLToPath } from 'node:url'
|
|
22
|
+
import { styleText } from 'node:util'
|
|
22
23
|
import { compileToBytecode } from './hermes.mjs'
|
|
23
24
|
import { hotPrelude } from './hot-prelude.mjs'
|
|
24
25
|
import { resolvePlugins } from './plugins.mjs'
|
|
@@ -27,12 +28,27 @@ import { runOnAndroid, runOnIOS } from './run.mjs'
|
|
|
27
28
|
import { createSymbolicator, framedFiles } from './symbolicate.mjs'
|
|
28
29
|
|
|
29
30
|
const PORT = 40836 // 0x9F84, from #0E9F84, the nativue green
|
|
30
|
-
const
|
|
31
|
+
const MAX_POST_LENGTH = 1_000_000 // characters, of what the app posts: a stack, console output
|
|
32
|
+
const LOG_COLORS = { info: 'blue', debug: 'gray', warn: 'yellow', error: 'red' }
|
|
33
|
+
const PLATFORM_WIDTH = 'android'.length
|
|
31
34
|
const BUNDLE_DIRECTORY = 'ios/App'
|
|
32
35
|
const BUNDLE_PATH = `${BUNDLE_DIRECTORY}/main.bundle.js`
|
|
33
36
|
const ANDROID_ASSETS_DIRECTORY = 'android/app/src/main/assets'
|
|
34
37
|
const KEEPALIVE_INTERVAL_MS = 15000
|
|
35
38
|
const UNANSWERED_UPDATE_TIMEOUT_MS = 10000
|
|
39
|
+
// What a release build leaves out: logs slow the JavaScript thread and land in the device's log, which
|
|
40
|
+
// Android keeps readable. warn, error and assert stay, for problems in the field.
|
|
41
|
+
const DEVELOPMENT_CONSOLE_METHODS = [
|
|
42
|
+
'log',
|
|
43
|
+
'info',
|
|
44
|
+
'debug',
|
|
45
|
+
'trace',
|
|
46
|
+
'table',
|
|
47
|
+
'dir',
|
|
48
|
+
'group',
|
|
49
|
+
'groupCollapsed',
|
|
50
|
+
'groupEnd',
|
|
51
|
+
]
|
|
36
52
|
|
|
37
53
|
const NATIVE_COMPONENT_TAGS = [
|
|
38
54
|
'View',
|
|
@@ -162,6 +178,19 @@ const APP_VITE_PLUGINS = [
|
|
|
162
178
|
...appPlugins.flatMap((plugin) => plugin.vite ?? []),
|
|
163
179
|
]
|
|
164
180
|
|
|
181
|
+
/**
|
|
182
|
+
* Each method an empty function the minifier then drops with its call, even where the call's value is
|
|
183
|
+
* used (`onPress: () => console.log(item)`). Arguments that do something still run.
|
|
184
|
+
*/
|
|
185
|
+
function withoutDevelopmentLogs() {
|
|
186
|
+
return Object.fromEntries(
|
|
187
|
+
DEVELOPMENT_CONSOLE_METHODS.flatMap((method) => [
|
|
188
|
+
[`console.${method}`, '(() => {})'],
|
|
189
|
+
[`globalThis.console.${method}`, '(() => {})'],
|
|
190
|
+
]),
|
|
191
|
+
)
|
|
192
|
+
}
|
|
193
|
+
|
|
165
194
|
function viteConfig({ mode, plugins = [] }) {
|
|
166
195
|
// Vite reads the mode from NODE_ENV: development builds keep each component's file (for errors).
|
|
167
196
|
process.env.NODE_ENV = mode
|
|
@@ -196,7 +225,10 @@ function viteConfig({ mode, plugins = [] }) {
|
|
|
196
225
|
{ find: /^@\//, replacement: `${process.cwd()}/src/` },
|
|
197
226
|
],
|
|
198
227
|
},
|
|
199
|
-
define: {
|
|
228
|
+
define: {
|
|
229
|
+
'process.env.NODE_ENV': JSON.stringify(mode),
|
|
230
|
+
...(mode === 'production' ? withoutDevelopmentLogs() : {}),
|
|
231
|
+
},
|
|
200
232
|
build: {
|
|
201
233
|
lib: {
|
|
202
234
|
entry: frameworkPath('src/entry.ts'),
|
|
@@ -241,7 +273,13 @@ function vueHotUpdates(sendToApps) {
|
|
|
241
273
|
// runtime is a Vite client: the dev server speaks Vite's protocol for it and relays updates over SSE.
|
|
242
274
|
async function dev() {
|
|
243
275
|
const connectedApps = new Set()
|
|
244
|
-
|
|
276
|
+
// A source map, read once until the code changes: every message to the apps is a reload, an update
|
|
277
|
+
// or a keepalive.
|
|
278
|
+
const sourceMapsByFile = new Map()
|
|
279
|
+
const sendToApps = (message) => {
|
|
280
|
+
sourceMapsByFile.clear()
|
|
281
|
+
connectedApps.forEach((response) => response.write(message))
|
|
282
|
+
}
|
|
245
283
|
const config = viteConfig({
|
|
246
284
|
mode: 'development',
|
|
247
285
|
plugins: [vueHotUpdates((payload) => sendToApps(`data: hot ${JSON.stringify(payload)}\n\n`))],
|
|
@@ -373,19 +411,50 @@ async function dev() {
|
|
|
373
411
|
return sourceMap.ok ? { sourceMap: await sourceMap.json(), directory: BUNDLE_DIRECTORY } : null
|
|
374
412
|
}
|
|
375
413
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
414
|
+
function cachedSourceMapOf(file) {
|
|
415
|
+
if (!sourceMapsByFile.has(file)) {
|
|
416
|
+
const sourceMap = sourceMapOf(file)
|
|
417
|
+
|
|
418
|
+
sourceMapsByFile.set(file, sourceMap)
|
|
419
|
+
sourceMap.catch(() => sourceMapsByFile.delete(file))
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
return sourceMapsByFile.get(file)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** The text with its stack frames pointing at the app's files. */
|
|
426
|
+
async function symbolicate(text) {
|
|
379
427
|
const files = [...framedFiles(text)]
|
|
380
|
-
|
|
381
|
-
|
|
428
|
+
|
|
429
|
+
if (files.length === 0) return text
|
|
430
|
+
|
|
431
|
+
const sourceMaps = await Promise.all(files.map(cachedSourceMapOf))
|
|
432
|
+
const symbolicateFrames = createSymbolicator(
|
|
382
433
|
Object.fromEntries(
|
|
383
434
|
files.map((file, index) => [file, sourceMaps[index]]).filter(([, map]) => map),
|
|
384
435
|
),
|
|
385
436
|
)
|
|
386
437
|
|
|
438
|
+
return symbolicateFrames(text)
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// The app posts an error's stack; it gets it back pointing at the app's files.
|
|
442
|
+
async function handleSymbolicate(request, response) {
|
|
443
|
+
const text = await symbolicate(await readBody(request))
|
|
444
|
+
|
|
387
445
|
response.writeHead(200, { 'Content-Type': 'text/plain' })
|
|
388
|
-
response.end(
|
|
446
|
+
response.end(text)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// What the app's console prints (hot-client.js).
|
|
450
|
+
async function handleLog(request, response) {
|
|
451
|
+
const { platform, entries } = JSON.parse(await readBody(request))
|
|
452
|
+
|
|
453
|
+
// Without a source map (Vite restarting), a stack prints as the app sent it.
|
|
454
|
+
for (const { level, text } of entries) {
|
|
455
|
+
printLog(platform, level, await symbolicate(text).catch(() => text))
|
|
456
|
+
}
|
|
457
|
+
response.writeHead(204).end()
|
|
389
458
|
}
|
|
390
459
|
|
|
391
460
|
const routes = {
|
|
@@ -393,6 +462,7 @@ async function dev() {
|
|
|
393
462
|
'/bundle.js': handleBundle,
|
|
394
463
|
'/hot': handleHotMessage,
|
|
395
464
|
'/symbolicate': handleSymbolicate,
|
|
465
|
+
'/log': handleLog,
|
|
396
466
|
}
|
|
397
467
|
|
|
398
468
|
http
|
|
@@ -435,11 +505,21 @@ async function dev() {
|
|
|
435
505
|
setInterval(() => sendToApps(':\n\n'), KEEPALIVE_INTERVAL_MS)
|
|
436
506
|
}
|
|
437
507
|
|
|
508
|
+
/** Each line after the first starts under the first's text, past the platform. */
|
|
509
|
+
function printLog(platform, level, text) {
|
|
510
|
+
const color = LOG_COLORS[level]
|
|
511
|
+
const aligned = text.replaceAll('\n', `\n${' '.repeat(PLATFORM_WIDTH + 1)}`)
|
|
512
|
+
|
|
513
|
+
console.log(
|
|
514
|
+
`${styleText('dim', platform.padEnd(PLATFORM_WIDTH))} ${color ? styleText(color, aligned) : aligned}`,
|
|
515
|
+
)
|
|
516
|
+
}
|
|
517
|
+
|
|
438
518
|
async function readBody(request) {
|
|
439
519
|
let text = ''
|
|
440
520
|
for await (const chunk of request) {
|
|
441
521
|
text += chunk
|
|
442
|
-
if (text.length >
|
|
522
|
+
if (text.length > MAX_POST_LENGTH) throw new Error('body too long')
|
|
443
523
|
}
|
|
444
524
|
|
|
445
525
|
return text
|
package/ios/Bridge.swift
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import UIKit
|
|
2
2
|
import JavaScriptRuntime
|
|
3
|
+
import os
|
|
3
4
|
import yoga
|
|
4
5
|
|
|
5
6
|
/// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
|
|
@@ -345,7 +346,7 @@ final class Bridge {
|
|
|
345
346
|
}
|
|
346
347
|
}
|
|
347
348
|
|
|
348
|
-
define("log") { arguments in
|
|
349
|
+
define("log") { arguments in logFromJavaScript(string(arguments[0]), level: string(arguments[1])) }
|
|
349
350
|
|
|
350
351
|
define("reportError") { [unowned self] arguments in
|
|
351
352
|
reportError(message: string(arguments[0]), details: string(arguments[1]))
|
|
@@ -1108,6 +1109,49 @@ private func double(_ argument: Any) -> Double {
|
|
|
1108
1109
|
(argument as? NSNumber)?.doubleValue ?? 0
|
|
1109
1110
|
}
|
|
1110
1111
|
|
|
1112
|
+
private let javaScriptLogger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "nativue", category: "JavaScript")
|
|
1113
|
+
/// The system log cuts a message at 1 KB: a longer one goes in parts of this many bytes, in order.
|
|
1114
|
+
private let maxLogPartBytes = 1000
|
|
1115
|
+
|
|
1116
|
+
/// The console's levels as the system log's, which Xcode and Console.app show and filter. Release builds
|
|
1117
|
+
/// keep the text private, as anyone with the device can read the system log.
|
|
1118
|
+
private func logFromJavaScript(_ message: String, level: String) {
|
|
1119
|
+
let type: OSLogType = switch level {
|
|
1120
|
+
case "debug": .debug
|
|
1121
|
+
case "info": .info
|
|
1122
|
+
case "warn", "error": .error
|
|
1123
|
+
default: .default
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
for part in logParts(of: message) {
|
|
1127
|
+
#if DEBUG
|
|
1128
|
+
javaScriptLogger.log(level: type, "\(part, privacy: .public)")
|
|
1129
|
+
#else
|
|
1130
|
+
javaScriptLogger.log(level: type, "\(part, privacy: .private)")
|
|
1131
|
+
#endif
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
private func logParts(of message: String) -> [String] {
|
|
1136
|
+
var parts: [String] = []
|
|
1137
|
+
var part = ""
|
|
1138
|
+
var partBytes = 0
|
|
1139
|
+
|
|
1140
|
+
for character in message {
|
|
1141
|
+
let characterBytes = character.utf8.count
|
|
1142
|
+
|
|
1143
|
+
if partBytes + characterBytes > maxLogPartBytes {
|
|
1144
|
+
parts.append(part)
|
|
1145
|
+
part = ""
|
|
1146
|
+
partBytes = 0
|
|
1147
|
+
}
|
|
1148
|
+
part.append(character)
|
|
1149
|
+
partBytes += characterBytes
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
return parts + [part]
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1111
1155
|
private func string(_ argument: Any) -> String {
|
|
1112
1156
|
argument as? String ?? ""
|
|
1113
1157
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativue/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "Vue rendering real native views on iOS and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"scripts": {
|
|
35
|
-
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/gradients.test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
|
|
35
|
+
"test": "(cd ../../examples/demo && nativue build) && node test/test.mjs && node test/gradients.test.mjs && node test/console.test.mjs && node test/native-events.test.mjs && node test/hermes.test.mjs && node test/prebuild.test.mjs",
|
|
36
36
|
"typecheck": "vue-tsc"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
package/src/console.ts
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// console as on the web, for engines without one: values formatted as Node and browsers do, %
|
|
2
|
+
// substitutions, table, group and assert. The rest of the web's console does nothing, so libraries
|
|
3
|
+
// calling it keep working.
|
|
4
|
+
|
|
5
|
+
export type LogLevel = 'log' | 'info' | 'debug' | 'warn' | 'error'
|
|
6
|
+
|
|
7
|
+
/** How deep nested objects show; deeper ones read [Object] and [Array], as in Node. */
|
|
8
|
+
const MAX_DEPTH = 2
|
|
9
|
+
/** An object or array longer than this on one line shows one entry per line. */
|
|
10
|
+
const MAX_LINE_LENGTH = 72
|
|
11
|
+
/** Past this, an array, Map, Set or object shows '... N more items', and a string '... N more characters', as in Node. */
|
|
12
|
+
const MAX_ITEMS = 100
|
|
13
|
+
const MAX_STRING_LENGTH = 10_000
|
|
14
|
+
const INDENT = ' '
|
|
15
|
+
const SUBSTITUTION = /%[sdifoOc%]/g
|
|
16
|
+
|
|
17
|
+
export function createConsole(write: (level: LogLevel, text: string) => void) {
|
|
18
|
+
let groupDepth = 0
|
|
19
|
+
|
|
20
|
+
function emit(level: LogLevel, text: string) {
|
|
21
|
+
write(level, text.replace(/^/gm, INDENT.repeat(groupDepth)))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const printer =
|
|
25
|
+
(level: LogLevel) =>
|
|
26
|
+
(...values: unknown[]) =>
|
|
27
|
+
emit(level, formatValues(values))
|
|
28
|
+
|
|
29
|
+
function group(...labels: unknown[]) {
|
|
30
|
+
if (labels.length > 0) emit('log', formatValues(labels))
|
|
31
|
+
groupDepth++
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Typed to take what the web's console takes: console.time('label') type-checks.
|
|
35
|
+
const doNothing: (...values: unknown[]) => void = () => {}
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
log: printer('log'),
|
|
39
|
+
info: printer('info'),
|
|
40
|
+
debug: printer('debug'),
|
|
41
|
+
warn: printer('warn'),
|
|
42
|
+
error: printer('error'),
|
|
43
|
+
|
|
44
|
+
trace(...values: unknown[]) {
|
|
45
|
+
// The stack's first lines are the Error's and this function's frame.
|
|
46
|
+
const stack = (new Error().stack ?? '').split('\n').slice(2).join('\n')
|
|
47
|
+
|
|
48
|
+
emit('log', `Trace: ${formatValues(values)}\n${stack}`)
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
table(data: unknown, columns?: string[]) {
|
|
52
|
+
if (typeof data !== 'object' || data === null) return emit('log', formatValues([data]))
|
|
53
|
+
|
|
54
|
+
emit('log', formatTable(data, columns))
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
group,
|
|
58
|
+
// A terminal can't fold a group: it shows open.
|
|
59
|
+
groupCollapsed: group,
|
|
60
|
+
|
|
61
|
+
groupEnd() {
|
|
62
|
+
groupDepth = Math.max(0, groupDepth - 1)
|
|
63
|
+
},
|
|
64
|
+
|
|
65
|
+
assert(condition?: unknown, ...values: unknown[]) {
|
|
66
|
+
if (condition) return
|
|
67
|
+
|
|
68
|
+
emit(
|
|
69
|
+
'error',
|
|
70
|
+
values.length > 0 ? `Assertion failed: ${formatValues(values)}` : 'Assertion failed',
|
|
71
|
+
)
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
clear: doNothing,
|
|
75
|
+
count: doNothing,
|
|
76
|
+
countReset: doNothing,
|
|
77
|
+
dir: doNothing,
|
|
78
|
+
dirxml: doNothing,
|
|
79
|
+
profile: doNothing,
|
|
80
|
+
profileEnd: doNothing,
|
|
81
|
+
time: doNothing,
|
|
82
|
+
timeEnd: doNothing,
|
|
83
|
+
timeLog: doNothing,
|
|
84
|
+
timeStamp: doNothing,
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Strings as they are, the rest inspected; a first string with % takes the next values in. */
|
|
89
|
+
export function formatValues(values: unknown[]): string {
|
|
90
|
+
const [first, ...rest] = values
|
|
91
|
+
|
|
92
|
+
if (typeof first !== 'string' || !first.includes('%')) return values.map(formatValue).join(' ')
|
|
93
|
+
|
|
94
|
+
const remaining = [...rest]
|
|
95
|
+
const substituted = first.replace(SUBSTITUTION, (token) => {
|
|
96
|
+
if (token === '%%') return '%'
|
|
97
|
+
if (remaining.length === 0) return token
|
|
98
|
+
|
|
99
|
+
return substitute(token, remaining.shift())
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
return [substituted, ...remaining.map(formatValue)].join(' ')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function substitute(token: string, value: unknown) {
|
|
106
|
+
switch (token) {
|
|
107
|
+
case '%s':
|
|
108
|
+
return formatValue(value)
|
|
109
|
+
case '%d':
|
|
110
|
+
return String(Number(asNumber(value)))
|
|
111
|
+
case '%i':
|
|
112
|
+
return String(parseInt(String(asNumber(value)), 10))
|
|
113
|
+
case '%f':
|
|
114
|
+
return String(parseFloat(String(asNumber(value))))
|
|
115
|
+
case '%c':
|
|
116
|
+
return '' // CSS, which a terminal can't apply
|
|
117
|
+
default:
|
|
118
|
+
return inspect(value)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Objects and symbols, which can't be turned into numbers (or would throw), are NaN. */
|
|
123
|
+
function asNumber(value: unknown) {
|
|
124
|
+
return typeof value === 'symbol' || (typeof value === 'object' && value !== null) ? NaN : value
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function formatValue(value: unknown) {
|
|
128
|
+
return typeof value === 'string' ? value : inspect(value)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function inspect(value: unknown, depth = 0, seen = new Set<object>()): string {
|
|
132
|
+
switch (typeof value) {
|
|
133
|
+
case 'string':
|
|
134
|
+
return `'${truncate(value).replaceAll("'", "\\'")}'`
|
|
135
|
+
case 'bigint':
|
|
136
|
+
return `${value}n`
|
|
137
|
+
case 'symbol':
|
|
138
|
+
return value.toString()
|
|
139
|
+
case 'function':
|
|
140
|
+
return `[Function: ${value.name || '(anonymous)'}]`
|
|
141
|
+
case 'object':
|
|
142
|
+
return value === null ? 'null' : inspectObject(value, depth, seen)
|
|
143
|
+
default:
|
|
144
|
+
return String(value)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function inspectObject(value: object, depth: number, seen: Set<object>): string {
|
|
149
|
+
if (value instanceof Error) return value.stack ?? `${value.name}: ${value.message}`
|
|
150
|
+
if (value instanceof Date) return isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString()
|
|
151
|
+
if (value instanceof RegExp) return String(value)
|
|
152
|
+
if (seen.has(value)) return '[Circular]'
|
|
153
|
+
if (depth > MAX_DEPTH) return Array.isArray(value) ? '[Array]' : '[Object]'
|
|
154
|
+
|
|
155
|
+
seen.add(value)
|
|
156
|
+
try {
|
|
157
|
+
const inspectNested = (nested: unknown) => inspect(nested, depth + 1, seen)
|
|
158
|
+
|
|
159
|
+
if (Array.isArray(value)) return wrap('[', formatItems(value, inspectNested), ']')
|
|
160
|
+
if (value instanceof Map) {
|
|
161
|
+
const entries = formatItems(
|
|
162
|
+
[...value],
|
|
163
|
+
([key, item]) => `${inspectNested(key)} => ${inspectNested(item)}`,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return wrap(`Map(${value.size}) {`, entries, '}')
|
|
167
|
+
}
|
|
168
|
+
if (value instanceof Set) {
|
|
169
|
+
return wrap(`Set(${value.size}) {`, formatItems([...value], inspectNested), '}')
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const entries = formatItems(
|
|
173
|
+
Object.entries(value),
|
|
174
|
+
([key, item]) => `${formatKey(key)}: ${inspectNested(item)}`,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
return wrap(`${className(value)}{`, entries, '}')
|
|
178
|
+
} finally {
|
|
179
|
+
seen.delete(value)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function formatItems<Item>(items: Item[], format: (item: Item) => string) {
|
|
184
|
+
const shown = items.slice(0, MAX_ITEMS).map(format)
|
|
185
|
+
const hidden = items.length - shown.length
|
|
186
|
+
|
|
187
|
+
return hidden > 0 ? [...shown, `... ${hidden} more item${hidden === 1 ? '' : 's'}`] : shown
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function truncate(text: string) {
|
|
191
|
+
const hidden = text.length - MAX_STRING_LENGTH
|
|
192
|
+
|
|
193
|
+
return hidden > 0 ? `${text.slice(0, MAX_STRING_LENGTH)}... ${hidden} more characters` : text
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 'Point ' for a class's instance, nothing for a plain object. */
|
|
197
|
+
function className(value: object) {
|
|
198
|
+
const name = Object.getPrototypeOf(value)?.constructor?.name
|
|
199
|
+
|
|
200
|
+
return name && name !== 'Object' ? `${name} ` : ''
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function formatKey(key: string) {
|
|
204
|
+
return /^[A-Za-z_$][\w$]*$/.test(key) ? key : inspect(key)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function wrap(open: string, entries: string[], close: string) {
|
|
208
|
+
if (entries.length === 0) return `${open}${close}`
|
|
209
|
+
|
|
210
|
+
const oneLine = `${open} ${entries.join(', ')} ${close}`
|
|
211
|
+
|
|
212
|
+
if (oneLine.length <= MAX_LINE_LENGTH && !oneLine.includes('\n')) return oneLine
|
|
213
|
+
|
|
214
|
+
return `${open}\n${entries.map((entry) => entry.replace(/^/gm, INDENT)).join(',\n')}\n${close}`
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A row per entry, a column per key of the entries that are objects, and Values for the others. */
|
|
218
|
+
export function formatTable(data: object, columns?: string[]) {
|
|
219
|
+
const rows = data instanceof Map ? [...data] : Object.entries(data)
|
|
220
|
+
const keys = columns ?? [
|
|
221
|
+
...new Set(rows.flatMap(([, row]) => (isTableRow(row) ? Object.keys(row) : []))),
|
|
222
|
+
]
|
|
223
|
+
const hasValues = rows.some(([, row]) => !isTableRow(row))
|
|
224
|
+
const header = ['(index)', ...keys, ...(hasValues ? ['Values'] : [])]
|
|
225
|
+
const body = rows.map(([index, row]) => [
|
|
226
|
+
String(index),
|
|
227
|
+
...keys.map((key) => (isTableRow(row) && key in row ? inspect(row[key], MAX_DEPTH) : '')),
|
|
228
|
+
...(hasValues ? [isTableRow(row) ? '' : inspect(row, MAX_DEPTH)] : []),
|
|
229
|
+
])
|
|
230
|
+
const widths = header.map((title, column) =>
|
|
231
|
+
Math.max(title.length, ...body.map((cells) => cells[column].length)),
|
|
232
|
+
)
|
|
233
|
+
const line = (left: string, middle: string, right: string) =>
|
|
234
|
+
left + widths.map((width) => '─'.repeat(width + 2)).join(middle) + right
|
|
235
|
+
const row = (cells: string[]) =>
|
|
236
|
+
`│ ${cells.map((cell, column) => cell.padEnd(widths[column])).join(' │ ')} │`
|
|
237
|
+
|
|
238
|
+
return [
|
|
239
|
+
line('┌', '┬', '┐'),
|
|
240
|
+
row(header),
|
|
241
|
+
line('├', '┼', '┤'),
|
|
242
|
+
...body.map(row),
|
|
243
|
+
line('└', '┴', '┘'),
|
|
244
|
+
].join('\n')
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function isTableRow(value: unknown): value is Record<string, unknown> {
|
|
248
|
+
return typeof value === 'object' && value !== null
|
|
249
|
+
}
|
package/src/globals.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// What the JavaScript engine has globally: the bridge, the hooks native calls into, and the web APIs
|
|
2
2
|
// prelude.ts (timers, console) and fetch.ts provide. No DOM.
|
|
3
3
|
import type { ColorScheme, WindowSize } from './appearance'
|
|
4
|
+
import type { createConsole, LogLevel } from './console'
|
|
4
5
|
import type { LayoutEvent, NativeModule, NetworkEventPayloads } from './types'
|
|
5
6
|
|
|
6
7
|
declare global {
|
|
@@ -28,12 +29,9 @@ declare global {
|
|
|
28
29
|
/** From the runtime (not __native): an object whose garbage collection releases the blob's bytes. */
|
|
29
30
|
var __blobCollector: ((blobId: string) => object) | undefined
|
|
30
31
|
|
|
31
|
-
var console:
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
warn(...values: unknown[]): void
|
|
35
|
-
error(...values: unknown[]): void
|
|
36
|
-
}
|
|
32
|
+
var console: ReturnType<typeof createConsole>
|
|
33
|
+
/** Development: the hot client's, sending what the console prints to the dev server. */
|
|
34
|
+
var __nativueOnLog: ((level: LogLevel, text: string) => void) | undefined
|
|
37
35
|
|
|
38
36
|
function setTimeout<Args extends unknown[]>(
|
|
39
37
|
callback: (...args: Args) => void,
|
package/src/prelude.ts
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
1
|
// The web APIs JavaScript engines don't have, built on the native bridge: console and timers. Runs
|
|
2
2
|
// first, before any other module. Engines (and Node, in tests) that have them keep theirs.
|
|
3
|
+
import { createConsole } from './console'
|
|
4
|
+
|
|
3
5
|
const timerCallbacks = new Map<number, () => void>()
|
|
4
6
|
let nextTimerId = 1
|
|
5
7
|
|
|
6
|
-
function log(...values: unknown[]) {
|
|
7
|
-
__native.log(values.map(String).join(' '))
|
|
8
|
-
}
|
|
9
|
-
|
|
10
8
|
function armTimer(timerId: number, callback: () => void, delay: number) {
|
|
11
9
|
timerCallbacks.set(timerId, callback)
|
|
12
10
|
__native.setTimer(timerId, delay)
|
|
@@ -16,7 +14,11 @@ function millisecondsOf(delay: number | undefined) {
|
|
|
16
14
|
return Math.max(0, Math.round(delay ?? 0))
|
|
17
15
|
}
|
|
18
16
|
|
|
19
|
-
|
|
17
|
+
// In development, the dev server's hot client also prints it in the terminal.
|
|
18
|
+
globalThis.console ??= createConsole((level, text) => {
|
|
19
|
+
__native.log(text, level)
|
|
20
|
+
globalThis.__nativueOnLog?.(level, text)
|
|
21
|
+
})
|
|
20
22
|
|
|
21
23
|
globalThis.setTimeout ??= (callback, delay, ...args) => {
|
|
22
24
|
const timerId = nextTimerId++
|
package/src/types.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Types shared by the framework and apps: styles, native events and the bridge to the native side.
|
|
2
2
|
import type { AnimatedNode } from './animated'
|
|
3
|
+
import type { LogLevel } from './console'
|
|
3
4
|
|
|
4
5
|
type Dimension = number | 'auto' | `${number}%`
|
|
5
6
|
type Edge = '' | 'Top' | 'Right' | 'Bottom' | 'Left' | 'Horizontal' | 'Vertical' | 'Start' | 'End'
|
|
@@ -128,7 +129,7 @@ export interface LayoutAnimationConfig {
|
|
|
128
129
|
|
|
129
130
|
/** Functions the native side exposes as globalThis.__native (see Bridge.swift). */
|
|
130
131
|
export interface NativeModule {
|
|
131
|
-
log(message: string): void
|
|
132
|
+
log(message: string, level: LogLevel): void
|
|
132
133
|
reportError(message: string, details: string): void
|
|
133
134
|
windowSize(): { width: number; height: number }
|
|
134
135
|
platform(): 'ios' | 'android'
|