@g9tm/lynxcontrols-pilot 0.0.0-stage → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +159 -2
  2. package/catalog/cards/G9PilotHost.md +16 -0
  3. package/catalog/cards/G9PilotMask.md +10 -0
  4. package/catalog/cards/G9PilotPanel.md +10 -0
  5. package/catalog/catalog.json +420 -0
  6. package/catalog/index.md +7 -0
  7. package/check/cli.mjs +5 -0
  8. package/check/index.mjs +137 -0
  9. package/check/index.test.mjs +180 -0
  10. package/config/cli.mjs +31 -0
  11. package/config/index.d.ts +62 -0
  12. package/config/index.mjs +380 -0
  13. package/config/index.test.mjs +406 -0
  14. package/dist/.tsbuildinfo +1 -0
  15. package/dist/anchors.d.ts +39 -0
  16. package/dist/anchors.d.ts.map +1 -0
  17. package/dist/anchors.jsx +103 -0
  18. package/dist/bridge.d.ts +4 -0
  19. package/dist/bridge.d.ts.map +1 -0
  20. package/dist/bridge.jsx +143 -0
  21. package/dist/busy.d.ts +4 -0
  22. package/dist/busy.d.ts.map +1 -0
  23. package/dist/busy.jsx +43 -0
  24. package/dist/commands.d.ts +24 -0
  25. package/dist/commands.d.ts.map +1 -0
  26. package/dist/commands.jsx +286 -0
  27. package/dist/consent.d.ts +51 -0
  28. package/dist/consent.d.ts.map +1 -0
  29. package/dist/consent.jsx +131 -0
  30. package/dist/explore.d.ts +36 -0
  31. package/dist/explore.d.ts.map +1 -0
  32. package/dist/explore.jsx +133 -0
  33. package/dist/flags.d.ts +69 -0
  34. package/dist/flags.d.ts.map +1 -0
  35. package/dist/flags.jsx +81 -0
  36. package/dist/host-core.d.ts +36 -0
  37. package/dist/host-core.d.ts.map +1 -0
  38. package/dist/host-core.jsx +90 -0
  39. package/dist/host-sink.d.ts +43 -0
  40. package/dist/host-sink.d.ts.map +1 -0
  41. package/dist/host-sink.jsx +87 -0
  42. package/dist/index-marks.d.ts +33 -0
  43. package/dist/index-marks.d.ts.map +1 -0
  44. package/dist/index-marks.jsx +40 -0
  45. package/dist/index-observe.d.ts +17 -0
  46. package/dist/index-observe.d.ts.map +1 -0
  47. package/dist/index-observe.jsx +14 -0
  48. package/dist/index.d.ts +18 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.jsx +11 -0
  51. package/dist/info.d.ts +10 -0
  52. package/dist/info.d.ts.map +1 -0
  53. package/dist/info.jsx +9 -0
  54. package/dist/kit.d.ts +67 -0
  55. package/dist/kit.d.ts.map +1 -0
  56. package/dist/kit.jsx +1 -0
  57. package/dist/layer.d.ts +4 -0
  58. package/dist/layer.d.ts.map +1 -0
  59. package/dist/layer.jsx +10 -0
  60. package/dist/layers.d.ts +4 -0
  61. package/dist/layers.d.ts.map +1 -0
  62. package/dist/layers.jsx +146 -0
  63. package/dist/mask.d.ts +20 -0
  64. package/dist/mask.d.ts.map +1 -0
  65. package/dist/mask.jsx +35 -0
  66. package/dist/net.d.ts +17 -0
  67. package/dist/net.d.ts.map +1 -0
  68. package/dist/net.jsx +60 -0
  69. package/dist/observe.d.ts +99 -0
  70. package/dist/observe.d.ts.map +1 -0
  71. package/dist/observe.jsx +194 -0
  72. package/dist/off.d.ts +45 -0
  73. package/dist/off.d.ts.map +1 -0
  74. package/dist/off.jsx +81 -0
  75. package/dist/otlp.d.ts +61 -0
  76. package/dist/otlp.d.ts.map +1 -0
  77. package/dist/otlp.jsx +141 -0
  78. package/dist/panel.d.ts +13 -0
  79. package/dist/panel.d.ts.map +1 -0
  80. package/dist/panel.jsx +182 -0
  81. package/dist/session.d.ts +42 -0
  82. package/dist/session.d.ts.map +1 -0
  83. package/dist/session.jsx +115 -0
  84. package/dist/types.d.ts +47 -0
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/types.jsx +1 -0
  87. package/dist/watch.d.ts +17 -0
  88. package/dist/watch.d.ts.map +1 -0
  89. package/dist/watch.jsx +165 -0
  90. package/doctor/cli.mjs +5 -0
  91. package/doctor/index.mjs +214 -0
  92. package/doctor/index.test.mjs +174 -0
  93. package/gradle/g9pilot.app.gradle +55 -0
  94. package/gradle/g9pilot.settings.gradle +27 -0
  95. package/ios/g9pilot.rb +47 -0
  96. package/package.json +66 -4
  97. package/rspeedy/index.d.ts +40 -0
  98. package/rspeedy/index.mjs +100 -0
  99. package/rspeedy/index.test.mjs +192 -0
