@nstudio/nativescript-compiler-octane 0.0.0-stage → 9.2.0-alpha.11
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/LICENSE +19 -0
- package/README.md +27 -2
- package/dist/core-api.js +8 -0
- package/dist/hooks.js +76 -0
- package/dist/index.js +33 -0
- package/dist/octane.js +933 -0
- package/dist/package.js +13 -0
- package/package.json +45 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright OpenJS Foundation and other contributors, https://openjsf.org
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
19
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nstudio/nativescript-compiler-octane
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Octane adapter for [`@nstudio/nativescript-compiler`](https://www.npmjs.com/package/@nstudio/nativescript-compiler), enabling NativeScript Octane apps (`@nativescript-community/octane`) to compile directly to native code with no JavaScript runtime.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
ns extension install @nstudio/nativescript-compiler
|
|
9
|
+
npm install --save-dev @nstudio/nativescript-compiler-octane
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Install the adapter at the same version as `@nstudio/nativescript-compiler`.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
ns compile ios
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
> Note: Octane compiled builds currently target iOS only.
|
|
21
|
+
|
|
22
|
+
## Supported Versions
|
|
23
|
+
|
|
24
|
+
- `@nativescript-community/octane`: `>=0.2.4 <0.3.0`
|
|
25
|
+
|
|
26
|
+
## License
|
|
27
|
+
|
|
28
|
+
MIT
|
package/dist/core-api.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
|
|
2
|
+
export let core;
|
|
3
|
+
/** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
|
|
4
|
+
export let ts;
|
|
5
|
+
export function useCore(api) {
|
|
6
|
+
core = api;
|
|
7
|
+
ts = api.ts;
|
|
8
|
+
}
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { core, ts } from "./core-api.js";
|
|
2
|
+
const OCTANE = /[\\/]@nativescript-community[\\/]octane[\\/]/;
|
|
3
|
+
const STORE = /[\\/](octane|@nativescript-community[\\/]octane)[\\/]/;
|
|
4
|
+
/** `renderNativeScriptApp(host, Component, props)`: the component rendered into the host as Octane's root, its props' arguments in order. */
|
|
5
|
+
function rootArgs(t, e, arg) {
|
|
6
|
+
const [, component, props] = e.arguments;
|
|
7
|
+
const name = component && ts.isIdentifier(component) ? component.text : '';
|
|
8
|
+
const info = t.components.get(name);
|
|
9
|
+
if (!info)
|
|
10
|
+
throw t.error(e, `rendering ${component?.getText() ?? 'nothing'}: not a component`);
|
|
11
|
+
if (props && !ts.isObjectLiteralExpression(props))
|
|
12
|
+
throw t.error(props, 'root props other than an object literal');
|
|
13
|
+
const given = new Map();
|
|
14
|
+
for (const p of props?.properties ?? []) {
|
|
15
|
+
if (ts.isPropertyAssignment(p))
|
|
16
|
+
given.set(p.name.getText(), p.initializer);
|
|
17
|
+
else if (ts.isShorthandPropertyAssignment(p))
|
|
18
|
+
given.set(p.name.text, p.name);
|
|
19
|
+
else
|
|
20
|
+
throw t.error(p, 'a root prop');
|
|
21
|
+
}
|
|
22
|
+
const args = info.props.flatMap((p) => {
|
|
23
|
+
const v = given.get(p);
|
|
24
|
+
if (!v) {
|
|
25
|
+
if (info.optional?.includes(p))
|
|
26
|
+
return [];
|
|
27
|
+
throw t.error(e, `rendering ${name} without its prop ${p}`);
|
|
28
|
+
}
|
|
29
|
+
return [arg(p, v)];
|
|
30
|
+
});
|
|
31
|
+
return { name, args, render: info.members.render };
|
|
32
|
+
}
|
|
33
|
+
const declFile = (decl) => decl?.getSourceFile().fileName ?? '';
|
|
34
|
+
export const swiftHooks = {
|
|
35
|
+
globalCall(t, name, e, decl) {
|
|
36
|
+
if (name === 'renderNativeScriptApp' && OCTANE.test(declFile(decl))) {
|
|
37
|
+
const root = rootArgs(t, e, (p, v) => `${core.swift.ident(p)}: ${t.coerce(v, t.typeOf(v))}`);
|
|
38
|
+
return `OctaneRoot(host: ${t.expr(e.arguments[0])}) { ${root.name}(${root.args.join(', ')}).${root.render}() }`;
|
|
39
|
+
}
|
|
40
|
+
if (name === 'useSyncExternalStore' && STORE.test(declFile(decl))) {
|
|
41
|
+
// One subscription per call site: its listener bumps a version every reader tracks, then the snapshot is read.
|
|
42
|
+
const [subscribe, snapshot] = e.arguments;
|
|
43
|
+
const site = `${e.getSourceFile().fileName}:${e.getStart()}`;
|
|
44
|
+
const type = t.typeOf(e);
|
|
45
|
+
const subscribeType = t.typeOf(subscribe);
|
|
46
|
+
let bare = snapshot;
|
|
47
|
+
while (ts.isParenthesizedExpression(bare))
|
|
48
|
+
bare = bare.expression;
|
|
49
|
+
// A function declaration or literal that does not throw reads without `try`; a variable holding a function has Swift's throwing function type.
|
|
50
|
+
const declared = t.resolve(bare)?.declarations?.find((d) => ts.isFunctionDeclaration(d) && !!d.body);
|
|
51
|
+
const read = ts.isArrowFunction(bare) || ts.isFunctionExpression(bare) ? bare : declared;
|
|
52
|
+
const snap = read && !t.throwsInfo.fn(read) ? `{ () -> ${type} in ${t.expr(snapshot)}() }`
|
|
53
|
+
: `{ () throws -> ${type} in try ${t.expr(snapshot)}() }`;
|
|
54
|
+
return `jsExternalStore(${core.swift.string(site)}, subscribe: ${t.convert(t.coerce(subscribe, subscribeType), subscribeType, 'Any?')}, snapshot: ${snap})`;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
export const kotlinHooks = {
|
|
60
|
+
globalCall(t, name, e, decl) {
|
|
61
|
+
if (name === 'renderNativeScriptApp' && OCTANE.test(declFile(decl))) {
|
|
62
|
+
const root = rootArgs(t, e, (p, v) => `${core.kotlin.ident(p)} = ${t.coerce(v, t.typeOf(v))}`);
|
|
63
|
+
return `OctaneRoot(${t.expr(e.arguments[0])}) { ${root.name}(${root.args.join(', ')}).${root.render}() }`;
|
|
64
|
+
}
|
|
65
|
+
if (name === 'useSyncExternalStore' && STORE.test(declFile(decl))) {
|
|
66
|
+
// One subscription per call site: its listener bumps a version every reader tracks, then the snapshot is read.
|
|
67
|
+
const [subscribe, snapshot] = e.arguments;
|
|
68
|
+
const site = `${e.getSourceFile().fileName}:${e.getStart()}`;
|
|
69
|
+
const bare = (x) => { while (ts.isParenthesizedExpression(x))
|
|
70
|
+
x = x.expression; return x; };
|
|
71
|
+
const read = t.functionValue(bare(snapshot));
|
|
72
|
+
return `jsExternalStore(${core.kotlin.string(site)}, ${t.functionValue(bare(subscribe))}) { ${read.startsWith('::') ? read.slice(2) : `(${read})`}() }`;
|
|
73
|
+
}
|
|
74
|
+
return undefined;
|
|
75
|
+
},
|
|
76
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { useCore } from "./core-api.js";
|
|
3
|
+
import { kotlinHooks, swiftHooks } from "./hooks.js";
|
|
4
|
+
import { octaneApp } from "./octane.js";
|
|
5
|
+
import { PACKAGE } from "./package.js";
|
|
6
|
+
const behaviour = { schedule: 'event', eventScope: 'event', propsOrder: 'pre', deferBindings: false, insertion: 'built', listenersAfterBindings: false, effectScope: null, checkEveryBinding: 'off', slots: false, rowSignals: 'off', fragments: false, kit: { attributeValue: 'octaneValue', className: 'octaneClassName', rowItems: 'octaneItems' } };
|
|
7
|
+
export default function adapter(core) {
|
|
8
|
+
useCore(core);
|
|
9
|
+
return {
|
|
10
|
+
apiVersion: 1,
|
|
11
|
+
name: 'octane',
|
|
12
|
+
packages: ['@nativescript-community/octane', '@nativescript/octane', 'octane', '@nativescript-community/vite-octane'],
|
|
13
|
+
behaviour,
|
|
14
|
+
reach: 'project',
|
|
15
|
+
swift: swiftHooks,
|
|
16
|
+
kotlin: kotlinHooks,
|
|
17
|
+
package: PACKAGE,
|
|
18
|
+
frontEnd(app) {
|
|
19
|
+
const tsx = app.files.filter((f) => f.endsWith('.tsx'));
|
|
20
|
+
const octane = octaneApp(app.entry, new Map([app.entry, ...app.sources, ...tsx].map((f) => [f, readFileSync(f, 'utf8')])), app.platform);
|
|
21
|
+
const mounted = !!octane.mounted;
|
|
22
|
+
return {
|
|
23
|
+
components: octane.components,
|
|
24
|
+
overrides: new Map(octane.overrides),
|
|
25
|
+
mounted,
|
|
26
|
+
modules: mounted ? [...app.sources, ...tsx, app.entry] : app.sources.filter((f) => !octane.glue.has(f)),
|
|
27
|
+
root: octane.root,
|
|
28
|
+
// An app mounting its own roots renders as Octane's NativeScript driver does.
|
|
29
|
+
behaviour: mounted ? { ...behaviour, slots: true, rowSignals: 'value' } : behaviour,
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
package/dist/octane.js
ADDED
|
@@ -0,0 +1,933 @@
|
|
|
1
|
+
import { basename, dirname, join, relative } from 'node:path';
|
|
2
|
+
import { core, ts } from "./core-api.js";
|
|
3
|
+
/** Handler props NativeScript Octane spells the web's way; any other `onFooBar` is the event `fooBar`. */
|
|
4
|
+
const EVENT_ALIASES = { onClick: 'tap', onPress: 'tap', onTap: 'tap', onDoubleTap: 'doubleTap', onLongPress: 'longPress', onChange: 'textChange', onSubmit: 'returnPress' };
|
|
5
|
+
const eventName = (prop) => EVENT_ALIASES[prop] ?? prop[2].toLowerCase() + prop.slice(3);
|
|
6
|
+
/** Views whose JSX text children are their `text`, as the driver folds `#text` nodes. */
|
|
7
|
+
const TEXT_HOSTS = new Set(['Label', 'Button', 'TextField']);
|
|
8
|
+
const HOOKS = new Set(['useState', 'useMemo', 'useCallback', 'useSyncExternalStore', 'useRef']);
|
|
9
|
+
const EFFECTS = new Set(['useEffect', 'useLayoutEffect']);
|
|
10
|
+
/** The page title, a prop every page component takes; `$` keeps it clear of the app's own props. */
|
|
11
|
+
const TITLE = '$title';
|
|
12
|
+
/**
|
|
13
|
+
* An Octane NativeScript app: function components over lowercase core tags,
|
|
14
|
+
* each page an Octane root of its own mounted by the app's helper around
|
|
15
|
+
* `renderNativeScriptApp` on a core `Frame`, and stores read through
|
|
16
|
+
* `useSyncExternalStore`.
|
|
17
|
+
*/
|
|
18
|
+
export function octaneApp(entry, files, platform = 'ios') {
|
|
19
|
+
const parse = (f, text = files.get(f)) => ts.createSourceFile(f, text, ts.ScriptTarget.Latest, true, f.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
20
|
+
const { fns: pageFns, glue } = pageFunctions(files, parse);
|
|
21
|
+
if (!pageFns.size && /\brenderNativeScriptApp\b/.test(files.get(entry) ?? '')) {
|
|
22
|
+
// Component files are read as the target's build sees them, the other platform's branches gone.
|
|
23
|
+
const folded = new Map([...files].map(([f, text]) => [f, f.endsWith('.tsx') ? core.foldPlatform(text, f, platform) : text]));
|
|
24
|
+
return mountedApp(entry, folded);
|
|
25
|
+
}
|
|
26
|
+
const callTo = (n, push) => ts.isCallExpression(n) && ts.isIdentifier(n.expression) && pageFns.get(n.expression.text)?.push === push ? pageFns.get(n.expression.text) : null;
|
|
27
|
+
// The first page: `frame.navigate({ create: () => createPage(Home, {}, 'Recipes') })` in the entry.
|
|
28
|
+
const entrySf = parse(entry);
|
|
29
|
+
let first = null;
|
|
30
|
+
walk(entrySf, (n) => {
|
|
31
|
+
const fn = callTo(n, false);
|
|
32
|
+
if (!fn || first)
|
|
33
|
+
return;
|
|
34
|
+
const call = n;
|
|
35
|
+
const title = call.arguments[fn.title];
|
|
36
|
+
if (!title || !ts.isStringLiteralLike(title))
|
|
37
|
+
throw fail(call, 'the first page needs a string title');
|
|
38
|
+
first = { component: call.arguments[fn.component].getText(), props: staticProps(call.arguments[fn.props]), title: title.text };
|
|
39
|
+
});
|
|
40
|
+
if (!first || !/\bnew Frame\(/.test(files.get(entry)))
|
|
41
|
+
throw new Error(`${entry}: no Frame navigating to a page made with renderNativeScriptApp`);
|
|
42
|
+
const start = first;
|
|
43
|
+
// Components: a TSX file's capitalized functions. Pushing a page and `new Color(x)` are rewritten in the source first.
|
|
44
|
+
const sources = new Map();
|
|
45
|
+
const targets = new Set([start.component]);
|
|
46
|
+
const fns = [];
|
|
47
|
+
for (const [f, text] of files) {
|
|
48
|
+
if (!f.endsWith('.tsx'))
|
|
49
|
+
continue;
|
|
50
|
+
const sf = parse(f);
|
|
51
|
+
const edits = [];
|
|
52
|
+
const colors = importedFrom(sf, '@nativescript/core').has('Color');
|
|
53
|
+
walk(sf, (n) => {
|
|
54
|
+
const fn = callTo(n, true);
|
|
55
|
+
if (fn) {
|
|
56
|
+
const call = n;
|
|
57
|
+
const component = call.arguments[fn.component].getText();
|
|
58
|
+
const props = call.arguments[fn.props];
|
|
59
|
+
if (props && !ts.isObjectLiteralExpression(props))
|
|
60
|
+
throw at(props, 'page props other than an object literal');
|
|
61
|
+
const given = props ? props.properties.map((p) => p.getText()) : [];
|
|
62
|
+
targets.add(component);
|
|
63
|
+
edits.push({ start: call.getStart(), end: call.getEnd(), text: `$navigateTo(${component}, { props: { ${[...given, `${TITLE}: ${call.arguments[fn.title].getText()}`].join(', ')} } })` });
|
|
64
|
+
}
|
|
65
|
+
// The kit takes a CSS color string wherever core takes a Color.
|
|
66
|
+
if (colors && ts.isNewExpression(n) && n.expression.getText() === 'Color' && n.arguments?.length === 1)
|
|
67
|
+
edits.push({ start: n.getStart(), end: n.getEnd(), text: `(${n.arguments[0].getText()})` });
|
|
68
|
+
});
|
|
69
|
+
let out = text;
|
|
70
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
71
|
+
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
72
|
+
sources.set(f, out);
|
|
73
|
+
for (const st of parse(f, out).statements)
|
|
74
|
+
if (ts.isFunctionDeclaration(st) && st.name && /^[A-Z]/.test(st.name.text))
|
|
75
|
+
fns.push({ file: f, name: st.name.text });
|
|
76
|
+
}
|
|
77
|
+
const names = new Map(fns.map(({ file, name }) => [name, file]));
|
|
78
|
+
const components = fns.map(({ file, name }) => {
|
|
79
|
+
const fn = parse(file, sources.get(file)).statements.find((s) => ts.isFunctionDeclaration(s) && s.name?.text === name);
|
|
80
|
+
return octaneComponent(file, fn, targets.has(name), names);
|
|
81
|
+
});
|
|
82
|
+
const overrides = new Map();
|
|
83
|
+
for (const [f, text] of files) {
|
|
84
|
+
if (f.endsWith('.tsx') || f === entry || glue.has(f))
|
|
85
|
+
continue;
|
|
86
|
+
const store = externalStore(text);
|
|
87
|
+
if (store)
|
|
88
|
+
overrides.set(f, store);
|
|
89
|
+
}
|
|
90
|
+
// The frame, starting at the first page.
|
|
91
|
+
const root = 'AppFrame';
|
|
92
|
+
if (names.has(root))
|
|
93
|
+
throw new Error(`${names.get(root)}: ${root} is the release build's name for the app's frame`);
|
|
94
|
+
const startFile = names.get(start.component);
|
|
95
|
+
if (!startFile)
|
|
96
|
+
throw new Error(`${entry}: ${start.component} is not a component of the app`);
|
|
97
|
+
const file = join(dirname(entry), `${root}.octane.ts`);
|
|
98
|
+
components.push({
|
|
99
|
+
name: root, file, props: [],
|
|
100
|
+
source: `import ${start.component} from '${moduleFrom(file, startFile, start.component)}';\nexport default class ${root} {}\n`,
|
|
101
|
+
template: [{ kind: 'element', tag: 'Frame', attrs: [], events: [], children: [{ kind: 'component', name: start.component, props: [{ name: TITLE, value: start.title }, ...start.props], events: [] }] }],
|
|
102
|
+
});
|
|
103
|
+
return { components, overrides, glue, root };
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The app's page functions: one that calls `renderNativeScriptApp(page, component, props)`
|
|
107
|
+
* and sets `page.actionBar.title`, and those that pass their arguments on to
|
|
108
|
+
* it, pushing the page when they do it inside a `navigate(...)` call.
|
|
109
|
+
*/
|
|
110
|
+
function pageFunctions(files, parse) {
|
|
111
|
+
const fns = new Map();
|
|
112
|
+
const glue = new Set();
|
|
113
|
+
for (const [f, text] of files) {
|
|
114
|
+
if (f.endsWith('.tsx') || !text.includes('renderNativeScriptApp'))
|
|
115
|
+
continue;
|
|
116
|
+
const decls = parse(f).statements.filter((s) => ts.isFunctionDeclaration(s) && !!s.name && !!s.body);
|
|
117
|
+
const params = (fn) => fn.parameters.map((p) => p.name.getText());
|
|
118
|
+
for (const fn of decls) {
|
|
119
|
+
const ps = params(fn);
|
|
120
|
+
const found = { component: -1, props: -1, title: -1, push: false };
|
|
121
|
+
walk(fn.body, (n) => {
|
|
122
|
+
if (ts.isCallExpression(n) && n.expression.getText() === 'renderNativeScriptApp') {
|
|
123
|
+
found.component = ps.indexOf(n.arguments[1]?.getText() ?? '');
|
|
124
|
+
found.props = ps.indexOf(n.arguments[2]?.getText() ?? '');
|
|
125
|
+
}
|
|
126
|
+
if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken && /\.actionBar\.title$/.test(n.left.getText()))
|
|
127
|
+
found.title = ps.indexOf(n.right.getText());
|
|
128
|
+
});
|
|
129
|
+
if (found.component < 0)
|
|
130
|
+
continue;
|
|
131
|
+
if (found.title < 0)
|
|
132
|
+
throw fail(fn, 'a page needs its title set from a parameter (`page.actionBar.title = title`)');
|
|
133
|
+
fns.set(fn.name.text, found);
|
|
134
|
+
glue.add(f);
|
|
135
|
+
}
|
|
136
|
+
for (const fn of decls) {
|
|
137
|
+
if (fns.has(fn.name.text))
|
|
138
|
+
continue;
|
|
139
|
+
const ps = params(fn);
|
|
140
|
+
walk(fn.body, (n) => {
|
|
141
|
+
if (!ts.isCallExpression(n) || !ts.isIdentifier(n.expression))
|
|
142
|
+
return;
|
|
143
|
+
const inner = fns.get(n.expression.text);
|
|
144
|
+
if (!inner || inner.push)
|
|
145
|
+
return;
|
|
146
|
+
const arg = (i) => ps.indexOf(n.arguments[i]?.getText() ?? '');
|
|
147
|
+
let push = false;
|
|
148
|
+
for (let p = n.parent; p !== fn; p = p.parent)
|
|
149
|
+
if (ts.isCallExpression(p) && ts.isPropertyAccessExpression(p.expression) && p.expression.name.text === 'navigate')
|
|
150
|
+
push = true;
|
|
151
|
+
fns.set(fn.name.text, { component: arg(inner.component), props: arg(inner.props), title: arg(inner.title), push });
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { fns, glue };
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* An Octane function component as a virtual class. Octane re-runs the body
|
|
159
|
+
* on every render, as React does; the release build gets the same results by
|
|
160
|
+
* making `useState` a signal, `useMemo` and every other body const a derived
|
|
161
|
+
* value, and `useSyncExternalStore` a getter over the store's signals.
|
|
162
|
+
*/
|
|
163
|
+
function octaneComponent(path, fn, page, components, options = {}) {
|
|
164
|
+
const name = fn.name.text;
|
|
165
|
+
const sf = fn.getSourceFile();
|
|
166
|
+
const file = `${dirname(path)}/${name}.octane.ts`;
|
|
167
|
+
const scope = { names: new Map() };
|
|
168
|
+
const fields = [];
|
|
169
|
+
const props = [];
|
|
170
|
+
const arity = new Map(options.arity ?? []);
|
|
171
|
+
// Props: `{ recipe, onTap }: { recipe: Recipe; onTap: () => void }`, or `props: { ... }` read as `props.recipe`;
|
|
172
|
+
// the type may be an interface or an intersection of them, a prop may have a default, the rest may be gathered.
|
|
173
|
+
const param = fn.parameters[0];
|
|
174
|
+
let propsName = '';
|
|
175
|
+
const optional = [];
|
|
176
|
+
let rest = null;
|
|
177
|
+
if (param) {
|
|
178
|
+
if (!param.type)
|
|
179
|
+
throw at(param, 'untyped props');
|
|
180
|
+
const members = propMembers(param.type, sf);
|
|
181
|
+
if (ts.isIdentifier(param.name))
|
|
182
|
+
propsName = param.name.text;
|
|
183
|
+
const bound = new Map();
|
|
184
|
+
if (ts.isObjectBindingPattern(param.name)) {
|
|
185
|
+
for (const e of param.name.elements) {
|
|
186
|
+
if (e.dotDotDotToken)
|
|
187
|
+
continue;
|
|
188
|
+
if (e.propertyName)
|
|
189
|
+
throw at(e, 'a renamed prop');
|
|
190
|
+
bound.set(e.name.text, e);
|
|
191
|
+
}
|
|
192
|
+
const gathered = param.name.elements.find((e) => e.dotDotDotToken);
|
|
193
|
+
if (gathered)
|
|
194
|
+
rest = { name: gathered.name.text, keys: members.map((m) => m.name).filter((n) => !bound.has(n) && n !== 'key') };
|
|
195
|
+
}
|
|
196
|
+
for (const m of members) {
|
|
197
|
+
if (m.name === 'key')
|
|
198
|
+
continue;
|
|
199
|
+
props.push(m.name);
|
|
200
|
+
if (m.optional)
|
|
201
|
+
optional.push(m.name);
|
|
202
|
+
fields.push(` ${m.name}${m.optional ? '?' : '!'}: ${m.type};`);
|
|
203
|
+
const def = bound.get(m.name)?.initializer;
|
|
204
|
+
if (!propsName)
|
|
205
|
+
scope.names.set(m.name, def ? `(this.${m.name} ?? ${def.getText()})` : `this.${m.name}`);
|
|
206
|
+
if (m.arity !== undefined)
|
|
207
|
+
arity.set(m.name, m.arity);
|
|
208
|
+
}
|
|
209
|
+
if (rest)
|
|
210
|
+
fields.push(' $passed!: Set<string>;');
|
|
211
|
+
}
|
|
212
|
+
if (page) {
|
|
213
|
+
props.push(TITLE);
|
|
214
|
+
fields.push(` ${TITLE}!: string;`);
|
|
215
|
+
}
|
|
216
|
+
const restName = rest?.name;
|
|
217
|
+
const full = (s) => ({ names: s.names, members: propsName ? { object: propsName, replacement: 'this' } : restName ? { object: restName, replacement: 'this' } : undefined });
|
|
218
|
+
// A platform branch folded to a block that returns (`if (!isIOS) { … return <label/> }`) is the body; what follows it never runs.
|
|
219
|
+
const returning = fn.body.statements.find((st) => ts.isBlock(st) && !!st.statements.length && ts.isReturnStatement(st.statements[st.statements.length - 1]));
|
|
220
|
+
const body = returning ? [...fn.body.statements.slice(0, fn.body.statements.indexOf(returning)), ...returning.statements] : fn.body.statements;
|
|
221
|
+
const ret = body.find(ts.isReturnStatement);
|
|
222
|
+
if (!ret?.expression)
|
|
223
|
+
throw fail(fn, `${name} returns no JSX`);
|
|
224
|
+
const hook = (e) => (ts.isCallExpression(e) && ts.isIdentifier(e.expression) && /^use[A-Z]/.test(e.expression.text) ? e.expression.text : null);
|
|
225
|
+
const effectCall = (st) => (ts.isExpressionStatement(st) && ts.isCallExpression(st.expression) && ts.isIdentifier(st.expression.expression) && EFFECTS.has(st.expression.expression.text) ? st.expression : null);
|
|
226
|
+
for (const st of body) {
|
|
227
|
+
if (st === ret)
|
|
228
|
+
continue;
|
|
229
|
+
if (effectCall(st))
|
|
230
|
+
continue;
|
|
231
|
+
if (ts.isFunctionDeclaration(st) && st.name) {
|
|
232
|
+
arity.set(st.name.text, st.parameters.length);
|
|
233
|
+
scope.names.set(st.name.text, `this.${st.name.text}`);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (!ts.isVariableStatement(st))
|
|
237
|
+
throw at(st, `a statement in ${name}`);
|
|
238
|
+
for (const d of st.declarationList.declarations) {
|
|
239
|
+
const init = d.initializer;
|
|
240
|
+
const h = hook(init);
|
|
241
|
+
if (h && !HOOKS.has(h) && !options.hooks?.has(h))
|
|
242
|
+
throw at(init, h);
|
|
243
|
+
if (ts.isObjectBindingPattern(d.name) && !h) {
|
|
244
|
+
// `const { top, bottom } = safeAreaInsets()`: each a derived value read from the object.
|
|
245
|
+
for (const e of d.name.elements)
|
|
246
|
+
scope.names.set(e.name.text, `this.${e.name.text}`);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
if (ts.isArrayBindingPattern(d.name)) {
|
|
250
|
+
if (h !== 'useState')
|
|
251
|
+
throw at(d, 'array destructuring');
|
|
252
|
+
const [value, setter] = d.name.elements.map((e) => (ts.isBindingElement(e) ? e.name.getText() : ''));
|
|
253
|
+
scope.names.set(value, `this.${value}()`);
|
|
254
|
+
if (setter)
|
|
255
|
+
scope.names.set(setter, `this.${value}.$write`);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (!ts.isIdentifier(d.name))
|
|
259
|
+
throw at(d, 'object destructuring');
|
|
260
|
+
const id = d.name.text;
|
|
261
|
+
const fnInit = h === 'useCallback' ? init.arguments[0] : init;
|
|
262
|
+
if (ts.isArrowFunction(fnInit) || ts.isFunctionExpression(fnInit))
|
|
263
|
+
arity.set(id, fnInit.parameters.length);
|
|
264
|
+
scope.names.set(id, `this.${id}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (page)
|
|
268
|
+
scope.names.set(TITLE, `this.${TITLE}`);
|
|
269
|
+
const method = (id, f) => {
|
|
270
|
+
const b = ts.isBlock(f.body) ? f.body.getText() : `{ return ${f.body.getText()}; }`;
|
|
271
|
+
return ` ${(ts.getModifiers(f)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ? 'async ' : '')}${id}(${f.parameters.map((p) => p.getText()).join(', ')})${f.type ? `: ${f.type.getText()}` : ''} ${core.rewrite(b, full(scope), 'statements')}`;
|
|
272
|
+
};
|
|
273
|
+
const getter = (id, f) => ` get ${id}() ${ts.isBlock(f.body) ? core.rewrite(f.body.getText(), full(scope), 'statements') : `{ return ${core.rewrite(f.body.getText(), full(scope))}; }`}`;
|
|
274
|
+
const effects = [];
|
|
275
|
+
let effectCount = 0;
|
|
276
|
+
for (const st of body) {
|
|
277
|
+
if (st === ret)
|
|
278
|
+
continue;
|
|
279
|
+
const effect = effectCall(st);
|
|
280
|
+
if (effect) {
|
|
281
|
+
// `useEffect(fn, deps)`: fn's body as a method returning its cleanup, deps as a method returning the list.
|
|
282
|
+
const [fx, deps] = effect.arguments;
|
|
283
|
+
if (!fx || !(ts.isArrowFunction(fx) || ts.isFunctionExpression(fx)))
|
|
284
|
+
throw at(effect, `${effect.expression.getText()} without a function literal`);
|
|
285
|
+
const run = `$effect${effectCount}`;
|
|
286
|
+
const depsName = deps ? `$deps${effectCount}` : null;
|
|
287
|
+
effectCount++;
|
|
288
|
+
fields.push(method(run, fx));
|
|
289
|
+
if (deps)
|
|
290
|
+
fields.push(` ${depsName}(): any[] { return ${core.rewrite(deps.getText(), full(scope))}; }`);
|
|
291
|
+
effects.push({ run, deps: depsName, layout: effect.expression.text === 'useLayoutEffect' });
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (ts.isFunctionDeclaration(st)) {
|
|
295
|
+
fields.push(method(st.name.text, st));
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
for (const d of st.declarationList.declarations) {
|
|
299
|
+
const init = d.initializer;
|
|
300
|
+
const h = hook(init);
|
|
301
|
+
const args = h ? init.arguments : ts.factory.createNodeArray();
|
|
302
|
+
if (ts.isObjectBindingPattern(d.name) && !h) {
|
|
303
|
+
const tmp = `$object${effectCount++}`;
|
|
304
|
+
fields.push(` get ${tmp}() { return ${core.rewrite(init.getText(), full(scope))}; }`);
|
|
305
|
+
for (const e of d.name.elements)
|
|
306
|
+
fields.push(` get ${e.name.text}() { return this.${tmp}.${(e.propertyName ?? e.name).text}; }`);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (h === 'useRef') {
|
|
310
|
+
// A ref is an object that lives as long as the component: a field.
|
|
311
|
+
const id = d.name.text;
|
|
312
|
+
const call = init;
|
|
313
|
+
const typeArg = call.typeArguments?.[0]?.getText();
|
|
314
|
+
const value = args[0] ? core.rewrite(args[0].getText(), full(scope)) : 'undefined';
|
|
315
|
+
fields.push(typeArg ? ` ${id}: { current: ${typeArg} } = { current: ${value} };` : ` ${id} = { current: ${value} };`);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (h === 'useState') {
|
|
319
|
+
const value = d.name.elements[0].name.getText();
|
|
320
|
+
const call = init;
|
|
321
|
+
const typeArgs = call.typeArguments ? `<${call.typeArguments.map((t) => t.getText()).join(', ')}>` : '';
|
|
322
|
+
fields.push(` ${value} = $state($writable${typeArgs}(${args[0] ? core.rewrite(args[0].getText(), full(scope)) : 'undefined'}));`);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const id = d.name.text;
|
|
326
|
+
if (h === 'useSyncExternalStore' && options.elements) {
|
|
327
|
+
// Read through the store's subscription, which re-renders what read it when it notifies.
|
|
328
|
+
fields.push(` get ${id}() { return useSyncExternalStore(${args.map((a) => core.rewrite(a.getText(), full(scope))).join(', ')}); }`);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (h && options.hooks?.has(h)) {
|
|
332
|
+
fields.push(` get ${id}() { return ${core.rewrite(init.getText(), full(scope))}; }`);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (h === 'useSyncExternalStore') {
|
|
336
|
+
// The store's state is signals: reading the snapshot is the subscription.
|
|
337
|
+
const snapshot = args[1];
|
|
338
|
+
if (ts.isArrowFunction(snapshot) || ts.isFunctionExpression(snapshot))
|
|
339
|
+
fields.push(getter(id, snapshot));
|
|
340
|
+
else
|
|
341
|
+
fields.push(` get ${id}() { return ${core.rewrite(snapshot.getText(), full(scope))}(); }`);
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
if (h === 'useMemo') {
|
|
345
|
+
fields.push(getter(id, args[0]));
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (h === 'useCallback') {
|
|
349
|
+
fields.push(method(id, args[0]));
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
|
|
353
|
+
fields.push(method(id, init));
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
// Octane recomputes a body const on every render: a derived value.
|
|
357
|
+
fields.push(` get ${id}() { return ${core.rewrite(init.getText(), full(scope))}; }`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
// The template.
|
|
361
|
+
const methods = [];
|
|
362
|
+
let next = 0;
|
|
363
|
+
const prelude = (loops) => loops.map((l) => l.prelude ?? '').join('');
|
|
364
|
+
const params = (loops) => loops.map((l) => l.param).join(', ');
|
|
365
|
+
const loopArgs = (loops) => loops.flatMap((l) => [l.item, l.index]).join(', ');
|
|
366
|
+
const local = (loops, extra = {}) => {
|
|
367
|
+
const names = new Map(scope.names);
|
|
368
|
+
for (const l of loops) {
|
|
369
|
+
names.delete(l.item);
|
|
370
|
+
names.delete(l.index);
|
|
371
|
+
}
|
|
372
|
+
for (const [k, v] of Object.entries(extra))
|
|
373
|
+
names.set(k, v);
|
|
374
|
+
return full({ names });
|
|
375
|
+
};
|
|
376
|
+
/** Components whose prop types a binding names (`Streamdown['config']`). */
|
|
377
|
+
const propTypes = new Set();
|
|
378
|
+
const expr = (code, loops, returns) => {
|
|
379
|
+
const m = `$b${next++}`;
|
|
380
|
+
const pre = prelude(loops);
|
|
381
|
+
const r = returns ? `: ${returns}` : '';
|
|
382
|
+
methods.push(pre ? ` ${m}(${params(loops)})${r} ${core.rewrite(`{ ${pre} return (${code}); }`, local(loops), 'statements')}` : ` ${m}(${params(loops)})${r} { return ${core.rewrite(code, local(loops))}; }`);
|
|
383
|
+
return m;
|
|
384
|
+
};
|
|
385
|
+
/** A handler; on a two-way element's change event, `e.object.<its property>` is the event's value. */
|
|
386
|
+
const handler = (e, loops, model, guard) => {
|
|
387
|
+
const m = `$e${next++}`;
|
|
388
|
+
let code;
|
|
389
|
+
if (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) {
|
|
390
|
+
const p = e.parameters[0] ? e.parameters[0].name.getText() : null;
|
|
391
|
+
let text = e.body.getText();
|
|
392
|
+
if (p && model)
|
|
393
|
+
text = text.replace(new RegExp(`\\b${p}\\.object\\.${model.prop}\\b`, 'g'), `(${p}.value as ${model.type})`);
|
|
394
|
+
const extra = p ? { [p]: '$event' } : {};
|
|
395
|
+
code = ts.isBlock(e.body) ? core.rewrite(text, local(loops, extra), 'statements') : `${core.rewrite(text, local(loops, extra)).slice(1, -1)};`;
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
const t = e.getText();
|
|
399
|
+
code = `${core.rewrite(t, local(loops)).slice(1, -1)}(${arity.get(t) === 0 ? '' : '$event'});`;
|
|
400
|
+
}
|
|
401
|
+
const pre = prelude(loops);
|
|
402
|
+
if (guard)
|
|
403
|
+
code = `if (${core.rewrite(guard, local(loops))}) { ${code} }`;
|
|
404
|
+
if (pre)
|
|
405
|
+
code = core.rewrite(`{ ${pre} ${code} }`, local(loops), 'statements').slice(1, -1);
|
|
406
|
+
methods.push(` ${m}(${[params(loops), '$event: $EventData'].filter(Boolean).join(', ')}) { ${code} }`);
|
|
407
|
+
return m;
|
|
408
|
+
};
|
|
409
|
+
const element = (n, loops) => {
|
|
410
|
+
const open = ts.isJsxElement(n) ? n.openingElement : n;
|
|
411
|
+
const tag = open.tagName.getText();
|
|
412
|
+
const isComponent = /^[A-Z]/.test(tag);
|
|
413
|
+
const el = isComponent ? null : core.canonical(tag) ?? options.elements?.get(tag) ?? null;
|
|
414
|
+
if (isComponent && !components.has(tag))
|
|
415
|
+
throw fail(open, `<${tag}> is not a component of the app`);
|
|
416
|
+
if (!isComponent && !el)
|
|
417
|
+
throw fail(open, `<${tag}> is not a @nativescript/core element the release build knows`);
|
|
418
|
+
const model = el ? core.MODELS[el] : undefined;
|
|
419
|
+
const attrs = [];
|
|
420
|
+
const events = [];
|
|
421
|
+
let renderItem = null;
|
|
422
|
+
let ref;
|
|
423
|
+
for (const a of open.attributes.properties) {
|
|
424
|
+
if (ts.isJsxSpreadAttribute(a)) {
|
|
425
|
+
// `{...rest}`: each prop the component gathered, set only when its parent gave it.
|
|
426
|
+
if (!rest || a.expression.getText() !== rest.name || isComponent)
|
|
427
|
+
throw at(a, 'a spread attribute');
|
|
428
|
+
for (const key of rest.keys) {
|
|
429
|
+
if (/^on[A-Z]/.test(key)) {
|
|
430
|
+
const m = `$e${next++}`;
|
|
431
|
+
methods.push(` ${m}(${[params(loops), '$event: $EventData'].filter(Boolean).join(', ')}) { this.${key}?.($event); }`);
|
|
432
|
+
events.push({ name: eventName(key), method: m, ifPassed: key });
|
|
433
|
+
}
|
|
434
|
+
else
|
|
435
|
+
attrs.push({ name: key === 'className' ? 'class' : key, method: expr(`this.${key}`, loops), ifPassed: key });
|
|
436
|
+
}
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
const attr = a.name.getText();
|
|
440
|
+
if (attr === 'key')
|
|
441
|
+
continue;
|
|
442
|
+
if (attr === 'ref') {
|
|
443
|
+
const init = a.initializer;
|
|
444
|
+
if (!init || !ts.isJsxExpression(init) || !init.expression)
|
|
445
|
+
throw at(a, 'a ref without an object');
|
|
446
|
+
ref = expr(init.expression.getText(), loops);
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
const init = a.initializer;
|
|
450
|
+
if (el === 'ListView' && attr === 'renderItem' && init && ts.isJsxExpression(init) && init.expression) {
|
|
451
|
+
renderItem = init.expression;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (el === 'ListView' && (attr === 'itemTemplateSelector' || attr === 'itemTemplates' || attr === 'itemTemplate'))
|
|
455
|
+
throw at(a, `${attr} on a listview`);
|
|
456
|
+
if (!isComponent && /^on[A-Z]/.test(attr) && init && ts.isJsxExpression(init) && init.expression && ts.isConditionalExpression(skipParens(init.expression))) {
|
|
457
|
+
const c = skipParens(init.expression);
|
|
458
|
+
const none = (x) => x.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(x) && x.text === 'undefined');
|
|
459
|
+
if (none(c.whenFalse) || none(c.whenTrue)) {
|
|
460
|
+
const fn = none(c.whenFalse) ? c.whenTrue : c.whenFalse;
|
|
461
|
+
const when = expr(none(c.whenFalse) ? c.condition.getText() : `!(${c.condition.getText()})`, loops);
|
|
462
|
+
events.push({ name: eventName(attr), method: handler(fn, loops, undefined, none(c.whenFalse) ? c.condition.getText() : `!(${c.condition.getText()})`), when });
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (!isComponent && /^on[A-Z]/.test(attr) && init && ts.isJsxExpression(init) && init.expression) {
|
|
467
|
+
const ev = eventName(attr);
|
|
468
|
+
events.push({ name: ev, method: handler(init.expression, loops, model?.event === ev ? model : undefined) });
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
const name = attr === 'className' ? 'class' : attr;
|
|
472
|
+
if (!init)
|
|
473
|
+
attrs.push({ name, value: 'true' });
|
|
474
|
+
else if (ts.isStringLiteral(init))
|
|
475
|
+
attrs.push({ name, value: init.text });
|
|
476
|
+
else if (ts.isJsxExpression(init) && init.expression) {
|
|
477
|
+
// A value given to a component's prop has the prop's type (an object literal is not a shape of its own, a function takes the prop's parameters).
|
|
478
|
+
if (isComponent)
|
|
479
|
+
propTypes.add(tag);
|
|
480
|
+
attrs.push({ name, method: expr(init.expression.getText(), loops, isComponent ? `${tag}['${attr}']` : undefined) });
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
const kids = ts.isJsxElement(n) ? n.children : ts.factory.createNodeArray();
|
|
484
|
+
if (isComponent) {
|
|
485
|
+
if (kids.some((c) => !ts.isJsxText(c) || !c.containsOnlyTriviaWhiteSpaces))
|
|
486
|
+
throw at(n, 'children of a component');
|
|
487
|
+
return { kind: 'component', name: tag, props: attrs, events };
|
|
488
|
+
}
|
|
489
|
+
if (el === 'ListView') {
|
|
490
|
+
if (kids.some((c) => !ts.isJsxText(c) || !c.containsOnlyTriviaWhiteSpaces))
|
|
491
|
+
throw at(n, 'children of a listview');
|
|
492
|
+
if (!renderItem)
|
|
493
|
+
throw fail(open, 'a listview needs renderItem in a release build');
|
|
494
|
+
return { kind: 'element', tag: el, attrs, events, children: rows(renderItem, attrs, loops) };
|
|
495
|
+
}
|
|
496
|
+
// A text view whose child is a formatted string (or a component rendering one) hosts it as `formattedText`.
|
|
497
|
+
const hostsElement = kids.some((k) => ts.isJsxElement(k) || ts.isJsxSelfClosingElement(k));
|
|
498
|
+
if (TEXT_HOSTS.has(el) && !hostsElement) {
|
|
499
|
+
const text = textOf(kids, loops);
|
|
500
|
+
if (text)
|
|
501
|
+
attrs.push(text);
|
|
502
|
+
return { kind: 'element', tag: el, attrs, events, children: [], ref };
|
|
503
|
+
}
|
|
504
|
+
return { kind: 'element', tag: el, attrs, events, children: children(kids, loops), ref };
|
|
505
|
+
};
|
|
506
|
+
/**
|
|
507
|
+
* A listview's `renderItem(item, index)`, which the driver renders into a cell of its own; a row that is a
|
|
508
|
+
* conditional becomes a template per branch.
|
|
509
|
+
*/
|
|
510
|
+
const rows = (fn, attrs, loops) => {
|
|
511
|
+
while (ts.isParenthesizedExpression(fn))
|
|
512
|
+
fn = fn.expression;
|
|
513
|
+
if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn))
|
|
514
|
+
throw at(fn, 'renderItem other than an inline function');
|
|
515
|
+
if (ts.isBlock(fn.body))
|
|
516
|
+
throw at(fn, 'renderItem with a block body');
|
|
517
|
+
const items = attrs.find((a) => a.name === 'items');
|
|
518
|
+
if (!items || !('method' in items))
|
|
519
|
+
throw at(fn, 'a listview without bound items');
|
|
520
|
+
const item = fn.parameters[0] ? fn.parameters[0].name.getText() : `$item${loops.length}`;
|
|
521
|
+
const index = fn.parameters[1] ? fn.parameters[1].name.getText() : `$i${loops.length}`;
|
|
522
|
+
const inner = [...loops, { item, index, param: `${item} = this.${items.method}(${loopArgs(loops)})[0], ${index} = 0` }];
|
|
523
|
+
const { templates, selector } = core.rowTemplates(jsx(fn.body, inner), item, index);
|
|
524
|
+
if (selector) {
|
|
525
|
+
const m = `$b${next++}`;
|
|
526
|
+
methods.push(` ${m}(${params(inner)}): string { return ${selector((c) => `this.${c}(${loopArgs(inner)})`)}; }`);
|
|
527
|
+
attrs.push({ name: 'itemTemplateSelector', method: m });
|
|
528
|
+
}
|
|
529
|
+
return templates;
|
|
530
|
+
};
|
|
531
|
+
/** Text children as the driver folds them into `text`: JSX's whitespace rules, then each expression printed. */
|
|
532
|
+
const textOf = (list, loops) => {
|
|
533
|
+
let literal = '';
|
|
534
|
+
let template = '';
|
|
535
|
+
let dynamic = false;
|
|
536
|
+
for (const c of list) {
|
|
537
|
+
if (ts.isJsxText(c)) {
|
|
538
|
+
const t = jsxText(c.text);
|
|
539
|
+
literal += t;
|
|
540
|
+
template += t.replace(/[\\`]/g, '\\$&').replace(/\$\{/g, '\\${');
|
|
541
|
+
}
|
|
542
|
+
else if (ts.isJsxExpression(c)) {
|
|
543
|
+
if (!c.expression)
|
|
544
|
+
continue;
|
|
545
|
+
dynamic = true;
|
|
546
|
+
template += '${' + c.expression.getText() + '}';
|
|
547
|
+
}
|
|
548
|
+
else
|
|
549
|
+
throw at(c, 'an element inside a text view');
|
|
550
|
+
}
|
|
551
|
+
if (dynamic)
|
|
552
|
+
return { name: 'text', method: expr('`' + template + '`', loops) };
|
|
553
|
+
return literal ? { name: 'text', value: literal } : null;
|
|
554
|
+
};
|
|
555
|
+
const jsx = (e, loops) => {
|
|
556
|
+
while (ts.isParenthesizedExpression(e))
|
|
557
|
+
e = e.expression;
|
|
558
|
+
if (e.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(e) && e.text === 'undefined'))
|
|
559
|
+
return [];
|
|
560
|
+
if (ts.isJsxElement(e) || ts.isJsxSelfClosingElement(e))
|
|
561
|
+
return [element(e, loops)];
|
|
562
|
+
if (ts.isJsxFragment(e))
|
|
563
|
+
return children(e.children, loops);
|
|
564
|
+
// `cond && <X/>`
|
|
565
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
566
|
+
return [{ kind: 'if', branches: [{ cond: expr(e.left.getText(), loops), body: jsx(e.right, loops) }] }];
|
|
567
|
+
// `cond ? <A/> : <B/>`
|
|
568
|
+
if (ts.isConditionalExpression(e))
|
|
569
|
+
return [{ kind: 'if', branches: [{ cond: expr(e.condition.getText(), loops), body: jsx(e.whenTrue, loops) }, { cond: null, body: jsx(e.whenFalse, loops) }] }];
|
|
570
|
+
// `list.map((item, i) => <X key={…}/>)`
|
|
571
|
+
if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === 'map') {
|
|
572
|
+
const cb = e.arguments[0];
|
|
573
|
+
if (!ts.isArrowFunction(cb))
|
|
574
|
+
throw at(e, '.map without an arrow function');
|
|
575
|
+
const item = cb.parameters[0].name.getText();
|
|
576
|
+
const index = cb.parameters[1] ? cb.parameters[1].name.getText() : `$i${loops.length}`;
|
|
577
|
+
const items = expr(e.expression.expression.getText(), loops);
|
|
578
|
+
const inner = [...loops, { item, index, param: `${item} = this.${items}(${loopArgs(loops)})[0], ${index} = 0` }];
|
|
579
|
+
if (ts.isBlock(cb.body)) {
|
|
580
|
+
const stmts = [...cb.body.statements];
|
|
581
|
+
const leading = stmts.filter((x, k) => ts.isVariableStatement(x) && stmts.slice(0, k).every(ts.isVariableStatement));
|
|
582
|
+
const withConsts = [...loops, { ...inner[inner.length - 1], prelude: leading.map((x) => x.getText()).join(' ') }];
|
|
583
|
+
let keyNode;
|
|
584
|
+
walk(cb.body, (n) => { if (!keyNode && ts.isJsxAttribute(n) && n.name.getText() === 'key')
|
|
585
|
+
keyNode = n; });
|
|
586
|
+
const k = keyNode?.initializer;
|
|
587
|
+
const key = k && ts.isJsxExpression(k) && k.expression ? expr(k.expression.getText(), withConsts) : k && ts.isStringLiteral(k) ? expr(k.getText(), withConsts) : null;
|
|
588
|
+
return [{ kind: 'for', items, key, item, index, body: block(stmts.slice(leading.length), withConsts) }];
|
|
589
|
+
}
|
|
590
|
+
let row = cb.body;
|
|
591
|
+
while (ts.isParenthesizedExpression(row))
|
|
592
|
+
row = row.expression;
|
|
593
|
+
const open = ts.isJsxElement(row) ? row.openingElement : ts.isJsxSelfClosingElement(row) ? row : null;
|
|
594
|
+
const keyAttr = open?.attributes.properties.find((a) => ts.isJsxAttribute(a) && a.name.getText() === 'key');
|
|
595
|
+
const k = keyAttr?.initializer;
|
|
596
|
+
const key = k && ts.isJsxExpression(k) && k.expression ? expr(k.expression.getText(), inner) : k && ts.isStringLiteral(k) ? expr(k.getText(), inner) : null;
|
|
597
|
+
return [{ kind: 'for', items, key, item, index, body: jsx(row, inner) }];
|
|
598
|
+
}
|
|
599
|
+
throw at(e, `{${e.getText().slice(0, 50)}} in JSX`);
|
|
600
|
+
};
|
|
601
|
+
/** A row's statements after its consts: what it returns, through `if` and `switch`. */
|
|
602
|
+
const block = (stmts, loops) => {
|
|
603
|
+
const withPrelude = (text) => {
|
|
604
|
+
const last = loops[loops.length - 1];
|
|
605
|
+
return [...loops.slice(0, -1), { ...last, prelude: `${last.prelude ?? ''} ${text}` }];
|
|
606
|
+
};
|
|
607
|
+
for (let k = 0; k < stmts.length; k++) {
|
|
608
|
+
const st = stmts[k];
|
|
609
|
+
if (ts.isVariableStatement(st))
|
|
610
|
+
return block(stmts.slice(k + 1), withPrelude(st.getText()));
|
|
611
|
+
if (ts.isBlock(st))
|
|
612
|
+
return block([...st.statements, ...stmts.slice(k + 1)], loops);
|
|
613
|
+
if (ts.isReturnStatement(st))
|
|
614
|
+
return st.expression ? jsx(st.expression, loops) : [];
|
|
615
|
+
if (ts.isIfStatement(st)) {
|
|
616
|
+
const then = block(ts.isBlock(st.thenStatement) ? [...st.thenStatement.statements] : [st.thenStatement], loops);
|
|
617
|
+
const otherwise = st.elseStatement ? block(ts.isBlock(st.elseStatement) ? [...st.elseStatement.statements] : [st.elseStatement], loops) : block(stmts.slice(k + 1), loops);
|
|
618
|
+
return [{ kind: 'if', branches: [{ cond: expr(st.expression.getText(), loops), body: then }, { cond: null, body: otherwise }] }];
|
|
619
|
+
}
|
|
620
|
+
if (ts.isSwitchStatement(st)) {
|
|
621
|
+
const subject = st.expression.getText();
|
|
622
|
+
const branches = [];
|
|
623
|
+
let labels = [];
|
|
624
|
+
for (const c of st.caseBlock.clauses) {
|
|
625
|
+
if (ts.isCaseClause(c))
|
|
626
|
+
labels.push(c.expression.getText());
|
|
627
|
+
if (!c.statements.length)
|
|
628
|
+
continue;
|
|
629
|
+
const body = block([...c.statements], loops);
|
|
630
|
+
branches.push({ cond: ts.isDefaultClause(c) ? null : expr(labels.map((l) => `(${subject}) === ${l}`).join(' || '), loops), body });
|
|
631
|
+
labels = [];
|
|
632
|
+
}
|
|
633
|
+
if (!branches.some((b) => b.cond === null))
|
|
634
|
+
branches.push({ cond: null, body: block(stmts.slice(k + 1), loops) });
|
|
635
|
+
return [{ kind: 'if', branches }];
|
|
636
|
+
}
|
|
637
|
+
throw at(st, 'a statement in a row');
|
|
638
|
+
}
|
|
639
|
+
return [];
|
|
640
|
+
};
|
|
641
|
+
const children = (list, loops) => list.flatMap((c) => {
|
|
642
|
+
if (ts.isJsxText(c)) {
|
|
643
|
+
if (!c.containsOnlyTriviaWhiteSpaces)
|
|
644
|
+
throw at(c, 'text outside a text view');
|
|
645
|
+
return [];
|
|
646
|
+
}
|
|
647
|
+
if (ts.isJsxExpression(c))
|
|
648
|
+
return c.expression ? jsx(c.expression, loops) : [];
|
|
649
|
+
return jsx(c, loops);
|
|
650
|
+
});
|
|
651
|
+
let template = jsx(ret.expression, []);
|
|
652
|
+
// The page's action bar, titled by whoever pushed it.
|
|
653
|
+
if (page)
|
|
654
|
+
template = [{ kind: 'element', tag: 'ActionBar', attrs: [{ name: 'title', method: expr(TITLE, []) }], events: [], children: [] }, ...template];
|
|
655
|
+
// Imports: components as their virtual classes, Octane's own modules dropped, the rest as far as the class still uses them.
|
|
656
|
+
const members = [...fields, ...methods].join('\n');
|
|
657
|
+
const used = (id) => new RegExp(`(^|[^\\w$])${id.replace(/\$/g, '\\$')}(?![\\w$])`).test(members);
|
|
658
|
+
const imports = [];
|
|
659
|
+
if (options.elements && used('useSyncExternalStore'))
|
|
660
|
+
imports.push(`import { useSyncExternalStore } from 'octane';`);
|
|
661
|
+
for (const i of sf.statements.filter(ts.isImportDeclaration)) {
|
|
662
|
+
const from = i.moduleSpecifier.text;
|
|
663
|
+
if (from === 'octane' || from.startsWith('octane/') || from.startsWith('@nativescript-community/octane'))
|
|
664
|
+
continue;
|
|
665
|
+
const clause = i.importClause;
|
|
666
|
+
if (!clause)
|
|
667
|
+
continue;
|
|
668
|
+
const named = clause.namedBindings && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : [];
|
|
669
|
+
const locals = [...named.map((e) => e.name.text), ...(clause.name ? [clause.name.text] : [])];
|
|
670
|
+
for (const n of locals)
|
|
671
|
+
if (components.has(n) && used(n))
|
|
672
|
+
imports.push(`import ${n} from '${moduleFrom(file, components.get(n), n)}';`);
|
|
673
|
+
const kept = named.filter((e) => !components.has(e.name.text) && used(e.name.text));
|
|
674
|
+
if (kept.length)
|
|
675
|
+
imports.push(`import ${clause.isTypeOnly ? 'type ' : ''}{ ${kept.map((e) => e.getText()).join(', ')} } from '${from}';`);
|
|
676
|
+
if (clause.name && !components.has(clause.name.text) && used(clause.name.text))
|
|
677
|
+
imports.push(`import ${clause.name.text} from '${from}';`);
|
|
678
|
+
}
|
|
679
|
+
// The file's own declarations other than components, from the file as a module.
|
|
680
|
+
const fileLocals = sf.statements.flatMap((st) => {
|
|
681
|
+
if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEnumDeclaration(st)) && st.name && !components.has(st.name.text))
|
|
682
|
+
return [st.name.text];
|
|
683
|
+
if (ts.isVariableStatement(st))
|
|
684
|
+
return st.declarationList.declarations.flatMap((d) => (ts.isIdentifier(d.name) ? [d.name.text] : []));
|
|
685
|
+
return [];
|
|
686
|
+
}).filter(used);
|
|
687
|
+
for (const tag of propTypes)
|
|
688
|
+
if (!imports.some((i) => i.startsWith(`import ${tag} from`)))
|
|
689
|
+
imports.push(`import type ${tag} from '${moduleFrom(file, components.get(tag), tag)}';`);
|
|
690
|
+
if (fileLocals.length && options.elements)
|
|
691
|
+
imports.push(`import { ${fileLocals.join(', ')} } from './${basename(path).replace(/\.tsx?$/, '')}';`);
|
|
692
|
+
const source = [`import { $writable, $state, $navigateTo, type EventData as $EventData } from '@nativescript/release';`, ...imports, '', `export default class ${name} {`, ...fields, ...methods, '}', ''].join('\n');
|
|
693
|
+
return { name, file, source, props, template, page, optional, passed: !!rest, effects };
|
|
694
|
+
}
|
|
695
|
+
/** A component's props: the members of its parameter's type, an inline type, an interface or type of its file, or an intersection of them. */
|
|
696
|
+
function propMembers(type, sf) {
|
|
697
|
+
if (ts.isParenthesizedTypeNode(type))
|
|
698
|
+
return propMembers(type.type, sf);
|
|
699
|
+
if (ts.isIntersectionTypeNode(type))
|
|
700
|
+
return type.types.flatMap((t) => propMembers(t, sf));
|
|
701
|
+
const fromMembers = (members) => members.filter((m) => ts.isPropertySignature(m) && !!m.type).map((m) => ({
|
|
702
|
+
name: m.name.getText(), type: m.type.getText(), optional: !!m.questionToken, arity: ts.isFunctionTypeNode(m.type) ? m.type.parameters.length : undefined,
|
|
703
|
+
}));
|
|
704
|
+
if (ts.isTypeLiteralNode(type))
|
|
705
|
+
return fromMembers(type.members);
|
|
706
|
+
if (ts.isTypeReferenceNode(type) && ts.isIdentifier(type.typeName)) {
|
|
707
|
+
const name = type.typeName.text;
|
|
708
|
+
for (const st of sf.statements) {
|
|
709
|
+
if (ts.isInterfaceDeclaration(st) && st.name.text === name)
|
|
710
|
+
return fromMembers(st.members);
|
|
711
|
+
if (ts.isTypeAliasDeclaration(st) && st.name.text === name)
|
|
712
|
+
return propMembers(st.type, sf);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
throw at(type, 'props typed other than by an object type of the component\'s file');
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* An app that mounts Octane roots itself: function components over core's
|
|
719
|
+
* lowercase tags and the tags it registers, its entry and the rest of each
|
|
720
|
+
* component file translated as modules.
|
|
721
|
+
*/
|
|
722
|
+
function mountedApp(entry, files) {
|
|
723
|
+
const parse = (f, text = files.get(f)) => ts.createSourceFile(f, text, ts.ScriptTarget.Latest, true, f.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
724
|
+
const elements = new Map();
|
|
725
|
+
for (const [f] of files) {
|
|
726
|
+
walk(parse(f), (n) => {
|
|
727
|
+
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'registerElement' && n.arguments.length === 2 && ts.isStringLiteralLike(n.arguments[0]) && ts.isIdentifier(n.arguments[1])) {
|
|
728
|
+
elements.set(n.arguments[0].text.toLowerCase(), n.arguments[1].text);
|
|
729
|
+
}
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
const returnsJsx = (fn) => {
|
|
733
|
+
let found = false;
|
|
734
|
+
walk(fn.body, (n) => { if (ts.isReturnStatement(n) && n.expression && /^\(?\s*</.test(n.expression.getText()))
|
|
735
|
+
found = true; });
|
|
736
|
+
return found;
|
|
737
|
+
};
|
|
738
|
+
const fns = [];
|
|
739
|
+
for (const [f] of files) {
|
|
740
|
+
if (!f.endsWith('.tsx'))
|
|
741
|
+
continue;
|
|
742
|
+
for (const st of parse(f).statements)
|
|
743
|
+
if (ts.isFunctionDeclaration(st) && st.name && st.body && /^[A-Z]/.test(st.name.text) && returnsJsx(st))
|
|
744
|
+
fns.push({ file: f, fn: st });
|
|
745
|
+
}
|
|
746
|
+
const names = new Map(fns.map(({ file, fn }) => [fn.name.text, file]));
|
|
747
|
+
// The app's own hooks: functions named `use…` reading stores (useSyncExternalStore) and nothing stateful.
|
|
748
|
+
const hooks = new Set();
|
|
749
|
+
for (const [f] of files) {
|
|
750
|
+
for (const st of parse(f).statements) {
|
|
751
|
+
if (!ts.isFunctionDeclaration(st) || !st.name || !/^use[A-Z]/.test(st.name.text) || !st.body)
|
|
752
|
+
continue;
|
|
753
|
+
let pure = true;
|
|
754
|
+
walk(st.body, (n) => { if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && /^use[A-Z]/.test(n.expression.text) && n.expression.text !== 'useSyncExternalStore')
|
|
755
|
+
pure = false; });
|
|
756
|
+
if (!pure)
|
|
757
|
+
throw fail(st, `${st.name.text} uses state of its own`);
|
|
758
|
+
hooks.add(st.name.text);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
const arity = new Map();
|
|
762
|
+
for (const [f] of files) {
|
|
763
|
+
for (const st of parse(f).statements) {
|
|
764
|
+
if (ts.isFunctionDeclaration(st) && st.name)
|
|
765
|
+
arity.set(st.name.text, st.parameters.length);
|
|
766
|
+
if (ts.isVariableStatement(st))
|
|
767
|
+
for (const d of st.declarationList.declarations) {
|
|
768
|
+
if (ts.isIdentifier(d.name) && d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer)))
|
|
769
|
+
arity.set(d.name.text, d.initializer.parameters.length);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
const components = fns.map(({ file, fn }) => octaneComponent(file, fn, false, names, { elements, hooks, arity }));
|
|
774
|
+
// Each component file as a module: its components declared (the release build renders them), every declaration exported for the components' classes.
|
|
775
|
+
const overrides = new Map();
|
|
776
|
+
for (const [f, text] of files) {
|
|
777
|
+
if (!f.endsWith('.tsx'))
|
|
778
|
+
continue;
|
|
779
|
+
const sf = parse(f);
|
|
780
|
+
const edits = [];
|
|
781
|
+
for (const st of sf.statements) {
|
|
782
|
+
if (ts.isFunctionDeclaration(st) && st.name && names.get(st.name.text) === f) {
|
|
783
|
+
const p = st.parameters[0];
|
|
784
|
+
edits.push({ start: st.getStart(), end: st.getEnd(), text: `export declare function ${st.name.text}(${p?.type ? `props: ${p.type.getText()}` : ''}): any;` });
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
const exported = ts.canHaveModifiers(st) && ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
|
|
788
|
+
if (!exported && (ts.isFunctionDeclaration(st) || ts.isVariableStatement(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isClassDeclaration(st) || ts.isEnumDeclaration(st))) {
|
|
789
|
+
edits.push({ start: st.getStart(), end: st.getStart(), text: 'export ' });
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
let out = text;
|
|
793
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
794
|
+
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
795
|
+
overrides.set(f, out);
|
|
796
|
+
}
|
|
797
|
+
return { components, overrides, glue: new Set(), root: '', mounted: true };
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* A store in the shape `useSyncExternalStore` reads (`let state: State`, a
|
|
801
|
+
* `setState(patch)` that replaces it and notifies, `getState()`), as a class
|
|
802
|
+
* named for the state type: a signal per field read through a getter, and
|
|
803
|
+
* `setState({ field: value })` as writes of those signals. The listeners and
|
|
804
|
+
* `subscribe` go: reading a signal is the subscription.
|
|
805
|
+
*/
|
|
806
|
+
export function externalStore(text) {
|
|
807
|
+
const sf = ts.createSourceFile('store.ts', text, ts.ScriptTarget.Latest, true);
|
|
808
|
+
let state = null;
|
|
809
|
+
for (const st of sf.statements) {
|
|
810
|
+
if (!ts.isVariableStatement(st) || st.declarationList.flags & ts.NodeFlags.Const)
|
|
811
|
+
continue;
|
|
812
|
+
for (const d of st.declarationList.declarations)
|
|
813
|
+
if (d.type && ts.isTypeReferenceNode(d.type) && d.initializer && ts.isObjectLiteralExpression(d.initializer))
|
|
814
|
+
state = d;
|
|
815
|
+
}
|
|
816
|
+
if (!state)
|
|
817
|
+
return null;
|
|
818
|
+
const stateName = state.name.getText();
|
|
819
|
+
const typeName = state.type.getText();
|
|
820
|
+
const iface = sf.statements.find((s) => ts.isInterfaceDeclaration(s) && s.name.text === typeName);
|
|
821
|
+
// The setter: `state = { ...state, ...patch }`.
|
|
822
|
+
const setter = sf.statements.find((s) => ts.isFunctionDeclaration(s) && !!s.body && new RegExp(`\\b${stateName}\\s*=\\s*\\{\\s*\\.\\.\\.${stateName}\\b`).test(s.body.getText()));
|
|
823
|
+
if (!iface || !setter)
|
|
824
|
+
return null;
|
|
825
|
+
const setterName = setter.name.text;
|
|
826
|
+
// What the setter notifies through, and everything built on it.
|
|
827
|
+
const machinery = new Set();
|
|
828
|
+
walk(setter.body, (n) => { if (ts.isIdentifier(n) && n.text !== stateName && sf.statements.some((s) => ts.isVariableStatement(s) && s.declarationList.declarations.some((d) => d.name.getText() === n.text)))
|
|
829
|
+
machinery.add(n.text); });
|
|
830
|
+
const mentions = (s) => [...machinery].some((m) => new RegExp(`\\b${m}\\b`).test(s.getText()));
|
|
831
|
+
const fields = iface.members.filter(ts.isPropertySignature).map((m) => ({ name: m.name.getText(), type: m.type.getText() }));
|
|
832
|
+
const initial = new Map(state.initializer.kind === ts.SyntaxKind.ObjectLiteralExpression ? state.initializer.properties.filter(ts.isPropertyAssignment).map((p) => [p.name.getText(), p.initializer.getText()]) : []);
|
|
833
|
+
const exported = iface.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ? 'export ' : '';
|
|
834
|
+
const cls = [`${exported}class ${typeName} {`, ...fields.flatMap((f) => [` $${f.name} = $writable<${f.type}>(${initial.get(f.name) ?? 'undefined'});`, ` get ${f.name}(): ${f.type} { return this.$${f.name}(); }`]), '}'].join('\n');
|
|
835
|
+
const out = [`import { $writable } from '@nativescript/release';`];
|
|
836
|
+
for (const st of sf.statements) {
|
|
837
|
+
if (st === iface || st === setter || st === state.parent.parent)
|
|
838
|
+
continue;
|
|
839
|
+
if (ts.isVariableStatement(st) && st.declarationList.declarations.some((d) => machinery.has(d.name.getText())))
|
|
840
|
+
continue;
|
|
841
|
+
if (ts.isFunctionDeclaration(st) && mentions(st))
|
|
842
|
+
continue;
|
|
843
|
+
if (ts.isFunctionDeclaration(st) && st.body) {
|
|
844
|
+
const edits = [];
|
|
845
|
+
walk(st.body, (n) => {
|
|
846
|
+
if (!ts.isExpressionStatement(n) || !ts.isCallExpression(n.expression) || n.expression.expression.getText() !== setterName)
|
|
847
|
+
return;
|
|
848
|
+
const patch = n.expression.arguments[0];
|
|
849
|
+
if (!patch || !ts.isObjectLiteralExpression(patch))
|
|
850
|
+
throw at(n, `${setterName} with anything but an object literal`);
|
|
851
|
+
const writes = patch.properties.map((p) => {
|
|
852
|
+
if (ts.isShorthandPropertyAssignment(p))
|
|
853
|
+
return `${stateName}.$${p.name.text}.set(${p.name.text});`;
|
|
854
|
+
if (ts.isPropertyAssignment(p))
|
|
855
|
+
return `${stateName}.$${p.name.getText()}.set(${p.initializer.getText()});`;
|
|
856
|
+
throw at(p, 'a patch member');
|
|
857
|
+
});
|
|
858
|
+
edits.push({ start: n.getStart(), end: n.getEnd(), text: writes.join(' ') });
|
|
859
|
+
});
|
|
860
|
+
let code = st.getText();
|
|
861
|
+
const base = st.getStart();
|
|
862
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
863
|
+
code = code.slice(0, e.start - base) + e.text + code.slice(e.end - base);
|
|
864
|
+
out.push(code);
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
out.push(st.getText());
|
|
868
|
+
}
|
|
869
|
+
out.splice(1, 0, cls, `const ${stateName} = new ${typeName}();`);
|
|
870
|
+
return out.join('\n\n') + '\n';
|
|
871
|
+
}
|
|
872
|
+
/** Page props given in the entry: string literals only. */
|
|
873
|
+
function staticProps(e) {
|
|
874
|
+
if (!e)
|
|
875
|
+
return [];
|
|
876
|
+
if (!ts.isObjectLiteralExpression(e))
|
|
877
|
+
throw at(e, 'first-page props other than an object literal');
|
|
878
|
+
return e.properties.map((p) => {
|
|
879
|
+
if (!ts.isPropertyAssignment(p) || !ts.isStringLiteralLike(p.initializer))
|
|
880
|
+
throw at(p, 'a first-page prop that is not a string');
|
|
881
|
+
return { name: p.name.getText(), value: p.initializer.text };
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
/** JSX text as JSX keeps it: lines trimmed where they meet a line break, blank lines dropped, the rest joined by a space. */
|
|
885
|
+
function jsxText(raw) {
|
|
886
|
+
const lines = raw.split(/\r\n|\n|\r/);
|
|
887
|
+
let last = -1;
|
|
888
|
+
lines.forEach((l, i) => { if (/[^ \t]/.test(l))
|
|
889
|
+
last = i; });
|
|
890
|
+
let out = '';
|
|
891
|
+
lines.forEach((line, i) => {
|
|
892
|
+
let t = line.replace(/\t/g, ' ');
|
|
893
|
+
if (i > 0)
|
|
894
|
+
t = t.replace(/^ +/, '');
|
|
895
|
+
if (i < lines.length - 1)
|
|
896
|
+
t = t.replace(/ +$/, '');
|
|
897
|
+
if (t)
|
|
898
|
+
out += i === last ? t : t + ' ';
|
|
899
|
+
});
|
|
900
|
+
return out;
|
|
901
|
+
}
|
|
902
|
+
function importedFrom(sf, module) {
|
|
903
|
+
const names = new Set();
|
|
904
|
+
for (const i of sf.statements.filter(ts.isImportDeclaration)) {
|
|
905
|
+
const b = i.importClause?.namedBindings;
|
|
906
|
+
if (i.moduleSpecifier.text === module && b && ts.isNamedImports(b))
|
|
907
|
+
for (const e of b.elements)
|
|
908
|
+
names.add(e.name.text);
|
|
909
|
+
}
|
|
910
|
+
return names;
|
|
911
|
+
}
|
|
912
|
+
/** The import specifier of component `name` (defined in `source`) from the virtual file `from`. */
|
|
913
|
+
function moduleFrom(from, source, name) {
|
|
914
|
+
const r = relative(dirname(from), join(dirname(source), `${name}.octane`));
|
|
915
|
+
return r.startsWith('.') ? r : './' + r;
|
|
916
|
+
}
|
|
917
|
+
function walk(node, visit) {
|
|
918
|
+
visit(node);
|
|
919
|
+
ts.forEachChild(node, (c) => walk(c, visit));
|
|
920
|
+
}
|
|
921
|
+
function at(n, what) {
|
|
922
|
+
return fail(n, `${what} is not supported in a release build yet`);
|
|
923
|
+
}
|
|
924
|
+
function fail(n, message) {
|
|
925
|
+
const sf = n.getSourceFile();
|
|
926
|
+
const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
|
|
927
|
+
return new Error(`${sf.fileName}:${line + 1}:${character + 1}: ${message}`);
|
|
928
|
+
}
|
|
929
|
+
function skipParens(e) {
|
|
930
|
+
while (ts.isParenthesizedExpression(e))
|
|
931
|
+
e = e.expression;
|
|
932
|
+
return e;
|
|
933
|
+
}
|
package/dist/package.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** The adapter's package folder, the nearest holding a package.json: run as TypeScript or from its built dist/ alike. */
|
|
5
|
+
const ROOT = (() => {
|
|
6
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
while (!existsSync(join(dir, 'package.json')))
|
|
8
|
+
dir = dirname(dir);
|
|
9
|
+
return dir;
|
|
10
|
+
})();
|
|
11
|
+
const { name, version } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
12
|
+
/** The package the adapter ships as: its kit is Kotlin, read from the package's own kit-android/. */
|
|
13
|
+
export const PACKAGE = { name, version, root: ROOT };
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nstudio/nativescript-compiler-octane",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "9.2.0-alpha.11",
|
|
4
|
+
"description": "The Octane adapter of @nstudio/nativescript-compiler: compiles a NativeScript app written with Octane into a native iOS or Android app with no JavaScript runtime.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"source": "./index.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "ns-compiled-adapter build .",
|
|
18
|
+
"prepack": "npm run build"
|
|
19
|
+
},
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "https://github.com/nstudio/nativescript-compiler.git",
|
|
24
|
+
"directory": "packages/octane"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@nstudio/nativescript-compiler": "9.2.0-alpha.11"
|
|
28
|
+
},
|
|
29
|
+
"nativescript": {
|
|
30
|
+
"compilerAdapter": {
|
|
31
|
+
"apiVersion": 1,
|
|
32
|
+
"detect": {
|
|
33
|
+
"priority": 10,
|
|
34
|
+
"dependencies": [
|
|
35
|
+
"@nativescript-community/octane",
|
|
36
|
+
"@nativescript/octane"
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
"testedVersions": {
|
|
40
|
+
"@nativescript-community/octane": ">=0.2.4 <0.3.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
}
|
|
47
|
+
}
|