@codemoreira/esad 1.2.4 → 1.2.6

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/bin/esad.js CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
 
3
3
  const { program } = require('commander');
4
4
  const pkg = require('../package.json');
package/package.json CHANGED
@@ -1,12 +1,22 @@
1
1
  {
2
2
  "name": "@codemoreira/esad",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
4
4
  "description": "Easy Super App Development - Zero-Config CLI and DevTools for React Native Module Federation",
5
5
  "main": "src/plugin/index.js",
6
+ "types": "./src/plugin/index.d.ts",
6
7
  "exports": {
7
- ".": "./src/plugin/index.js",
8
- "./plugin": "./src/plugin/index.js",
9
- "./client": "./src/client/index.js"
8
+ ".": {
9
+ "types": "./src/plugin/index.d.ts",
10
+ "default": "./src/plugin/index.js"
11
+ },
12
+ "./plugin": {
13
+ "types": "./src/plugin/index.d.ts",
14
+ "default": "./src/plugin/index.js"
15
+ },
16
+ "./client": {
17
+ "types": "./src/client/index.d.ts",
18
+ "default": "./src/client/index.js"
19
+ }
10
20
  },
11
21
  "bin": {
12
22
  "esad": "./bin/esad.js"
@@ -26,5 +36,9 @@
26
36
  "cross-spawn": "^7.0.3",
27
37
  "fs-extra": "^11.2.0"
28
38
  },
29
- "devDependencies": {}
39
+ "devDependencies": {
40
+ "@rspack/core": "^1.7.9",
41
+ "@types/react": "^19.2.14",
42
+ "@types/react-native": "^0.72.8"
43
+ }
30
44
  }