package/dist/watch.jsx ADDED
@@ -0,0 +1,165 @@
1
+ import { dispatch, emit, installBlackbox, latinDigitsInPersian, recordLog, registerCommand, registerScreenCheck } from "@g9tm/app-pilot";
2
+ import { installLynxOracles, registerUiCommands } from "@g9tm/app-pilot-lynx";
3
+ import { g9Popups } from "@g9tm/lynxcontrols/popup";
4
+ import { BLACKBOX, ORACLES, PROFILE, SCREEN, SETTINGS, VITALS } from "./flags.jsx";
5
+ import { kit, textFor } from "./host-core.jsx";
6
+ import { installHostSink } from "./host-sink.jsx";
7
+ import { lynxControlsLayers } from "./layers.jsx";
8
+ import { autoReports, createFindingsBuffer, summarize } from "./observe.jsx";
9
+ import { sendOtlp, toOtlpLogs } from "./otlp.jsx";
10
+ let findings = null;
11
+ function g9PilotFindings() {
12
+ return findings;
13
+ }
14
+ const LOG_LEVEL = {
15
+ trace: 'debug',
16
+ debug: 'debug',
17
+ information: 'info',
18
+ warning: 'warn',
19
+ error: 'error',
20
+ critical: 'error'
21
+ };
22
+ const FIELD_TYPES = new Set([
23
+ 'Entry',
24
+ 'Editor',
25
+ 'SearchBar',
26
+ 'Picker',
27
+ 'DatePicker',
28
+ 'TimePicker'
29
+ ]);
30
+ const latinDigitsOutsideFields = (nodes, context)=>latinDigitsInPersian(nodes.filter((n)=>!FIELD_TYPES.has(n.type)), context.language);
31
+ function installScreen(ctx) {
32
+ var _p_notes;
33
+ const p = ctx.props();
34
+ return registerUiCommands({
35
+ layers: lynxControlsLayers(kit),
36
+ ...p.bottomBarPrefix ? {
37
+ bottomBarPrefix: p.bottomBarPrefix
38
+ } : {},
39
+ notes: [
40
+ 'G9LynxControls app: every control with an id is a target; g9.where / g9.go reach any place.',
41
+ ...null != (_p_notes = p.notes) ? _p_notes : []
42
+ ]
43
+ });
44
+ }
45
+ async function askReportConsent(ctx) {
46
+ const lang = ctx.language();
47
+ const ask = ctx.props().askConsent;
48
+ try {
49
+ if (ask) return await ask({
50
+ kid: 'report',
51
+ reading: false
52
+ });
53
+ return await g9Popups().showConfirm(textFor(lang, 'گزارش خطاهای این دستگاه برای پشتیبانی فرستاده شود؟', 'Send this device’s problem report to support?'), {
54
+ title: textFor(lang, 'گزارش خطا', 'Problem report'),
55
+ okText: textFor(lang, 'بفرست', 'Send'),
56
+ cancelText: textFor(lang, 'نه', 'No')
57
+ });
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+ function installWatch(ctx) {
63
+ const offs = [];
64
+ if (BLACKBOX) {
65
+ offs.push(installBlackbox({
66
+ console: false,
67
+ fetch: false
68
+ }));
69
+ offs.push(ctx.core.diagnostics.onLog((e)=>{
70
+ var _LOG_LEVEL_e_level, _e_source;
71
+ return recordLog(null != (_LOG_LEVEL_e_level = LOG_LEVEL[e.level]) ? _LOG_LEVEL_e_level : 'info', null != (_e_source = e.source) ? _e_source : 'g9', e.message);
72
+ }));
73
+ offs.push(ctx.core.diagnostics.onOperationFailed((r)=>{
74
+ var _r_userMessage, _ref;
75
+ var _r_exceptions;
76
+ return recordLog('error', r.source, null != (_r_userMessage = r.userMessage) ? _r_userMessage : '', null != (_ref = null == (_r_exceptions = r.exceptions) ? void 0 : _r_exceptions[0]) ? _ref : '');
77
+ }));
78
+ }
79
+ if (SCREEN) offs.push(installScreen(ctx));
80
+ if (ORACLES) {
81
+ var _SETTINGS_observe_rules_i18nlatinDigits, _r_auto;
82
+ const rules = {
83
+ ...SETTINGS.observe.rules
84
+ };
85
+ const digits = (null != (_SETTINGS_observe_rules_i18nlatinDigits = SETTINGS.observe.rules["i18n.latinDigits"]) ? _SETTINGS_observe_rules_i18nlatinDigits : 'auto') === 'auto';
86
+ if (digits) rules['i18n.latinDigits'] = 'off';
87
+ offs.push(installLynxOracles({
88
+ rules,
89
+ language: ctx.language,
90
+ ...VITALS ? {} : {
91
+ vitals: false
92
+ }
93
+ }));
94
+ if (digits) offs.push(registerScreenCheck('g9.latinDigits', latinDigitsOutsideFields));
95
+ const buffer = createFindingsBuffer({
96
+ settings: SETTINGS.observe,
97
+ preferences: ctx.core.preferences
98
+ });
99
+ findings = buffer;
100
+ offs.push(()=>{
101
+ buffer.stop();
102
+ findings = null;
103
+ });
104
+ offs.push(installHostSink(buffer, {
105
+ dispatch: dispatch
106
+ }));
107
+ const r = SETTINGS.observe.report;
108
+ const meta = {
109
+ profile: PROFILE,
110
+ environment: SETTINGS.environment
111
+ };
112
+ const deliver = async (report)=>{
113
+ var _r_endpoint, _r_service;
114
+ var _ctx_props_onReport, _ctx_props;
115
+ const send = 'local' !== r.via && 'never' !== r.consent && ('build' === r.consent || await askReportConsent(ctx));
116
+ if (!send) return false;
117
+ if ('diagnostic' === r.via) await (null == (_ctx_props_onReport = (_ctx_props = ctx.props()).onReport) ? void 0 : _ctx_props_onReport.call(_ctx_props, report));
118
+ if ('hub' === r.via) emit('g9.report', report);
119
+ if ('otlp' === r.via) return (await sendOtlp(null != (_r_endpoint = r.endpoint) ? _r_endpoint : '', toOtlpLogs(report, {
120
+ service: null != (_r_service = r.service) ? _r_service : null
121
+ }))).ok;
122
+ return true;
123
+ };
124
+ const every = (null != (_r_auto = r.auto) ? _r_auto : 0) * 1000;
125
+ if (every > 0) offs.push(autoReports(buffer, every, async ()=>void await deliver(await buffer.report(meta))));
126
+ const read = async (command, args = {})=>{
127
+ const a = await dispatch({
128
+ id: `g9.summary.${command}`,
129
+ command,
130
+ args,
131
+ kid: 'self-g9.summary',
132
+ scopes: [
133
+ '*'
134
+ ]
135
+ });
136
+ return a.ok ? a.result : null;
137
+ };
138
+ offs.push(registerCommand('g9.summary', async ()=>summarize(meta, buffer.list(), {
139
+ vitals: await read('perf.vitals'),
140
+ traces: await read('trace.list'),
141
+ log: await read('log.tail', {
142
+ limit: 200
143
+ })
144
+ }), {
145
+ scope: 'observe',
146
+ mutating: false,
147
+ description: 'What the watch saw, in one glance: findings by rule and severity, stalls and memory, failure traces, log levels.'
148
+ }));
149
+ offs.push(registerCommand('g9.report', async ()=>{
150
+ const report = await buffer.report(meta);
151
+ return {
152
+ ...report,
153
+ sent: await deliver(report)
154
+ };
155
+ }, {
156
+ scope: 'observe',
157
+ mutating: true,
158
+ description: 'The findings, traces and log tail this device kept, as one report (sent where the build says).'
159
+ }));
160
+ }
161
+ return ()=>{
162
+ for (const off of offs.reverse())off();
163
+ };
164
+ }
165
+ export { askReportConsent, g9PilotFindings, installScreen, installWatch, latinDigitsOutsideFields };
package/doctor/cli.mjs ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // The bin of g9pilot-doctor (doctor/index.mjs holds the logic and its tests).
3
+ import { main } from './index.mjs';
4
+
5
+ process.exitCode = main(process.argv.slice(2));
@@ -0,0 +1,214 @@
1
+ // g9pilot-doctor: is this app wired for G9AppPilot the way @g9tm/lynxcontrols-pilot expects? One pass over the app's
2
+ // folder, each finding a line (ok · warn · FAIL), the exit code 1 on any FAIL — for a developer after a change, and for
3
+ // CI before a release. It reads; it never writes.
4
+ // the configuration g9pilot.config.json found, valid, every environment resolves (keys, key files, short-lived keys)
5
+ // the bundler lynx.config.* adds pluginG9Pilot()
6
+ // Android the settings and app Gradle helpers applied; the host's src/pilot/on and src/pilot/off twins
7
+ // iOS the Podfile requires the helper
8
+ // the imports the app's code imports the packages' main entries only (a subpath can instantiate a module twice)
9
+ // the keys a private key never in the app's folder outside an ignored one
10
+ // the artifacts every dist folder with a pilot-receipt.json holds exactly what its profile says (g9pilot-check)
11
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
12
+ import { dirname, join, relative as rel } from 'node:path';
13
+ import { inspect, verdict } from '../check/index.mjs';
14
+ import { G9PilotConfigError, resolvePilotConfig } from '../config/index.mjs';
15
+
16
+ const DAY = 86_400_000;
17
+ /** A path inside the app, written the same on every platform. */
18
+ const relative = (from, to) => rel(from, to).split(/[\\/]/).join('/');
19
+ const SKIP = new Set(['node_modules', '.git', 'build', '.gradle', 'Pods', 'DerivedData', '.cxx']);
20
+
21
+ const read = (file) => {
22
+ try {
23
+ return readFileSync(file, 'utf8');
24
+ } catch {
25
+ return null;
26
+ }
27
+ };
28
+ const firstOf = (dir, names) => names.map((n) => join(dir, n)).find((f) => existsSync(f)) ?? null;
29
+
30
+ /** Every file under `dir` whose name passes `keep` (the folders of builds and dependencies skipped). */
31
+ function walk(dir, keep, out = []) {
32
+ let entries = [];
33
+ try {
34
+ entries = readdirSync(dir);
35
+ } catch {
36
+ return out;
37
+ }
38
+ for (const name of entries) {
39
+ if (SKIP.has(name) || name.startsWith('dist')) continue;
40
+ const path = join(dir, name);
41
+ let st;
42
+ try {
43
+ st = statSync(path);
44
+ } catch {
45
+ continue;
46
+ }
47
+ if (st.isDirectory()) walk(path, keep, out);
48
+ else if (keep(name)) out.push(path);
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** Whether `path` (inside the app) is covered by a line of the app's .gitignore (the simple forms only). */
54
+ function ignored(app, path) {
55
+ const rules = (read(join(app, '.gitignore')) ?? '')
56
+ .split(/\r?\n/)
57
+ .map((l) => l.trim())
58
+ .filter((l) => l && !l.startsWith('#'));
59
+ const at = relative(app, path);
60
+ return rules.some((r) => {
61
+ const rule = r.replace(/^\//, '').replace(/\/$/, '');
62
+ if (rule.endsWith('*')) return at.startsWith(rule.slice(0, -1));
63
+ return at === rule || at.startsWith(`${rule}/`);
64
+ });
65
+ }
66
+
67
+ /** The pilot imports the app's code may make: the main entries and the build-time subpaths. */
68
+ const SUBPATH =
69
+ /from\s+['"](@g9tm\/app-pilot(?:-[a-z]+)?\/[^'"]+|@g9tm\/lynxcontrols-pilot\/(?!rspeedy|config|check)[^'"]+)['"]/g;
70
+
71
+ /**
72
+ * Examines the app at `app`; → [{level: 'ok' | 'warn' | 'fail', area, message}]. `now` is the clock short-lived keys are
73
+ * judged against.
74
+ */
75
+ export function examine(app, { now = Date.now() } = {}) {
76
+ const out = [];
77
+ const ok = (area, message) => out.push({ level: 'ok', area, message });
78
+ const warn = (area, message) => out.push({ level: 'warn', area, message });
79
+ const bad = (area, message) => out.push({ level: 'fail', area, message });
80
+
81
+ // the configuration
82
+ const file = join(app, 'g9pilot.config.json');
83
+ let config = null;
84
+ if (!existsSync(file))
85
+ warn('config', 'no g9pilot.config.json: every build is off (no environment can carry G9AppPilot)');
86
+ else {
87
+ try {
88
+ config = JSON.parse(readFileSync(file, 'utf8'));
89
+ } catch (e) {
90
+ bad('config', `g9pilot.config.json is not valid JSON: ${e.message}`);
91
+ }
92
+ }
93
+ const resolved = [];
94
+ if (config) {
95
+ const names = Object.keys(config.environments ?? {});
96
+ if (names.length === 0) warn('config', 'g9pilot.config.json names no environment');
97
+ for (const name of names) {
98
+ try {
99
+ const r = resolvePilotConfig(config, name, { baseDir: app });
100
+ resolved.push(r);
101
+ ok('config', `${name}: ${r.profile} (${r.distribution})${r.modules.bridge ? `, ${r.keys.length} key(s)` : ''}`);
102
+ for (const k of r.keys) {
103
+ if (typeof k.notAfter !== 'number') continue;
104
+ if (k.notAfter <= now)
105
+ warn('keys', `${name}: the key "${k.kid}" expired on ${new Date(k.notAfter).toISOString()}`);
106
+ else if (k.notAfter - now < 7 * DAY)
107
+ warn('keys', `${name}: the key "${k.kid}" expires on ${new Date(k.notAfter).toISOString()}`);
108
+ }
109
+ } catch (e) {
110
+ if (!(e instanceof G9PilotConfigError)) throw e;
111
+ bad('config', `${name}: ${e.message.replace(/^g9pilot\.config: /, '')}`);
112
+ }
113
+ }
114
+ }
115
+ const bridged = resolved.some((r) => r.modules.bridge);
116
+
117
+ // the bundler
118
+ const lynxConfig = firstOf(app, ['lynx.config.ts', 'lynx.config.mts', 'lynx.config.mjs', 'lynx.config.js']);
119
+ if (!lynxConfig) warn('rspeedy', 'no lynx.config.* here');
120
+ else if (/pluginG9Pilot\s*\(/.test(read(lynxConfig) ?? ''))
121
+ ok('rspeedy', `${relative(app, lynxConfig)} adds pluginG9Pilot()`);
122
+ else
123
+ bad('rspeedy', `${relative(app, lynxConfig)} does not add pluginG9Pilot(): every build resolves the empty entry`);
124
+
125
+ // Android
126
+ const android = join(app, 'android');
127
+ if (existsSync(android)) {
128
+ const settings = firstOf(android, ['settings.gradle.kts', 'settings.gradle']);
129
+ const appGradle = firstOf(join(android, 'app'), ['build.gradle.kts', 'build.gradle']);
130
+ if (settings && /g9pilot\.settings\.gradle/.test(read(settings) ?? ''))
131
+ ok('android', 'settings apply g9pilot.settings.gradle');
132
+ else bad('android', 'settings.gradle(.kts) does not apply g9pilot.settings.gradle');
133
+ if (appGradle && /g9pilot\.app\.gradle/.test(read(appGradle) ?? ''))
134
+ ok('android', 'app applies g9pilot.app.gradle');
135
+ else bad('android', 'app/build.gradle(.kts) does not apply g9pilot.app.gradle');
136
+ const twins = ['on', 'off'].filter((t) => existsSync(join(android, 'app', 'src', 'pilot', t)));
137
+ if (twins.length === 2) ok('android', 'the host keeps both twins (src/pilot/on, src/pilot/off)');
138
+ else if (bridged) bad('android', `the host lacks src/pilot/${['on', 'off'].find((t) => !twins.includes(t))}`);
139
+ else warn('android', 'no src/pilot twins: fine while no environment carries the bridge');
140
+ }
141
+
142
+ // iOS
143
+ const podfile = join(app, 'ios', 'Podfile');
144
+ if (existsSync(podfile)) {
145
+ if (/lynxcontrols-pilot\/ios\/g9pilot/.test(read(podfile) ?? ''))
146
+ ok('ios', 'the Podfile requires the g9pilot helper');
147
+ else if (bridged) bad('ios', 'the Podfile does not require @g9tm/lynxcontrols-pilot/ios/g9pilot');
148
+ else warn('ios', 'the Podfile does not require the g9pilot helper (no environment carries the bridge)');
149
+ }
150
+
151
+ // the imports
152
+ const sources = walk(join(app, 'src'), (n) => /\.(?:[cm]?[jt]sx?)$/.test(n));
153
+ let subpaths = 0;
154
+ for (const f of sources) {
155
+ for (const m of (read(f) ?? '').matchAll(SUBPATH)) {
156
+ subpaths++;
157
+ bad(
158
+ 'imports',
159
+ `${relative(app, f)} imports ${m[1]}: import the main entry (a subpath can instantiate a module twice)`,
160
+ );
161
+ }
162
+ }
163
+ if (subpaths === 0) ok('imports', `${sources.length} source file(s) import only the main entries`);
164
+
165
+ // the keys: a private key inside the app folder must sit in an ignored folder
166
+ const keyFiles = walk(app, (n) => /\.(?:pem|key|p8|pk8)$/.test(n) || n.endsWith('.private'));
167
+ let exposed = 0;
168
+ for (const f of keyFiles) {
169
+ if (!/PRIVATE KEY/.test(read(f) ?? '')) continue;
170
+ if (ignored(app, f) || ignored(app, dirname(f))) continue;
171
+ exposed++;
172
+ bad('keys', `${relative(app, f)} holds a private key and .gitignore does not cover it`);
173
+ }
174
+ if (exposed === 0) ok('keys', 'no private key outside an ignored folder');
175
+
176
+ // the artifacts
177
+ for (const name of readdirSafe(app).filter((n) => n.startsWith('dist'))) {
178
+ const dir = join(app, name);
179
+ if (!existsSync(join(dir, 'pilot-receipt.json'))) continue;
180
+ const found = inspect(dir);
181
+ const profile = found.receipt?.profile;
182
+ const problems = profile
183
+ ? verdict(found, profile, { devtool: found.receipt.native?.devtool === true })
184
+ : ['no profile in the receipt'];
185
+ if (problems.length) for (const p of problems) bad('artifact', `${name}: ${p}`);
186
+ else ok('artifact', `${name}: holds what ${profile} says`);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ function readdirSafe(dir) {
192
+ try {
193
+ return readdirSync(dir);
194
+ } catch {
195
+ return [];
196
+ }
197
+ }
198
+
199
+ /** The command line: `g9pilot-doctor [app folder] [--json]` (doctor/cli.mjs is the bin). */
200
+ export function main(args, { log = console.log, now } = {}) {
201
+ const app = args.find((a) => !a.startsWith('--')) ?? process.cwd();
202
+ if (!existsSync(app)) {
203
+ log(`g9pilot-doctor: ${app} does not exist`);
204
+ return 2;
205
+ }
206
+ const findings = examine(app, now === undefined ? {} : { now });
207
+ if (args.includes('--json')) log(JSON.stringify(findings, null, 2));
208
+ else
209
+ for (const f of findings)
210
+ log(`${f.level === 'ok' ? 'ok ' : f.level === 'warn' ? 'warn' : 'FAIL'} ${f.area.padEnd(8)} ${f.message}`);
211
+ const failed = findings.filter((f) => f.level === 'fail').length;
212
+ if (!args.includes('--json')) log(failed ? `g9pilot-doctor: ${failed} problem(s)` : 'g9pilot-doctor: healthy');
213
+ return failed ? 1 : 0;
214
+ }
@@ -0,0 +1,174 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import test from 'node:test';
6
+ import { examine, main } from './index.mjs';
7
+
8
+ const KEY = { kid: 'qa', publicKey: 'MFkw-public', scopes: ['*'] };
9
+ const NOW = Date.parse('2026-11-19T00:00:00Z');
10
+
11
+ function withApp(files, run) {
12
+ const dir = mkdtempSync(join(tmpdir(), 'g9pilot-doctor-'));
13
+ try {
14
+ for (const [path, content] of Object.entries(files)) {
15
+ if (content === undefined) continue;
16
+ mkdirSync(dirname(join(dir, path)), { recursive: true });
17
+ writeFileSync(join(dir, path), typeof content === 'string' ? content : JSON.stringify(content));
18
+ }
19
+ return run(dir);
20
+ } finally {
21
+ rmSync(dir, { recursive: true, force: true });
22
+ }
23
+ }
24
+ const levels = (findings, area) => findings.filter((f) => f.area === area).map((f) => `${f.level}: ${f.message}`);
25
+
26
+ const HEALTHY = {
27
+ 'g9pilot.config.json': {
28
+ keys: [KEY],
29
+ environments: { store: { profile: 'off', distribution: 'store' }, qa: { profile: 'full' } },
30
+ },
31
+ 'lynx.config.ts': 'plugins: [pluginG9Pilot()]',
32
+ 'android/settings.gradle.kts': 'apply(from = "x/g9pilot.settings.gradle")',
33
+ 'android/app/build.gradle.kts': 'apply(from = "x/g9pilot.app.gradle")',
34
+ 'android/app/src/pilot/on/java/Host.kt': '',
35
+ 'android/app/src/pilot/off/java/Host.kt': '',
36
+ 'ios/Podfile': "require_relative '../node_modules/@g9tm/lynxcontrols-pilot/ios/g9pilot'",
37
+ 'src/app.tsx':
38
+ "import { G9PilotHost } from '@g9tm/lynxcontrols-pilot';\nimport { pluginG9Pilot } from '@g9tm/lynxcontrols-pilot/rspeedy';",
39
+ '.gitignore': '.keys/\n',
40
+ '.keys/qa.pem': '-----BEGIN PRIVATE KEY-----',
41
+ };
42
+
43
+ test('a healthy app: every area ok, exit 0', () =>
44
+ withApp(HEALTHY, (dir) => {
45
+ const f = examine(dir, { now: NOW });
46
+ assert.deepEqual(
47
+ f.filter((x) => x.level !== 'ok'),
48
+ [],
49
+ );
50
+ assert.deepEqual(levels(f, 'config'), ['ok: store: off (store)', 'ok: qa: full (test), 1 key(s)']);
51
+ const lines = [];
52
+ assert.equal(main([dir], { log: (l) => lines.push(l), now: NOW }), 0);
53
+ assert.equal(lines.at(-1), 'g9pilot-doctor: healthy');
54
+ const json = [];
55
+ assert.equal(main([dir, '--json'], { log: (l) => json.push(l), now: NOW }), 0);
56
+ assert.equal(JSON.parse(json[0]).length, f.length);
57
+ }));
58
+
59
+ test('every wiring mistake is a FAIL with what to do', () =>
60
+ withApp(
61
+ {
62
+ ...HEALTHY,
63
+ 'g9pilot.config.json': {
64
+ keys: [KEY],
65
+ environments: { bad: { profile: 'full', distribution: 'store' }, qa: { profile: 'full' } },
66
+ },
67
+ 'lynx.config.ts': 'plugins: []',
68
+ 'android/settings.gradle.kts': '',
69
+ 'android/app/build.gradle.kts': '',
70
+ 'android/app/src/pilot/off/java/Host.kt': undefined,
71
+ 'ios/Podfile': '',
72
+ 'src/deep/x.ts':
73
+ "import { x } from '@g9tm/app-pilot/blackbox';\nimport y from '@g9tm/lynxcontrols-pilot/src/mask';",
74
+ 'secrets/admin.pem': '-----BEGIN PRIVATE KEY-----',
75
+ },
76
+ (dir) => {
77
+ rmSync(join(dir, 'android/app/src/pilot/off'), { recursive: true, force: true });
78
+ const f = examine(dir, { now: NOW });
79
+ assert.match(levels(f, 'config')[0], /^fail: bad: .*store/);
80
+ assert.match(levels(f, 'rspeedy')[0], /^fail: .*does not add pluginG9Pilot/);
81
+ assert.deepEqual(
82
+ levels(f, 'android').map((l) => l.slice(0, 4)),
83
+ ['fail', 'fail', 'fail'],
84
+ );
85
+ assert.match(levels(f, 'android')[2], /lacks src\/pilot\/off/);
86
+ assert.match(levels(f, 'ios')[0], /^fail/);
87
+ assert.equal(levels(f, 'imports').length, 2);
88
+ assert.match(levels(f, 'imports')[0], /@g9tm\/app-pilot\/blackbox/);
89
+ assert.deepEqual(levels(f, 'keys'), [
90
+ 'fail: secrets/admin.pem holds a private key and .gitignore does not cover it',
91
+ ]);
92
+ const lines = [];
93
+ assert.equal(main([dir], { log: (l) => lines.push(l) }), 1);
94
+ assert.match(lines.at(-1), /problem\(s\)/);
95
+ },
96
+ ));
97
+
98
+ test('without the bridge the twins and the Podfile are only warnings; no config, no lynx config, bad JSON', () => {
99
+ withApp(
100
+ {
101
+ 'g9pilot.config.json': { environments: { store: { profile: 'off', distribution: 'store' } } },
102
+ 'android/settings.gradle.kts': 'g9pilot.settings.gradle',
103
+ 'android/app/build.gradle': 'g9pilot.app.gradle',
104
+ 'ios/Podfile': '',
105
+ 'src/a.js': '',
106
+ },
107
+ (dir) => {
108
+ const f = examine(dir, { now: NOW });
109
+ assert.match(levels(f, 'android')[2], /^warn: no src\/pilot twins/);
110
+ assert.match(levels(f, 'ios')[0], /^warn/);
111
+ assert.match(levels(f, 'rspeedy')[0], /^warn: no lynx.config/);
112
+ },
113
+ );
114
+ withApp({ 'src/a.ts': '' }, (dir) => {
115
+ assert.match(levels(examine(dir), 'config')[0], /^warn: no g9pilot.config.json/);
116
+ });
117
+ withApp({ 'g9pilot.config.json': '{ nope' }, (dir) => {
118
+ assert.match(levels(examine(dir), 'config')[0], /^fail: g9pilot.config.json is not valid JSON/);
119
+ });
120
+ withApp({ 'g9pilot.config.json': {} }, (dir) => {
121
+ assert.match(levels(examine(dir), 'config')[0], /^warn: .*names no environment/);
122
+ });
123
+ });
124
+
125
+ test('short-lived keys: expired and expiring soon are warnings', () =>
126
+ withApp(
127
+ {
128
+ ...HEALTHY,
129
+ 'g9pilot.config.json': {
130
+ keys: [
131
+ { ...KEY, kid: 'old', notAfter: '2026-11-01T00:00:00Z' },
132
+ { ...KEY, kid: 'soon', notAfter: '2026-11-21T00:00:00Z' },
133
+ { ...KEY, kid: 'far', notAfter: '2027-06-01T00:00:00Z' },
134
+ ],
135
+ environments: { qa: { profile: 'full' } },
136
+ },
137
+ },
138
+ (dir) => {
139
+ assert.deepEqual(levels(examine(dir, { now: NOW }), 'keys').slice(0, 2), [
140
+ 'warn: qa: the key "old" expired on 2026-11-01T00:00:00.000Z',
141
+ 'warn: qa: the key "soon" expires on 2026-11-21T00:00:00.000Z',
142
+ ]);
143
+ },
144
+ ));
145
+
146
+ test('artifacts: a dist folder whose bundle holds more than its receipt says fails', () =>
147
+ withApp(
148
+ {
149
+ ...HEALTHY,
150
+ 'dist-store/pilot-receipt.json': { profile: 'off', native: { bridge: false, devtool: false } },
151
+ 'dist-store/main.lynx.bundle': 'pilot.respond pilot.dispatch g9.pilot',
152
+ 'dist-ok/pilot-receipt.json': { profile: 'off', native: { bridge: false, devtool: false } },
153
+ 'dist-ok/main.lynx.bundle': 'nothing here',
154
+ 'dist-none/main.lynx.bundle': 'no receipt: not judged',
155
+ },
156
+ (dir) => {
157
+ const a = levels(examine(dir, { now: NOW }), 'artifact');
158
+ assert.ok(a.includes('ok: dist-ok: holds what off says'), a.join('\n'));
159
+ assert.ok(
160
+ a.some((l) => l.startsWith('fail: dist-store:')),
161
+ a.join('\n'),
162
+ );
163
+ assert.equal(
164
+ a.some((l) => l.includes('dist-none')),
165
+ false,
166
+ );
167
+ },
168
+ ));
169
+
170
+ test('a missing folder is a usage error', () => {
171
+ const lines = [];
172
+ assert.equal(main(['/no/such/app'], { log: (l) => lines.push(l) }), 2);
173
+ assert.match(lines[0], /does not exist/);
174
+ });
@@ -0,0 +1,55 @@
1
+ // @g9tm/lynxcontrols-pilot for an Android app module (after `com.android.application`): what the settings helper
2
+ // resolved becomes the module's dependencies and constants.
3
+ // app/build.gradle.kts: apply(from = "<node_modules>/@g9tm/lynxcontrols-pilot/gradle/g9pilot.app.gradle")
4
+ // · the bridge (profile support / full): implementation project(':g9tm-app-pilot-lynx'), and with the `devtool` module
5
+ // Lynx DevTool (its version: -Pg9pilot.lynx or ext.g9pilotLynx, default 4.2.0; it brings V8, which must then be
6
+ // there at start — leaving half of it out crashes the first LynxView);
7
+ // · BuildConfig: G9PILOT_PROFILE, G9PILOT_BRIDGE, G9PILOT_CONFIG (the host's PilotConfig as JSON: appId, port, keys
8
+ // with the build's scope ceiling, signatureRequired, transport, badge, consent, session, selfDrive, devtool),
9
+ // G9PILOT_LYNX (the engine version, for dev.status);
10
+ // · the manifest placeholder g9pilotCleartext: true only with DevTool (a dev server on the device's loopback is
11
+ // http://127.0.0.1), so `android:usesCleartextTraffic="${g9pilotCleartext}"` stays false in every other build;
12
+ // · the Java/Kotlin source folder `src/pilot/on/java` with the bridge, else `src/pilot/off/java` (the host's two
13
+ // twins: the one that installs G9Pilot and the empty one), when the app has them.
14
+ def resolved = gradle.ext.has('g9pilot') ? gradle.ext.g9pilot : null
15
+ if (resolved == null) throw new GradleException('g9pilot: apply g9pilot.settings.gradle in settings first')
16
+ def bridge = resolved.bridge == 'true'
17
+ def devtool = resolved.devtool == 'true'
18
+ def lynxVersion = findProperty('g9pilot.lynx') ?: (project.ext.has('g9pilotLynx') ? project.ext.g9pilotLynx : '4.2.0')
19
+
20
+ def nativeJson = '{}'
21
+ if (bridge) {
22
+ def args = [resolved.containsKey('node') ? resolved.node : 'node', new File(resolved.packageDir, 'config/cli.mjs').absolutePath,
23
+ '--from', resolved.from, '--format', 'native']
24
+ if (resolved.env) args += ['--env', resolved.env]
25
+ def proc = args.execute()
26
+ def out = new StringBuilder(), err = new StringBuilder()
27
+ proc.waitForProcessOutput(out, err)
28
+ if (proc.exitValue() != 0) throw new GradleException("g9pilot: ${err.toString().trim()}")
29
+ nativeJson = out.toString().trim()
30
+ }
31
+ // a Java string literal for buildConfigField: backslashes, then quotes
32
+ def quoted = '"' + nativeJson.replace('\\', '\\\\').replace('"', '\\"') + '"'
33
+
34
+ android {
35
+ buildFeatures { buildConfig = true }
36
+ defaultConfig {
37
+ buildConfigField 'String', 'G9PILOT_PROFILE', "\"${resolved.profile}\""
38
+ buildConfigField 'boolean', 'G9PILOT_BRIDGE', bridge.toString()
39
+ buildConfigField 'String', 'G9PILOT_CONFIG', quoted
40
+ buildConfigField 'String', 'G9PILOT_LYNX', "\"${lynxVersion}\""
41
+ manifestPlaceholders['g9pilotCleartext'] = (bridge && devtool).toString()
42
+ }
43
+ def twin = file(bridge ? 'src/pilot/on/java' : 'src/pilot/off/java')
44
+ if (twin.exists()) sourceSets.main.java.srcDir(twin)
45
+ }
46
+
47
+ dependencies {
48
+ if (bridge) {
49
+ implementation project(':g9tm-app-pilot-lynx')
50
+ if (devtool) {
51
+ implementation "org.lynxsdk.lynx:lynx-devtool:${lynxVersion}"
52
+ implementation "org.lynxsdk.lynx:lynx-service-devtool:${lynxVersion}"
53
+ }
54
+ }
55
+ }
@@ -0,0 +1,27 @@
1
+ // @g9tm/lynxcontrols-pilot for an Android host's settings: includes G9AppPilot's native project ONLY when the build's
2
+ // environment carries the bridge (g9pilot.config.json, resolved by the same code as the page's bundle). A build without
3
+ // it does not even see the project. Groovy on purpose: a script plugin cannot see the Android Gradle plugin's types.
4
+ //
5
+ // settings.gradle.kts: apply(from = "<node_modules>/@g9tm/lynxcontrols-pilot/gradle/g9pilot.settings.gradle")
6
+ // the environment: -Pg9pilot.env=qa (or G9_PILOT_ENV=qa; none → off)
7
+ // where the config is: -Pg9pilot.from=<dir> (default: the folder above the Android project)
8
+ def pilotPackage = new File(buildscript.sourceFile.parentFile, '..').canonicalFile
9
+ def from = settings.providers.gradleProperty('g9pilot.from').orNull ?: settings.settingsDir.parentFile.absolutePath
10
+ def env = settings.providers.gradleProperty('g9pilot.env').orNull ?: (System.getenv('G9_PILOT_ENV') ?: '')
11
+ def node = settings.providers.gradleProperty('g9pilot.node').orNull ?: 'node'
12
+ def args = [node, new File(pilotPackage, 'config/cli.mjs').absolutePath, '--from', from, '--format', 'gradle']
13
+ if (env) args += ['--env', env]
14
+ def proc = args.execute()
15
+ def out = new StringBuilder(), err = new StringBuilder()
16
+ proc.waitForProcessOutput(out, err)
17
+ if (proc.exitValue() != 0) throw new GradleException("g9pilot: ${err.toString().trim()}")
18
+ def resolved = [:]
19
+ out.toString().eachLine { line -> def i = line.indexOf('='); if (i > 0) resolved[line.substring(0, i)] = line.substring(i + 1) }
20
+ gradle.ext.g9pilot = resolved + [env: env, from: from, packageDir: pilotPackage.absolutePath]
21
+ if (resolved.bridge == 'true') {
22
+ // the native bridge next to this package (npm hoists both; a workspace links them)
23
+ def lynxPilot = new File(pilotPackage, '../app-pilot-lynx/android').canonicalFile
24
+ if (!lynxPilot.exists()) throw new GradleException("g9pilot: ${lynxPilot} is missing (install @g9tm/app-pilot-lynx)")
25
+ include ':g9tm-app-pilot-lynx'
26
+ project(':g9tm-app-pilot-lynx').projectDir = lynxPilot
27
+ }