@oxy.so/bloom-language-codemod 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1 +1,43 @@
1
- Placeholder for @oxy.so/bloom-language-codemod. The real package is published by CI from OxyHQ/Bloom.
1
+ # @oxy.so/bloom-language-codemod
2
+
3
+ Moves an app's NativeWind `className` JSX and Bloom JSX to the [Bloom language](https://github.com/OxyHQ/Bloom/blob/main/docs/bloom-language.mdx), only where the rendered result stays the same. Everything else stays JSX, embedded in the chain with `Embed`, and the report says why.
4
+
5
+ ```tsx
6
+ // before
7
+ <Pressable onPress={open} className="flex-row items-center gap-3 px-4 py-3 active:opacity-70">
8
+ <Text className="text-sm text-muted-foreground">{count} likes</Text>
9
+ </Pressable>
10
+
11
+ // after
12
+ toElement(
13
+ HStack(Text(count, ' likes').font('14').leading('20px').foreground('muted'))
14
+ .padding('horizontal', 'lg')
15
+ .padding('vertical', 'md')
16
+ .align('center')
17
+ .spacing('md')
18
+ .when('pressed', (v) => v.opacity('70'))
19
+ .onPress(open),
20
+ )
21
+ ```
22
+
23
+ ## Use
24
+
25
+ Install it in the app beside `@oxy.so/bloom-language` (its peer, whose spec and className table it reads), then:
26
+
27
+ ```bash
28
+ npx bloom-language-codemod . --out .bloom-language-codemod # report and converted files
29
+ npx bloom-language-codemod . --write # rewrite the app's files in place
30
+ npx bloom-language-codemod --help
31
+ ```
32
+
33
+ It writes `report.md` and `report.generated.json` (what converted, and why the rest did not) and, without `--write`, the converted files under `<out>/files`. The app's NativeWind entry (`global.css`, or `--css <entry>`) is compiled with Tailwind 4 from the app's own install, and a class the app's theme draws differently from Bloom's stays JSX.
34
+
35
+ Then typecheck the app and format it with its Biome: the codemod prints with recast and does not format.
36
+
37
+ ## The proof
38
+
39
+ Every converted region can be rendered before and after through Bloom's parity harness, native and web, light and dark (`--fixtures`, then the parity suites). The proof runs from a Bloom checkout; see [the codemod's guide](https://github.com/OxyHQ/Bloom/blob/main/docs/bloom-language-codemod.mdx).
40
+
41
+ ## License
42
+
43
+ See `LICENSE`.
package/lib/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/lib/cli.js ADDED
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ /**
5
+ * bloom-language-codemod <app dir> [--css <entry>] [--write] [--out <dir>] [--package <name>=<dir>] [--fixtures]
6
+ *
7
+ * Reads every .tsx under <app dir> (tests and stories left out), converts what
8
+ * converts exactly, and writes the report (`report.generated.json`, `report.md`) to
9
+ * <out>. With `--write` the files are rewritten in place; without it the
10
+ * converted files go to <out>/files. `--css` is the app's NativeWind entry
11
+ * (default: global.css or styles/global.css); its theme is checked against
12
+ * Bloom's for every class (see overrides.ts). `--package <name>=<dir>` resolves
13
+ * a CSS package the app imports from a checkout of it (`@oxy.so/app-preset`)
14
+ * when the app's own install does not hold it. `--fixtures` also writes the
15
+ * parity corpus (<out>/corpus.generated.tsx, fixtures.generated.json and the
16
+ * app's stylesheet app.generated.css), which the parity suites render from a
17
+ * Bloom checkout.
18
+ */
19
+ const node_fs_1 = require("node:fs");
20
+ const node_path_1 = require("node:path");
21
+ const corpus_1 = require("./corpus");
22
+ const overrides_1 = require("./overrides");
23
+ const report_1 = require("./report");
24
+ const table_1 = require("./table");
25
+ const tailwind_1 = require("./tailwind");
26
+ const transform_1 = require("./transform");
27
+ const IGNORED = /(\.stories\.|__tests__|__mocks__|\.test\.|\.spec\.|\/test\/|node_modules|\/examples\/|\.d\.ts$)/;
28
+ function files(dir) {
29
+ const out = [];
30
+ for (const name of (0, node_fs_1.readdirSync)(dir)) {
31
+ const path = (0, node_path_1.join)(dir, name);
32
+ if (IGNORED.test(path) || name.startsWith('.'))
33
+ continue;
34
+ if ((0, node_fs_1.statSync)(path).isDirectory())
35
+ out.push(...files(path));
36
+ else if (path.endsWith('.tsx'))
37
+ out.push(path);
38
+ }
39
+ return out.sort();
40
+ }
41
+ function arg(name) {
42
+ const at = process.argv.indexOf(name);
43
+ return at >= 0 ? process.argv[at + 1] : undefined;
44
+ }
45
+ const USAGE = `Usage: bloom-language-codemod <app dir> [options]
46
+
47
+ Moves the app's NativeWind className JSX and Bloom JSX to the Bloom language
48
+ where the result renders the same, and reports why the rest stays JSX.
49
+
50
+ Options:
51
+ --out <dir> where the report and converted files go
52
+ (default: <app dir>/.bloom-language-codemod)
53
+ --write rewrite the app's files in place
54
+ --css <entry> the app's NativeWind CSS entry
55
+ (default: global.css or styles/global.css)
56
+ --package <name>=<dir> read a CSS package the app imports from <dir>
57
+ --fixtures also write the parity corpus (proven from a Bloom checkout)
58
+ -h, --help show this help
59
+ `;
60
+ async function main() {
61
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
62
+ process.stdout.write(USAGE);
63
+ return;
64
+ }
65
+ const app = (0, node_path_1.resolve)(process.argv[2] ?? '.');
66
+ if (!(0, node_fs_1.existsSync)(app) || !(0, node_fs_1.statSync)(app).isDirectory()) {
67
+ process.stderr.write(`bloom-language-codemod: ${app} is not a directory\n\n${USAGE}`);
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ const out = (0, node_path_1.resolve)(arg('--out') ?? (0, node_path_1.join)(app, '.bloom-language-codemod'));
72
+ const write = process.argv.includes('--write');
73
+ const withFixtures = process.argv.includes('--fixtures');
74
+ const cssEntry = arg('--css') ?? ['global.css', 'styles/global.css'].map((f) => (0, node_path_1.join)(app, f)).find(node_fs_1.existsSync);
75
+ const table = (0, table_1.loadTable)();
76
+ const roots = {};
77
+ process.argv.forEach((value, i) => {
78
+ if (process.argv[i - 1] !== '--package')
79
+ return;
80
+ const [name, dir] = value.split('=');
81
+ if (name && dir)
82
+ roots[name] = (0, node_path_1.resolve)(dir);
83
+ });
84
+ const sources = files(app).map((path) => ({ path, source: (0, node_fs_1.readFileSync)(path, 'utf8') }));
85
+ // The classes the app writes, checked against Bloom's stylesheet first.
86
+ const classes = new Set();
87
+ for (const { source } of sources)
88
+ for (const result of [(0, transform_1.transformSource)(source, { table })])
89
+ for (const c of result.classes)
90
+ classes.add(c);
91
+ const overridden = cssEntry
92
+ ? await (0, overrides_1.overriddenClasses)((0, node_fs_1.readFileSync)(cssEntry, 'utf8'), cssEntry, [...classes], roots)
93
+ : new Set();
94
+ const results = [];
95
+ for (const { path, source } of sources) {
96
+ const file = (0, node_path_1.relative)(app, path);
97
+ let result;
98
+ try {
99
+ result = (0, transform_1.transformSource)(source, { table, overridden, fixtures: withFixtures, name: file });
100
+ }
101
+ catch (error) {
102
+ console.error(`${file}: ${error.message}`);
103
+ continue;
104
+ }
105
+ results.push({ file, result });
106
+ if (!result.changed)
107
+ continue;
108
+ const target = write ? path : (0, node_path_1.join)(out, 'files', file);
109
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(target), { recursive: true });
110
+ (0, node_fs_1.writeFileSync)(target, result.code);
111
+ }
112
+ (0, node_fs_1.mkdirSync)(out, { recursive: true });
113
+ const { json, markdown } = (0, report_1.report)(results, { app, overridden });
114
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(out, 'report.generated.json'), `${JSON.stringify(json, null, 2)}\n`);
115
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(out, 'report.md'), markdown);
116
+ if (withFixtures) {
117
+ const fixtures = results.flatMap(({ result }) => result.fixtures);
118
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(out, 'fixtures.generated.json'), `${JSON.stringify(fixtures, null, 1)}\n`);
119
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(out, 'corpus.generated.tsx'), (0, corpus_1.corpusModule)(fixtures, out));
120
+ // The app's classes in the corpus, and the before side's Bloom's own, which
121
+ // the app compiles too (its `@source` over Bloom's lib). That Bloom is a
122
+ // devDependency: the corpus is proven from a Bloom checkout.
123
+ const before = (0, tailwind_1.packageRoot)(corpus_1.BEFORE_BLOOM, [__dirname]);
124
+ if (before === undefined)
125
+ throw new Error(`--fixtures needs ${corpus_1.BEFORE_BLOOM} (Bloom 22, the before side's Bloom), which a Bloom checkout installs: run it there`);
126
+ const used = new Set([
127
+ ...fixtures.flatMap((f) => f.classes),
128
+ ...(0, tailwind_1.packageCandidates)((0, node_path_1.join)(before, 'lib/module')),
129
+ ]);
130
+ const css = cssEntry
131
+ ? (await (0, tailwind_1.tailwind)((0, node_fs_1.readFileSync)(cssEntry, 'utf8'), cssEntry, roots)).build([...used])
132
+ : '';
133
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(out, 'app.generated.css'), css);
134
+ }
135
+ console.log(markdown.split('\n').slice(0, 14).join('\n'));
136
+ }
137
+ main().catch((error) => {
138
+ console.error(error);
139
+ process.exit(1);
140
+ });
@@ -0,0 +1,182 @@
1
+ import { type Arg } from './table';
2
+ /**
3
+ * The forms a prop's value takes in a rule:
4
+ * - `string`: a static string, or any expression that is no JSX (a hole);
5
+ * - `token`: a static string only, written as it is (or through the rule's map);
6
+ * - `flag`: bare (`.m()`), a literal (`.m(false)`) or an expression (`.m(x)`);
7
+ * - `boolean`: as a flag, for a modifier whose value is required (bare is `.m(true)`);
8
+ * - `mark`: bare or `{true}` only (`.m()`, a modifier that takes no value);
9
+ * - `number`: a static number, or an expression (a hole);
10
+ * - `handler`: a function, carried as it is;
11
+ * - `view`: an element, converted when it can be, else embedded;
12
+ * - `icon`: a Bloom icon component, by name;
13
+ * - `literal`: a boolean literal (bare is `true`), through the rule's map (`'true'`, `'false'`);
14
+ * - `refresh`: React Native's `RefreshControl` element, as a pull to refresh's
15
+ * binding and tint (`.refreshable([refreshing, () => onRefresh()], tint)`);
16
+ * - `contentStyle`: a static content container style of paddings and a gap, as
17
+ * `.contentMargins(edge, token)` and `.spacing(token)`;
18
+ * - `items`: an array of data (any expression but an element or a string), carried as it is;
19
+ * - `element`: a JSX element, as a view; a fragment or a `const` holding an element, embedded
20
+ * (any other name may be a component);
21
+ * - `row`: FlashList's `renderItem` as the node's row, which Bloom hands the
22
+ * same `{ item, index }`: an arrow of one parameter returning an expression (the
23
+ * parameter as written; an element its view, any other expression embedded), or a named function, carried
24
+ * as it is (`VirtualList(posts, renderPost)`), its identity kept;
25
+ * - `empty`: an empty object literal (`screen={{}}`), as the bare modifier;
26
+ * - `className`: a static className laid out in a view of its own, as the
27
+ * modifiers of that view's build function (`.contentView((v) => v.padding('lg'))`),
28
+ * each class through the className table;
29
+ * - `placement`: Bloom's responsive placement, a static token
30
+ * (`placement="bottom"`) or an object of them (`{ base: 'bottom', md: 'center' }`),
31
+ * as `.presentAt(base, tiers)`.
32
+ */
33
+ export type Form = 'string' | 'token' | 'flag' | 'boolean' | 'mark' | 'number' | 'handler' | 'view' | 'icon' | 'literal' | 'refresh' | 'contentStyle' | 'items' | 'element' | 'row' | 'placement' | 'empty' | 'className';
34
+ /** A prop as a modifier: its name and form, and for a token, Bloom's value to the language's. */
35
+ export interface PropRule {
36
+ readonly modifier: string;
37
+ readonly form: Form;
38
+ readonly map?: Readonly<Record<string, string>>;
39
+ /**
40
+ * A Bloom component (`module#export`) the node is drawn only inside when this
41
+ * prop is given (a list bound to its screen, in a `Screen`): its parity draws both sides in one.
42
+ */
43
+ readonly within?: string;
44
+ /**
45
+ * A second prop that is the modifier's next argument (`onEndReachedThreshold`
46
+ * to `.onEndReached(action, threshold)`); given without this prop, it is a reason.
47
+ */
48
+ readonly with?: readonly [prop: string, form: Form];
49
+ /** Fixed arguments after the value (`showsVerticalScrollIndicator` to `.scrollIndicators(value, 'vertical')`). */
50
+ readonly args?: readonly Arg[];
51
+ /**
52
+ * A `mark` named by a static string (`type="tabs"`): each value the prop
53
+ * takes, as the bare modifier (`true`) or none (`false`).
54
+ */
55
+ readonly marks?: Readonly<Record<string, boolean>>;
56
+ /**
57
+ * The modifier's one object argument's key (`maxWidth` to
58
+ * `.frame({ maxWidth })`): the props of one modifier join one object.
59
+ */
60
+ readonly key?: string;
61
+ /**
62
+ * The close handler Bloom calls with no arguments when the reader dismisses
63
+ * (`onClose`): the prop's value and it are one binding, `[open, () => onClose()]`,
64
+ * a modifier that ends the chain (`.presented()`). Either alone is a reason.
65
+ */
66
+ readonly closedBy?: string;
67
+ /**
68
+ * Props that are the modifier's options object after its value
69
+ * (`bottomBarPlacement` to `.footer(view, { placement })`), each by its key
70
+ * and form; given without this prop, each is a reason.
71
+ */
72
+ readonly options?: Readonly<Record<string, readonly [key: string, form: Form, map?: Readonly<Record<string, string>>]>>;
73
+ }
74
+ /**
75
+ * A constructor argument, in order:
76
+ * - a prop (`optional` ones are `undefined` when absent);
77
+ * - a binding: a value prop and its setter, `[value, setValue]`;
78
+ * - the element's text children, as one string (or, naming a component
79
+ * `module#export`, the text children of its one child, that component with no props);
80
+ * - an options object: each prop given, under its own name or the key named
81
+ * beside its form (none given, no argument);
82
+ * - the label and glyphs of a chip or a button: its text children as a `Text`,
83
+ * the props naming its glyphs as an `Icon` before and after it.
84
+ */
85
+ export type Param = {
86
+ readonly prop: string;
87
+ readonly form: Form;
88
+ readonly optional?: boolean;
89
+ } | {
90
+ /** The value prop and its setter (or the setters Bloom takes for it, the first winning). */
91
+ readonly binding: readonly [value: string, set: string | readonly string[]];
92
+ readonly hole: 'boolean' | 'string' | 'number';
93
+ } | {
94
+ readonly text: true | string;
95
+ } | {
96
+ readonly options: Readonly<Record<string, Form | readonly [key: string, form: Form]>>;
97
+ } | {
98
+ readonly label: {
99
+ readonly leading?: string;
100
+ readonly trailing?: string;
101
+ };
102
+ };
103
+ export interface ComponentRule {
104
+ /** The language constructor. */
105
+ readonly node: string;
106
+ readonly params?: readonly Param[];
107
+ readonly props?: Readonly<Record<string, PropRule>>;
108
+ /** The element's children as the constructor's rest arguments, each a view. */
109
+ readonly children?: boolean;
110
+ /** Modifiers with no argument the node always takes (a `Header` drawn as Bloom's PageHeader: `.inPage()`). */
111
+ readonly always?: readonly string[];
112
+ /**
113
+ * A Bloom component (`module#export`) it is drawn only inside (a screen's
114
+ * scroll view in a `Screen`): its parity draws both sides in one.
115
+ */
116
+ readonly within?: string;
117
+ /**
118
+ * Components (`module#export`) whose context the Bloom component reads and
119
+ * the language's node does not: inside one (in the file), the element stays JSX.
120
+ */
121
+ readonly outside?: readonly string[];
122
+ /**
123
+ * A shell around one input, drawn by the input's node: its children are the
124
+ * input (`module#export`, by its own rule) between glyphs (`TextFieldIcon`),
125
+ * which are the node's `icon` and `trailingIcon`; its own props join the input's.
126
+ */
127
+ readonly shell?: {
128
+ readonly input: string;
129
+ readonly icon: string;
130
+ };
131
+ /**
132
+ * Props gathered into one modifier's object, each given one under its own
133
+ * name, its value carried as it is (`overscan={n}` into `.tuning({ overscan: n })`).
134
+ */
135
+ readonly gather?: {
136
+ readonly modifier: string;
137
+ readonly props: Readonly<Record<string, Form>>;
138
+ };
139
+ /** Props the Bloom component draws in a way no modifier of the node does, and how: each is the reason it stays JSX. */
140
+ readonly differs?: Readonly<Record<string, string>>;
141
+ /**
142
+ * The parts (`module#export`, each by its own rule) its children are, converted
143
+ * with it as one node: each child is one of them, a comment, or a `.map()` whose
144
+ * function returns one. The language keys a part itself (by its value).
145
+ */
146
+ readonly parts?: readonly string[];
147
+ /** The compound component (`module#export`) this is a part of: alone, it stays JSX. */
148
+ readonly partOf?: string;
149
+ /** A fragment among its children is its children, each one of them (React draws them so). */
150
+ readonly fragments?: true;
151
+ }
152
+ /** Bloom's dialog placements (`bottom`, `center`…), the language's `.presentAt()` tokens. */
153
+ export declare const DIALOG_PLACEMENT: Readonly<Record<string, string>>;
154
+ /** The breakpoints a responsive placement names over its `base`, `.presentAt()`'s tiers. */
155
+ export declare const PLACEMENT_TIERS: readonly string[];
156
+ /** Bloom's spacing in points (`12`) as the language's space token (`md`), the spec's scale turned round. */
157
+ export declare const SPACE: Readonly<Record<string, string>>;
158
+ /** `module#export` to its rule. */
159
+ export declare const COMPONENT_RULES: Readonly<Record<string, ComponentRule>>;
160
+ /**
161
+ * Bloom's typography components, each its Text in a text style
162
+ * (parity/text.cases.tsx, `textStyle`). `Blockquote` is a View around its Text.
163
+ */
164
+ export declare const TEXT_STYLES: Readonly<Record<string, string>>;
165
+ /** Components removed in Bloom 22 that apps on 21 still draw, and what replaces each (docs/migrating-to-22.mdx). */
166
+ export declare const REMOVED: Readonly<Record<string, string>>;
167
+ /**
168
+ * Bloom components that stay JSX whatever their props, and why: the language
169
+ * draws them, but not as a node a region can hold in their place.
170
+ */
171
+ export declare const KEPT: Readonly<Record<string, string>>;
172
+ /**
173
+ * A Bloom `Screen` returned by a route (parity/screen.cases.tsx, `ScreenHost`):
174
+ * its one child is the body's root, and several (a fragment's included) are a
175
+ * `Group`'s; its props are the root's screen modifiers. Its header element is
176
+ * its view: Bloom's PageHeader is `Header(…).inPage()`, the Screen's own header
177
+ * on every platform (a bare `Header` would be the system bar on iOS in a native
178
+ * stack). Its bottom bar is the screen's `.footer()`.
179
+ */
180
+ export declare const SCREEN: ComponentRule;
181
+ /** The rule for a Bloom component, when the checked-out language draws its node. */
182
+ export declare function ruleFor(module: string, imported: string): ComponentRule | undefined;