@@ -1,47 +1,47 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const { runProcess } = require('../utils/process');
4
- const { getWorkspaceConfig } = require('../utils/config');
5
-
6
- module.exports = async (moduleName) => {
7
- const configObj = getWorkspaceConfig();
8
- if (!configObj) {
9
- console.error(`āŒ Error: Call this command from inside an ESAD workspace (esad.config.json not found).`);
10
- return;
11
- }
12
-
13
- const { projectName } = configObj.data;
14
- const isPrefixed = moduleName.startsWith(`${projectName}-`);
15
- const finalModuleName = isPrefixed ? moduleName : `${projectName}-\${moduleName}`;
16
-
17
- const workspaceDir = path.dirname(configObj.path);
18
- const targetDir = path.join(workspaceDir, finalModuleName);
19
-
20
- console.log(`\nšŸ“¦ Creating federated mini-app: ${finalModuleName}...\n`);
21
-
22
- try {
23
- await runProcess('npx', ['react-native@latest', 'init', finalModuleName], workspaceDir);
24
- console.log(`\nšŸ“¦ Installing ESAD dependencies...`);
25
- // Note: Assuming local link or npm install depends on final workflow
26
- await runProcess('npm', ['install', '@codemoreira/esad'], targetDir);
27
-
28
- const rspackContent = `import { withESAD } from '@codemoreira/esad/plugin';\n\nexport default withESAD({\n type: 'module',\n id: '${finalModuleName}'\n});\n`
29
- fs.writeFileSync(path.join(targetDir, 'rspack.config.mjs'), rspackContent);
30
- console.log(`āœ… Injected withESAD wrapper into rspack.config.mjs`);
31
-
32
- // Update package.json scripts
33
- const modPkgPath = path.join(targetDir, 'package.json');
34
- const modPkg = fs.readJsonSync(modPkgPath);
35
- modPkg.scripts = {
36
- ...modPkg.scripts,
37
- "start": "esad dev",
38
- "deploy": "esad deploy"
39
- };
40
- fs.writeJsonSync(modPkgPath, modPkg, { spaces: 2 });
41
- console.log(`āœ… Abstracted module scripts to use ESAD CLI.`);
42
-
43
- console.log(`\nšŸŽ‰ Module ${finalModuleName} is ready!`);
44
- } catch (err) {
45
- console.error(`āŒ Failed to scaffold module`, err.message);
46
- }
47
- };
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const { runProcess } = require('../utils/process');
4
+ const { getWorkspaceConfig } = require('../utils/config');
5
+
6
+ module.exports = async (moduleName) => {
7
+ const configObj = getWorkspaceConfig();
8
+ if (!configObj) {
9
+ console.error(`āŒ Error: Call this command from inside an ESAD workspace (esad.config.json not found).`);
10
+ return;
11
+ }
12
+
13
+ const { projectName } = configObj.data;
14
+ const isPrefixed = moduleName.startsWith(`${projectName}-`);
15
+ const finalModuleName = isPrefixed ? moduleName : `${projectName}-\${moduleName}`;
16
+
17
+ const workspaceDir = path.dirname(configObj.path);
18
+ const targetDir = path.join(workspaceDir, finalModuleName);
19
+
20
+ console.log(`\nšŸ“¦ Creating federated mini-app: ${finalModuleName}...\n`);
21
+
22
+ try {
23
+ await runProcess('npx', ['react-native@latest', 'init', finalModuleName], workspaceDir);
24
+ console.log(`\nšŸ“¦ Installing ESAD dependencies...`);
25
+ // Note: Assuming local link or npm install depends on final workflow
26
+ await runProcess('npm', ['install', '@codemoreira/esad'], targetDir);
27
+
28
+ const rspackContent = `import { withESAD } from '@codemoreira/esad/plugin';\n\nexport default withESAD({\n type: 'module',\n id: '${finalModuleName}'\n});\n`
29
+ fs.writeFileSync(path.join(targetDir, 'rspack.config.mjs'), rspackContent);
30
+ console.log(`āœ… Injected withESAD wrapper into rspack.config.mjs`);
31
+
32
+ // Update package.json scripts
33
+ const modPkgPath = path.join(targetDir, 'package.json');
34
+ const modPkg = fs.readJsonSync(modPkgPath);
35
+ modPkg.scripts = {
36
+ ...modPkg.scripts,
37
+ "start": "esad dev",
38
+ "deploy": "esad deploy"
39
+ };
40
+ fs.writeJsonSync(modPkgPath, modPkg, { spaces: 2 });
41
+ console.log(`āœ… Abstracted module scripts to use ESAD CLI.`);
42
+
43
+ console.log(`\nšŸŽ‰ Module ${finalModuleName} is ready!`);
44
+ } catch (err) {
45
+ console.error(`āŒ Failed to scaffold module`, err.message);
46
+ }
47
+ };
@@ -1,113 +1,113 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const { runProcess } = require('../utils/process');
4
- const templates = require('../templates/host');
5
-
6
- module.exports = async (projectName) => {
7
- const workspaceDir = path.join(process.cwd(), projectName);
8
- console.log(`\nšŸš€ Initializing ESAD Workspace: ${projectName}...\n`);
9
-
10
- fs.ensureDirSync(workspaceDir);
11
-
12
- const configPath = path.join(workspaceDir, 'esad.config.json');
13
- if (!fs.existsSync(configPath)) {
14
- const configTemplate = {
15
- projectName: projectName,
16
- registryUrl: "http://localhost:3000/modules",
17
- deployEndpoint: "http://localhost:3000/api/admin/modules/{{moduleId}}/versions",
18
- devModeEndpoint: "http://localhost:3000/api/admin/modules/{{moduleId}}"
19
- };
20
- fs.writeJsonSync(configPath, configTemplate, { spaces: 2 });
21
- console.log(`āœ… Generated dynamic configuration file: esad.config.json`);
22
- }
23
-
24
- const gitignorePath = path.join(workspaceDir, '.gitignore');
25
- if (!fs.existsSync(gitignorePath)) {
26
- const hostName = `${projectName}-host`;
27
- const gitignoreContent = `# ESAD Workspace Git Configuration\n` +
28
- `# Ignore everything by default\n` +
29
- `/*\n\n` +
30
- `# Exceptions: Track only the Host and Configs\n` +
31
- `!/${hostName}/\n` +
32
- `!/esad.config.json\n` +
33
- `!/.gitignore\n` +
34
- `\n# Ignore node_modules\n` +
35
- `node_modules/\n`;
36
- fs.writeFileSync(gitignorePath, gitignoreContent);
37
- console.log(`āœ… Generated .gitignore`);
38
- }
39
-
40
- const hostName = `${projectName}-host`;
41
- const hostDir = path.join(workspaceDir, hostName);
42
-
43
- try {
44
- console.log(`\nšŸ“¦ Scaffolding clean Expo project: ${hostName}...`);
45
- await runProcess('npx', ['create-expo-app', hostName, '--template', 'blank'], workspaceDir);
46
-
47
- console.log(`\nšŸ“¦ Installing ESAD, Re.Pack and UI dependencies into host...`);
48
- const hostPkgPath = path.join(hostDir, 'package.json');
49
- const hostPkg = fs.readJsonSync(hostPkgPath);
50
- const reactVersion = hostPkg.dependencies.react;
51
-
52
- const deps = [
53
- '@codemoreira/esad',
54
- '@callstack/repack@^5.2.5',
55
- '@rspack/core@^1.7.9',
56
- '@rspack/plugin-react-refresh@^1.6.1',
57
- '@callstack/repack-plugin-expo-modules',
58
- '@react-native-community/cli',
59
- 'nativewind',
60
- 'tailwindcss',
61
- 'postcss',
62
- 'autoprefixer',
63
- 'expo-secure-store',
64
- 'react-native-reanimated',
65
- 'react-native-safe-area-context',
66
- 'react-native-screens',
67
- 'expo-router',
68
- `react-dom@${reactVersion}`
69
- ];
70
- await runProcess('npm', ['install', ...deps], hostDir);
71
-
72
- // Re-read package.json to get the version after npm install updated it
73
- const updatedPkg = fs.readJsonSync(hostPkgPath);
74
-
75
- // Update package.json scripts to delegate to ESAD CLI
76
- updatedPkg.scripts = {
77
- ...updatedPkg.scripts,
78
- "start": "esad host start",
79
- "android": "esad host android",
80
- "ios": "esad host ios",
81
- "dev": "esad host dev"
82
- };
83
- fs.writeJsonSync(hostPkgPath, updatedPkg, { spaces: 2 });
84
- console.log(`āœ… Abstracted package.json scripts to use ESAD CLI.`);
85
-
86
- console.log(`\nšŸŽØ Configuring NativeWind & Tailwind...`);
87
- fs.writeFileSync(path.join(hostDir, 'tailwind.config.js'), templates.tailwindConfig);
88
- fs.writeFileSync(path.join(hostDir, 'babel.config.js'), templates.babelConfig);
89
-
90
- const rspackContent = `import { withESAD } from '@codemoreira/esad/plugin';\n\nexport default withESAD({\n type: 'host',\n id: '${hostName}'\n});\n`
91
- fs.writeFileSync(path.join(hostDir, 'rspack.config.mjs'), rspackContent);
92
-
93
- console.log(`\nšŸ” Scaffolding Auth & Navigation...`);
94
- fs.ensureDirSync(path.join(hostDir, 'providers'));
95
- fs.ensureDirSync(path.join(hostDir, 'hooks'));
96
- fs.ensureDirSync(path.join(hostDir, 'lib'));
97
- fs.ensureDirSync(path.join(hostDir, 'app', '(protected)', 'module'));
98
-
99
- fs.writeFileSync(path.join(hostDir, 'providers/auth.tsx'), templates.authProvider);
100
- fs.writeFileSync(path.join(hostDir, 'app/_layout.tsx'), templates.rootLayout);
101
- fs.writeFileSync(path.join(hostDir, 'app/login.tsx'), templates.loginPage);
102
- fs.writeFileSync(path.join(hostDir, 'app/global.css'), templates.globalCss);
103
- fs.writeFileSync(path.join(hostDir, 'lib/moduleLoader.ts'), templates.moduleLoader);
104
- fs.writeFileSync(path.join(hostDir, 'index.js'), templates.indexJs);
105
- fs.writeFileSync(path.join(hostDir, 'app/(protected)/index.tsx'), templates.dashboard);
106
- fs.writeFileSync(path.join(hostDir, 'app/(protected)/module/[id].tsx'), templates.modulePage);
107
-
108
- console.log(`\nšŸŽ‰ ESAD Workpace Initialized!`);
109
- console.log(`-> cd ${projectName}\n-> esad dev (to start Host)`);
110
- } catch (err) {
111
- console.error(`āŒ Failed to init Host:`, err.message);
112
- }
113
- };
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const { runProcess } = require('../utils/process');
4
+ const templates = require('../templates/host');
5
+
6
+ module.exports = async (projectName) => {
7
+ const workspaceDir = path.join(process.cwd(), projectName);
8
+ console.log(`\nšŸš€ Initializing ESAD Workspace: ${projectName}...\n`);
9
+
10
+ fs.ensureDirSync(workspaceDir);
11
+
12
+ const configPath = path.join(workspaceDir, 'esad.config.json');
13
+ if (!fs.existsSync(configPath)) {
14
+ const configTemplate = {
15
+ projectName: projectName,
16
+ registryUrl: "http://localhost:3000/modules",
17
+ deployEndpoint: "http://localhost:3000/api/admin/modules/{{moduleId}}/versions",
18
+ devModeEndpoint: "http://localhost:3000/api/admin/modules/{{moduleId}}"
19
+ };
20
+ fs.writeJsonSync(configPath, configTemplate, { spaces: 2 });
21
+ console.log(`āœ… Generated dynamic configuration file: esad.config.json`);
22
+ }
23
+
24
+ const gitignorePath = path.join(workspaceDir, '.gitignore');
25
+ if (!fs.existsSync(gitignorePath)) {
26
+ const hostName = `${projectName}-host`;
27
+ const gitignoreContent = `# ESAD Workspace Git Configuration\n` +
28
+ `# Ignore everything by default\n` +
29
+ `/*\n\n` +
30
+ `# Exceptions: Track only the Host and Configs\n` +
31
+ `!/${hostName}/\n` +
32
+ `!/esad.config.json\n` +
33
+ `!/.gitignore\n` +
34
+ `\n# Ignore node_modules\n` +
35
+ `node_modules/\n`;
36
+ fs.writeFileSync(gitignorePath, gitignoreContent);
37
+ console.log(`āœ… Generated .gitignore`);
38
+ }
39
+
40
+ const hostName = `${projectName}-host`;
41
+ const hostDir = path.join(workspaceDir, hostName);
42
+
43
+ try {
44
+ console.log(`\nšŸ“¦ Scaffolding clean Expo project: ${hostName}...`);
45
+ await runProcess('npx', ['create-expo-app', hostName, '--template', 'blank'], workspaceDir);
46
+
47
+ console.log(`\nšŸ“¦ Installing ESAD, Re.Pack and UI dependencies into host...`);
48
+ const hostPkgPath = path.join(hostDir, 'package.json');
49
+ const hostPkg = fs.readJsonSync(hostPkgPath);
50
+ const reactVersion = hostPkg.dependencies.react;
51
+
52
+ const deps = [
53
+ '@codemoreira/esad',
54
+ '@callstack/repack@^5.2.5',
55
+ '@rspack/core@^1.7.9',
56
+ '@rspack/plugin-react-refresh@^1.6.1',
57
+ '@callstack/repack-plugin-expo-modules',
58
+ '@react-native-community/cli',
59
+ 'nativewind',
60
+ 'tailwindcss',
61
+ 'postcss',
62
+ 'autoprefixer',
63
+ 'expo-secure-store',
64
+ 'react-native-reanimated',
65
+ 'react-native-safe-area-context',
66
+ 'react-native-screens',
67
+ 'expo-router',
68
+ `react-dom@${reactVersion}`
69
+ ];
70
+ await runProcess('npm', ['install', ...deps], hostDir);
71
+
72
+ // Re-read package.json to get the version after npm install updated it
73
+ const updatedPkg = fs.readJsonSync(hostPkgPath);
74
+
75
+ // Update package.json scripts to delegate to ESAD CLI
76
+ updatedPkg.scripts = {
77
+ ...updatedPkg.scripts,
78
+ "start": "esad host start",
79
+ "android": "esad host android",
80
+ "ios": "esad host ios",
81
+ "dev": "esad host dev"
82
+ };
83
+ fs.writeJsonSync(hostPkgPath, updatedPkg, { spaces: 2 });
84
+ console.log(`āœ… Abstracted package.json scripts to use ESAD CLI.`);
85
+
86
+ console.log(`\nšŸŽØ Configuring NativeWind & Tailwind...`);
87
+ fs.writeFileSync(path.join(hostDir, 'tailwind.config.js'), templates.tailwindConfig);
88
+ fs.writeFileSync(path.join(hostDir, 'babel.config.js'), templates.babelConfig);
89
+
90
+ const rspackContent = `import { withESAD } from '@codemoreira/esad/plugin';\n\nexport default withESAD({\n type: 'host',\n id: '${hostName}'\n});\n`
91
+ fs.writeFileSync(path.join(hostDir, 'rspack.config.mjs'), rspackContent);
92
+
93
+ console.log(`\nšŸ” Scaffolding Auth & Navigation...`);
94
+ fs.ensureDirSync(path.join(hostDir, 'providers'));
95
+ fs.ensureDirSync(path.join(hostDir, 'hooks'));
96
+ fs.ensureDirSync(path.join(hostDir, 'lib'));
97
+ fs.ensureDirSync(path.join(hostDir, 'app', '(protected)', 'module'));
98
+
99
+ fs.writeFileSync(path.join(hostDir, 'providers/auth.tsx'), templates.authProvider);
100
+ fs.writeFileSync(path.join(hostDir, 'app/_layout.tsx'), templates.rootLayout);
101
+ fs.writeFileSync(path.join(hostDir, 'app/login.tsx'), templates.loginPage);
102
+ fs.writeFileSync(path.join(hostDir, 'app/global.css'), templates.globalCss);
103
+ fs.writeFileSync(path.join(hostDir, 'lib/moduleLoader.ts'), templates.moduleLoader);
104
+ fs.writeFileSync(path.join(hostDir, 'index.js'), templates.indexJs);
105
+ fs.writeFileSync(path.join(hostDir, 'app/(protected)/index.tsx'), templates.dashboard);
106
+ fs.writeFileSync(path.join(hostDir, 'app/(protected)/module/[id].tsx'), templates.modulePage);
107
+
108
+ console.log(`\nšŸŽ‰ ESAD Workpace Initialized!`);
109
+ console.log(`-> cd ${projectName}\n-> esad dev (to start Host)`);
110
+ } catch (err) {
111
+ console.error(`āŒ Failed to init Host:`, err.message);
112
+ }
113
+ };
@@ -1,201 +1,201 @@
1
- module.exports = {
2
- tailwindConfig: `/** @type {import('tailwindcss').Config} */
3
- module.exports = {
4
- content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}", "./lib/**/*.{js,jsx,ts,tsx}"],
5
- presets: [require("nativewind/preset")],
6
- theme: {
7
- extend: {},
8
- },
9
- plugins: [],
10
- };`,
11
-
12
- babelConfig: `module.exports = function (api) {
13
- api.cache(true);
14
- return {
15
- presets: [
16
- ["babel-preset-expo", { jsxImportSource: "nativewind" }],
17
- "nativewind/babel",
18
- ],
19
- };
20
- };`,
21
-
22
- authProvider: `import { createContext, useEffect, useState, useContext } from "react";
23
- import * as SecureStore from "expo-secure-store";
24
-
25
- const AuthContext = createContext({});
26
-
27
- export function AuthProvider({ children }) {
28
- const [token, setToken] = useState(null);
29
- const [isInitialized, setIsInitialized] = useState(false);
30
-
31
- useEffect(() => {
32
- SecureStore.getItemAsync("token").then((val) => {
33
- setToken(val);
34
- setIsInitialized(true);
35
- });
36
- }, []);
37
-
38
- const login = (mockToken = "session_token") => {
39
- setToken(mockToken);
40
- SecureStore.setItemAsync("token", mockToken);
41
- };
42
-
43
- const logout = () => {
44
- setToken(null);
45
- SecureStore.deleteItemAsync("token");
46
- };
47
-
48
- return (
49
- <AuthContext.Provider value={{ token, login, logout, isInitialized }}>
50
- {children}
51
- </AuthContext.Provider>
52
- );
53
- }
54
-
55
- export const useAuth = () => useContext(AuthContext);`,
56
-
57
- rootLayout: `import { Stack, router } from "expo-router";
58
- import { useEffect } from "react";
59
- import { AuthProvider, useAuth } from "@/providers/auth";
60
- import { SafeAreaProvider } from "react-native-safe-area-context";
61
- import "./global.css";
62
-
63
- export default function RootLayout() {
64
- return (
65
- <SafeAreaProvider>
66
- <AuthProvider>
67
- <RootNavigation />
68
- </AuthProvider>\n </SafeAreaProvider>
69
- );
70
- }
71
-
72
- function RootNavigation() {
73
- const { token, isInitialized } = useAuth();
74
-
75
- useEffect(() => {
76
- if (!isInitialized) return;\n\n // Global SuperApp Registry
77
- globalThis.__SUPERAPP__ = {
78
- getToken: () => token,
79
- navigate: (route, params) => router.push({ pathname: route, params })
80
- };\n }, [isInitialized, token]);
81
-
82
- if (!isInitialized) return null;
83
-
84
- return (
85
- <Stack screenOptions={{ headerShown: false }}>
86
- <Stack.Screen name="login" redirect={!!token} />
87
- <Stack.Screen name="(protected)" redirect={!token} />
88
- </Stack>
89
- );
90
- }`,
91
-
92
- loginPage: `import { View, Text, TouchableOpacity } from "react-native";
93
- import { useAuth } from "@/providers/auth";
94
-
95
- export default function LoginPage() {
96
- const { login } = useAuth();
97
-
98
- return (
99
- <View className="flex-1 items-center justify-center bg-slate-50 p-6">
100
- <View className="w-full max-w-sm bg-white p-8 rounded-3xl shadow-xl border border-slate-100">
101
- <Text className="text-3xl font-bold text-slate-900 mb-2">Welcome</Text>
102
- <Text className="text-slate-500 mb-8">Sign in to access your SuperApp modules</Text>\n
103
- <TouchableOpacity
104
- onPress={() => login()}
105
- className="w-full bg-indigo-600 py-4 rounded-2xl items-center shadow-lg active:bg-indigo-700"
106
- >
107
- <Text className="text-white font-semibold text-lg">Entrar no App</Text>
108
- </TouchableOpacity>
109
- </View>
110
- </View>
111
- );
112
- }`,
113
-
114
- globalCss: `@tailwind base;\n@tailwind components;\n@tailwind utilities;`,
115
-
116
- moduleLoader: `import { ScriptManager } from "@callstack/repack/client";
117
-
118
- export async function loadModule(config) {
119
- await ScriptManager.shared.addScript({
120
- id: config.id,
121
- url: config.url
122
- });
123
-
124
- const container = global[config.scope];
125
- if (!container) throw new Error("Module " + config.scope + " not found");
126
-
127
- await container.init(__webpack_share_scopes__.default);
128
- const factory = await container.get(config.module);
129
- return factory();
130
- }`,
131
-
132
- dashboard: `import { View, Text, ScrollView, TouchableOpacity } from "react-native";
133
- import { Link } from "expo-router";
134
- import { useAuth } from "@/providers/auth";
135
-
136
- const MOCK_MODULES = [
137
- { id: 'mod1', name: 'Sales Dashboard', icon: 'šŸ“Š' },
138
- { id: 'mod2', name: 'Inventory Manager', icon: 'šŸ“¦' },
139
- ];
140
-
141
- export default function Dashboard() {
142
- const { logout } = useAuth();
143
-
144
- return (
145
- <ScrollView className="flex-1 bg-slate-50 p-6 pt-16">
146
- <View className="flex-row justify-between items-center mb-8">
147
- <View>
148
- <Text className="text-sm text-slate-500">Welcome back,</Text>
149
- <Text className="text-2xl font-bold text-slate-900">Explorer</Text>
150
- </View>
151
- <TouchableOpacity onPress={logout} className="p-2">
152
- <Text className="text-red-500 font-medium">Logout</Text>
153
- </TouchableOpacity>
154
- </View>
155
-
156
- <Text className="text-lg font-semibold text-slate-800 mb-4">Your Modules</Text>
157
-
158
- {MOCK_MODULES.map(m => (
159
- <Link key={m.id} href={\`/(protected)/module/\${m.id}\`} asChild>
160
- <TouchableOpacity className="bg-white p-6 rounded-2xl mb-4 shadow-sm border border-slate-100 flex-row items-center">
161
- <Text className="text-3xl mr-4">{m.icon}</Text>
162
- <View className="flex-1">
163
- <Text className="text-lg font-bold text-slate-900">{m.name}</Text>
164
- <Text className="text-slate-500">Tap to open module</Text>
165
- </View>
166
- </TouchableOpacity>
167
- </Link>
168
- ))}
169
- </ScrollView>
170
- );
171
- }`,
172
-
173
- modulePage: `import { useLocalSearchParams } from "expo-router";
174
- import { View, Text, ActivityIndicator } from "react-native";
175
- import { useEffect, useState } from "react";
176
- import { loadModule } from "@/lib/moduleLoader";
177
-
178
- export default function ModulePage() {
179
- const { id } = useLocalSearchParams();
180
- const [Module, setModule] = useState(null);
181
- const [error, setError] = useState(null);
182
-
183
- useEffect(() => {\n // In real app, fetch config from registry by id\n setError("Module dynamic loading requires a running CDN and Build setup.");\n }, [id]);
184
-
185
- if (error) return (
186
- <View className="flex-1 items-center justify-center p-10 bg-white">
187
- <Text className="text-red-500 text-center font-medium mb-4">{error}</Text>
188
- <Text className="text-slate-400 text-center text-sm">Follow the README to setup your module registry.</Text>
189
- </View>
190
- );
191
-
192
- return (
193
- <View className="flex-1 bg-white items-center justify-center">
194
- <ActivityIndicator size="large" color="#4f46e5" />
195
- <Text className="mt-4 text-slate-500">Loading federated module...</Text>
196
- </View>
197
- );
198
- }`,
199
-
200
- indexJs: `import "expo-router/entry";`
201
- };
1
+ module.exports = {
2
+ tailwindConfig: `/** @type {import('tailwindcss').Config} */
3
+ module.exports = {
4
+ content: ["./app/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}", "./lib/**/*.{js,jsx,ts,tsx}"],
5
+ presets: [require("nativewind/preset")],
6
+ theme: {
7
+ extend: {},
8
+ },
9
+ plugins: [],
10
+ };`,
11
+
12
+ babelConfig: `module.exports = function (api) {
13
+ api.cache(true);
14
+ return {
15
+ presets: [
16
+ ["babel-preset-expo", { jsxImportSource: "nativewind" }],
17
+ "nativewind/babel",
18
+ ],
19
+ };
20
+ };`,
21
+
22
+ authProvider: `import { createContext, useEffect, useState, useContext } from "react";
23
+ import * as SecureStore from "expo-secure-store";
24
+
25
+ const AuthContext = createContext({});
26
+
27
+ export function AuthProvider({ children }) {
28
+ const [token, setToken] = useState(null);
29
+ const [isInitialized, setIsInitialized] = useState(false);
30
+
31
+ useEffect(() => {
32
+ SecureStore.getItemAsync("token").then((val) => {
33
+ setToken(val);
34
+ setIsInitialized(true);
35
+ });
36
+ }, []);
37
+
38
+ const login = (mockToken = "session_token") => {
39
+ setToken(mockToken);
40
+ SecureStore.setItemAsync("token", mockToken);
41
+ };
42
+
43
+ const logout = () => {
44
+ setToken(null);
45
+ SecureStore.deleteItemAsync("token");
46
+ };
47
+
48
+ return (
49
+ <AuthContext.Provider value={{ token, login, logout, isInitialized }}>
50
+ {children}
51
+ </AuthContext.Provider>
52
+ );
53
+ }
54
+
55
+ export const useAuth = () => useContext(AuthContext);`,
56
+
57
+ rootLayout: `import { Stack, router } from "expo-router";
58
+ import { useEffect } from "react";
59
+ import { AuthProvider, useAuth } from "@/providers/auth";
60
+ import { SafeAreaProvider } from "react-native-safe-area-context";
61
+ import "./global.css";
62
+
63
+ export default function RootLayout() {
64
+ return (
65
+ <SafeAreaProvider>
66
+ <AuthProvider>
67
+ <RootNavigation />
68
+ </AuthProvider>\n </SafeAreaProvider>
69
+ );
70
+ }
71
+
72
+ function RootNavigation() {
73
+ const { token, isInitialized } = useAuth();
74
+
75
+ useEffect(() => {
76
+ if (!isInitialized) return;\n\n // Global SuperApp Registry
77
+ globalThis.__SUPERAPP__ = {
78
+ getToken: () => token,
79
+ navigate: (route, params) => router.push({ pathname: route, params })
80
+ };\n }, [isInitialized, token]);
81
+
82
+ if (!isInitialized) return null;
83
+
84
+ return (
85
+ <Stack screenOptions={{ headerShown: false }}>
86
+ <Stack.Screen name="login" redirect={!!token} />
87
+ <Stack.Screen name="(protected)" redirect={!token} />
88
+ </Stack>
89
+ );
90
+ }`,
91
+
92
+ loginPage: `import { View, Text, TouchableOpacity } from "react-native";
93
+ import { useAuth } from "@/providers/auth";
94
+
95
+ export default function LoginPage() {
96
+ const { login } = useAuth();
97
+
98
+ return (
99
+ <View className="flex-1 items-center justify-center bg-slate-50 p-6">
100
+ <View className="w-full max-w-sm bg-white p-8 rounded-3xl shadow-xl border border-slate-100">
101
+ <Text className="text-3xl font-bold text-slate-900 mb-2">Welcome</Text>
102
+ <Text className="text-slate-500 mb-8">Sign in to access your SuperApp modules</Text>\n
103
+ <TouchableOpacity
104
+ onPress={() => login()}
105
+ className="w-full bg-indigo-600 py-4 rounded-2xl items-center shadow-lg active:bg-indigo-700"
106
+ >
107
+ <Text className="text-white font-semibold text-lg">Entrar no App</Text>
108
+ </TouchableOpacity>
109
+ </View>
110
+ </View>
111
+ );
112
+ }`,
113
+
114
+ globalCss: `@tailwind base;\n@tailwind components;\n@tailwind utilities;`,
115
+
116
+ moduleLoader: `import { ScriptManager } from "@callstack/repack/client";
117
+
118
+ export async function loadModule(config) {
119
+ await ScriptManager.shared.addScript({
120
+ id: config.id,
121
+ url: config.url
122
+ });
123
+
124
+ const container = global[config.scope];
125
+ if (!container) throw new Error("Module " + config.scope + " not found");
126
+
127
+ await container.init(__webpack_share_scopes__.default);
128
+ const factory = await container.get(config.module);
129
+ return factory();
130
+ }`,
131
+
132
+ dashboard: `import { View, Text, ScrollView, TouchableOpacity } from "react-native";
133
+ import { Link } from "expo-router";
134
+ import { useAuth } from "@/providers/auth";
135
+
136
+ const MOCK_MODULES = [
137
+ { id: 'mod1', name: 'Sales Dashboard', icon: 'šŸ“Š' },
138
+ { id: 'mod2', name: 'Inventory Manager', icon: 'šŸ“¦' },
139
+ ];
140
+
141
+ export default function Dashboard() {
142
+ const { logout } = useAuth();
143
+
144
+ return (
145
+ <ScrollView className="flex-1 bg-slate-50 p-6 pt-16">
146
+ <View className="flex-row justify-between items-center mb-8">
147
+ <View>
148
+ <Text className="text-sm text-slate-500">Welcome back,</Text>
149
+ <Text className="text-2xl font-bold text-slate-900">Explorer</Text>
150
+ </View>
151
+ <TouchableOpacity onPress={logout} className="p-2">
152
+ <Text className="text-red-500 font-medium">Logout</Text>
153
+ </TouchableOpacity>
154
+ </View>
155
+
156
+ <Text className="text-lg font-semibold text-slate-800 mb-4">Your Modules</Text>
157
+
158
+ {MOCK_MODULES.map(m => (
159
+ <Link key={m.id} href={\`/(protected)/module/\${m.id}\`} asChild>
160
+ <TouchableOpacity className="bg-white p-6 rounded-2xl mb-4 shadow-sm border border-slate-100 flex-row items-center">
161
+ <Text className="text-3xl mr-4">{m.icon}</Text>
162
+ <View className="flex-1">
163
+ <Text className="text-lg font-bold text-slate-900">{m.name}</Text>
164
+ <Text className="text-slate-500">Tap to open module</Text>
165
+ </View>
166
+ </TouchableOpacity>
167
+ </Link>
168
+ ))}
169
+ </ScrollView>
170
+ );
171
+ }`,
172
+
173
+ modulePage: `import { useLocalSearchParams } from "expo-router";
174
+ import { View, Text, ActivityIndicator } from "react-native";
175
+ import { useEffect, useState } from "react";
176
+ import { loadModule } from "@/lib/moduleLoader";
177
+
178
+ export default function ModulePage() {
179
+ const { id } = useLocalSearchParams();
180
+ const [Module, setModule] = useState(null);
181
+ const [error, setError] = useState(null);
182
+
183
+ useEffect(() => {\n // In real app, fetch config from registry by id\n setError("Module dynamic loading requires a running CDN and Build setup.");\n }, [id]);
184
+
185
+ if (error) return (
186
+ <View className="flex-1 items-center justify-center p-10 bg-white">
187
+ <Text className="text-red-500 text-center font-medium mb-4">{error}</Text>
188
+ <Text className="text-slate-400 text-center text-sm">Follow the README to setup your module registry.</Text>
189
+ </View>
190
+ );
191
+
192
+ return (
193
+ <View className="flex-1 bg-white items-center justify-center">
194
+ <ActivityIndicator size="large" color="#4f46e5" />
195
+ <Text className="mt-4 text-slate-500">Loading federated module...</Text>
196
+ </View>
197
+ );
198
+ }`,
199
+
200
+ indexJs: `import "expo-router/entry";`
201
+ };
@@ -0,0 +1,11 @@
1
+ import { Dispatch, SetStateAction } from 'react';
2
+
3
+ export interface ESADEventEmitter {
4
+ set(key: string, value: any): void;
5
+ get(key: string): any;
6
+ subscribe(key: string, callback: (value: any) => void): () => void;
7
+ }
8
+
9
+ export const ESADState: ESADEventEmitter;
10
+
11
+ export function useESADState<T>(key: string, initialValue?: T): [T, Dispatch<SetStateAction<T>>];
@@ -0,0 +1,9 @@
1
+ import * as Rspack from '@rspack/core';
2
+
3
+ export interface ESADPluginOptions {
4
+ type: 'host' | 'module';
5
+ name?: string;
6
+ cdnUrl?: string;
7
+ }
8
+
9
+ export function withESAD(config: Rspack.Configuration, options: ESADPluginOptions): Rspack.Configuration;
@@ -1,41 +1,126 @@
1
+ const path = require('node:path');
2
+ const fs = require('node:fs');
1
3
  const Repack = require('@callstack/repack');
4
+ const { ExpoModulesPlugin } = require('@callstack/repack-plugin-expo-modules');
5
+ const { ProvidePlugin, DefinePlugin } = require('@rspack/core');
2
6
 
3
7
  /**
4
8
  * ESAD Re.Pack Plugin Wrapper
5
- * Abstracts away the boilerplate of Module Federation for SuperApps.
9
+ * Abstracts away the boilerplate of Module Federation and SDK integration for SuperApps.
6
10
  *
11
+ * @param {Object} env Rspack environment
7
12
  * @param {Object} options
8
13
  * @param {string} options.type 'host' | 'module'
9
14
  * @param {string} options.id Unique module or host ID
15
+ * @param {string} options.dirname Base directory (__dirname)
16
+ * @param {Object} [options.shared] Additional shared dependencies
17
+ * @param {Object} [options.exposes] Modules to expose (for modules)
18
+ * @param {Object} [options.remotes] Remote modules (for host)
10
19
  */
11
- function withESAD(options) {
12
- return (env) => {
13
- // In a real scenario, we merge heavily with Repack.getTemplateConfig here
14
- console.log(`[ESAD Plugin] Applying Zero-Config Re.Pack profile for ${options.type.toUpperCase()}: ${options.id}`);
15
-
16
- // Ensure the esad state library is ALWAYS shared
17
- const sharedConfig = {
18
- react: { singleton: true, eager: options.type === 'host' },
19
- 'react-native': { singleton: true, eager: options.type === 'host' },
20
- 'esad/client': { singleton: true, eager: true } // Crucial for Global State
21
- };
20
+ function withESAD(env, options) {
21
+ const isDev = env.dev !== false;
22
+ const dirname = options.dirname;
23
+ const pkgPath = path.resolve(dirname, 'package.json');
24
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
25
+ const id = options.id.replace(/-/g, '_');
22
26
 
23
- return {
24
- // Configuration abstraction
25
- plugins: [
26
- new Repack.plugins.ModuleFederationPlugin({
27
- name: options.id.replace(/-/g, '_'),
28
- shared: sharedConfig,
29
- // If type is module, also configure exposes
30
- ...(options.type === 'module' && {
31
- exposes: {
32
- './App': './src/App'
33
- }
34
- })
35
- })
36
- ]
37
- };
27
+ console.log(`[ESAD] Applying Mega-Zero-Config profile for ${options.type.toUpperCase()}: ${id}`);
28
+
29
+ const config = {
30
+ context: dirname,
31
+ entry: options.entry || './index.js',
32
+ resolve: {
33
+ ...Repack.getResolveOptions(),
34
+ alias: {
35
+ '@': path.resolve(dirname, '.'),
36
+ // Internal MFv2 & Re.Pack Aliases (Magic)
37
+ '@module-federation/runtime/helpers': path.resolve(dirname, 'node_modules/@module-federation/runtime/dist/helpers.js'),
38
+ '@module-federation/error-codes/browser': path.resolve(dirname, 'node_modules/@module-federation/error-codes/dist/browser.cjs'),
39
+ '@module-federation/sdk': path.resolve(dirname, 'node_modules/@module-federation/sdk'),
40
+
41
+ // ESAD SDK Aliases (Zero-Config)
42
+ '@codemoreira/esad/client': path.resolve(dirname, 'node_modules/@codemoreira/esad/src/client/index.js'),
43
+
44
+ ...Repack.getResolveOptions().alias,
45
+ ...options.alias,
46
+ }
47
+ },
48
+ module: {
49
+ rules: [
50
+ {
51
+ oneOf: [
52
+ {
53
+ test: /\.[cm]?[jt]sx?$/,
54
+ include: [
55
+ /node_modules[\\/]react-native/,
56
+ /node_modules[\\/]@react-native/,
57
+ ],
58
+ type: 'javascript/auto',
59
+ use: {
60
+ loader: '@callstack/repack/babel-swc-loader',
61
+ options: {
62
+ sourceMaps: true,
63
+ parallel: true,
64
+ },
65
+ },
66
+ },
67
+ ...Repack.getJsTransformRules(),
68
+ ]
69
+ },
70
+ ...Repack.getAssetTransformRules(),
71
+ ],
72
+ },
73
+ plugins: [
74
+ new ProvidePlugin({
75
+ process: 'process/browser',
76
+ }),
77
+ new DefinePlugin({
78
+ 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production'),
79
+ '__DEV__': JSON.stringify(isDev),
80
+ }),
81
+ new ExpoModulesPlugin(),
82
+ new Repack.RepackPlugin(),
83
+ new Repack.plugins.ModuleFederationPluginV2({
84
+ name: id,
85
+ filename: `${id}.container.js.bundle`,
86
+ remotes: options.remotes || {},
87
+ exposes: options.exposes || {},
88
+ dts: false,
89
+ dev: isDev,
90
+ shared: {
91
+ 'react': { singleton: true, eager: true, requiredVersion: pkg.dependencies.react },
92
+ 'react/jsx-runtime': { singleton: true, eager: true, requiredVersion: pkg.dependencies.react },
93
+ 'react-native': { singleton: true, eager: true, requiredVersion: pkg.dependencies['react-native'] },
94
+ 'react-native-safe-area-context': { singleton: true, eager: true, requiredVersion: pkg.dependencies['react-native-safe-area-context'] },
95
+ '@codemoreira/esad': { singleton: true, eager: true },
96
+ ...options.shared
97
+ }
98
+ })
99
+ ],
38
100
  };
101
+
102
+ // Add Host-specific DevServer magic for Expo
103
+ if (options.type === 'host') {
104
+ config.devServer = {
105
+ setupMiddlewares: (middlewares) => {
106
+ middlewares.unshift((req, res, next) => {
107
+ if (req.url.startsWith('/.expo/.virtual-metro-entry.bundle')) {
108
+ const query = req.url.split('?')[1];
109
+ const isMap = req.url.includes('.map');
110
+ const target = isMap ? '/index.bundle.map' : '/index.bundle';
111
+ const location = query ? `${target}?${query}` : target;
112
+ res.writeHead(302, { Location: location });
113
+ res.end();
114
+ return;
115
+ }
116
+ next();
117
+ });
118
+ return middlewares;
119
+ },
120
+ };
121
+ }
122
+
123
+ return config;
39
124
  }
40
125
 
41
126
  module.exports = { withESAD };