frontend-hamroun 1.2.65 → 1.2.66

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.
@@ -0,0 +1,75 @@
1
+ //go:build js && wasm
2
+ // +build js,wasm
3
+
4
+ package main
5
+
6
+ import (
7
+ "encoding/json"
8
+ "fmt"
9
+ "syscall/js"
10
+ )
11
+
12
+ // Example Go function to be called from JavaScript
13
+ func add(this js.Value, args []js.Value) interface{} {
14
+ if len(args) != 2 {
15
+ return js.ValueOf("Error: Expected two arguments")
16
+ }
17
+
18
+ a := args[0].Int()
19
+ b := args[1].Int()
20
+ return js.ValueOf(a + b)
21
+ }
22
+
23
+ // Process complex data in Go
24
+ func processData(this js.Value, args []js.Value) interface{} {
25
+ if len(args) == 0 {
26
+ return js.ValueOf("Error: Expected at least one argument")
27
+ }
28
+
29
+ // Get input data
30
+ data := args[0]
31
+ if data.Type() != js.TypeObject {
32
+ return js.ValueOf("Error: Expected JSON object")
33
+ }
34
+
35
+ // Convert JS object to Go map
36
+ jsonStr := js.Global().Get("JSON").Call("stringify", data).String()
37
+ var inputMap map[string]interface{}
38
+ if err := json.Unmarshal([]byte(jsonStr), &inputMap); err != nil {
39
+ return js.ValueOf(fmt.Sprintf("Error parsing JSON: %s", err.Error()))
40
+ }
41
+
42
+ // Add new fields
43
+ inputMap["processed"] = true
44
+ inputMap["processor"] = "Go WASM"
45
+
46
+ // Add some computed fields
47
+ if values, ok := inputMap["values"].([]interface{}); ok {
48
+ sum := 0.0
49
+ for _, v := range values {
50
+ if num, ok := v.(float64); ok {
51
+ sum += num
52
+ }
53
+ }
54
+ inputMap["sum"] = sum
55
+ }
56
+
57
+ // Convert back to JS
58
+ resultJSON, err := json.Marshal(inputMap)
59
+ if err != nil {
60
+ return js.ValueOf(fmt.Sprintf("Error generating JSON: %s", err.error()))
61
+ }
62
+
63
+ return js.ValueOf(string(resultJSON))
64
+ }
65
+
66
+ func main() {
67
+ fmt.Println("Go WASM Module initialized")
68
+
69
+ // Register functions to be callable from JavaScript
70
+ js.Global().Set("goAdd", js.FuncOf(add))
71
+ js.Global().Set("goProcessData", js.FuncOf(processData))
72
+
73
+ // Keep the program running
74
+ <-make(chan bool)
75
+ }
@@ -0,0 +1,3 @@
1
+ module wasmapp
2
+
3
+ go 1.23.6
@@ -0,0 +1,21 @@
1
+ # Frontend Hamroun - Go WebAssembly Template
2
+
3
+ This template demonstrates integration between Frontend Hamroun and Go WebAssembly for high-performance web applications.
4
+
5
+ ## Features
6
+
7
+ - 🔄 Go + WebAssembly integration
8
+ - ⚡ High-performance computation in the browser
9
+ - 🔍 Typed API for Go WASM functions
10
+ - 🔧 Automated build process for Go code
11
+ - 🧩 Example Go WASM modules and usage
12
+
13
+ ## Prerequisites
14
+
15
+ - [Node.js](https://nodejs.org/) (v14+)
16
+ - [Go](https://golang.org/dl/) (v1.16+)
17
+
18
+ ## Getting Started
19
+
20
+ 1. Install dependencies:
21
+
@@ -0,0 +1,218 @@
1
+ import { execSync } from 'child_process';
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname, resolve, join } from 'path';
4
+ import fs from 'fs';
5
+ import os from 'os';
6
+
7
+ // Get __dirname equivalent in ESM
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ // Check if running on Windows
12
+ const isWindows = os.platform() === 'win32';
13
+
14
+ // Check if Go is installed
15
+ function checkGoInstallation() {
16
+ try {
17
+ const output = execSync('go version', { encoding: 'utf8' });
18
+ console.log(`✓ Found Go: ${output.trim()}`);
19
+ return true;
20
+ } catch (error) {
21
+ console.error('✗ Go is not installed or not in PATH');
22
+ console.error('Please install Go from https://golang.org/dl/');
23
+ return false;
24
+ }
25
+ }
26
+
27
+ // Build Go WASM modules
28
+ async function buildWasmModules() {
29
+ // Check if Go is installed
30
+ if (!checkGoInstallation()) {
31
+ process.exit(1);
32
+ }
33
+
34
+ // Directory containing Go source files
35
+ const goSourceDir = resolve(__dirname, 'src', 'wasm');
36
+
37
+ // Output directory for WASM files
38
+ const wasmOutputDir = resolve(__dirname, 'public', 'wasm');
39
+
40
+ // Create output directory if it doesn't exist
41
+ if (!fs.existsSync(wasmOutputDir)) {
42
+ fs.mkdirSync(wasmOutputDir, { recursive: true });
43
+ }
44
+
45
+ // Get the Go root directory
46
+ const goRoot = execSync('go env GOROOT', { encoding: 'utf8' }).trim();
47
+
48
+ // Copy the wasm_exec.js file to the output directory
49
+ const wasmExecJsPath = join(goRoot, 'misc', 'wasm', 'wasm_exec.js');
50
+ const wasmExecJsDest = join(wasmOutputDir, 'wasm_exec.js');
51
+
52
+ console.log(`Copying ${wasmExecJsPath} to ${wasmExecJsDest}`);
53
+ fs.copyFileSync(wasmExecJsPath, wasmExecJsDest);
54
+
55
+ // Build all Go files in the WASM directory
56
+ if (fs.existsSync(goSourceDir)) {
57
+ const goFiles = fs.readdirSync(goSourceDir)
58
+ .filter(file => file.endsWith('.go'));
59
+
60
+ if (goFiles.length === 0) {
61
+ console.log('No Go files found in src/wasm');
62
+ return;
63
+ }
64
+
65
+ for (const goFile of goFiles) {
66
+ const goFilePath = join(goSourceDir, goFile);
67
+ const wasmFileName = goFile.replace('.go', '.wasm');
68
+ const wasmFilePath = join(wasmOutputDir, wasmFileName);
69
+
70
+ console.log(`Building ${goFile} to ${wasmFilePath}`);
71
+
72
+ try {
73
+ // Create a unique temporary directory with timestamp
74
+ const timestamp = Date.now();
75
+ const tempDir = join(os.tmpdir(), `go-wasm-build-${timestamp}`);
76
+
77
+ // Ensure the directory is clean (doesn't exist from previous builds)
78
+ if (fs.existsSync(tempDir)) {
79
+ fs.rmSync(tempDir, { recursive: true, force: true });
80
+ }
81
+
82
+ fs.mkdirSync(tempDir, { recursive: true });
83
+
84
+ // Copy the Go file to the temp directory
85
+ const tempGoFile = join(tempDir, goFile);
86
+ fs.copyFileSync(goFilePath, tempGoFile);
87
+
88
+ // Initialize Go module
89
+ console.log(`Initializing Go module in ${tempDir}`);
90
+ execSync(`go mod init wasmapp`, { cwd: tempDir });
91
+
92
+ // Build the WASM module with OS-specific command
93
+ if (isWindows) {
94
+ // Fix: Windows command without spaces in environment variables
95
+ // and using environment object instead of command-line args
96
+ execSync(`go build -o "${wasmFilePath}" "${tempGoFile}"`, {
97
+ cwd: tempDir,
98
+ env: {
99
+ ...process.env,
100
+ GOOS: 'js',
101
+ GOARCH: 'wasm'
102
+ }
103
+ });
104
+ } else {
105
+ // Unix/Linux/Mac command
106
+ execSync(`GOOS=js GOARCH=wasm go build -o "${wasmFilePath}" "${tempGoFile}"`, {
107
+ cwd: tempDir
108
+ });
109
+ }
110
+
111
+ // Clean up temporary directory
112
+ fs.rmSync(tempDir, { recursive: true, force: true });
113
+
114
+ console.log(`✓ Successfully built ${wasmFileName}`);
115
+ } catch (error) {
116
+ console.error(`✗ Error building ${goFile}:`);
117
+ console.error(error.message);
118
+ if (error.stdout) console.error(error.stdout.toString());
119
+ if (error.stderr) console.error(error.stderr.toString());
120
+ }
121
+ }
122
+ } else {
123
+ console.log(`Go source directory ${goSourceDir} not found, creating it...`);
124
+ fs.mkdirSync(goSourceDir, { recursive: true });
125
+
126
+ // Create an example Go file if the directory is empty
127
+ const exampleGoFile = join(goSourceDir, 'example.go');
128
+ const exampleGoContent = `//go:build js && wasm
129
+ // +build js,wasm
130
+
131
+ package main
132
+
133
+ import (
134
+ "encoding/json"
135
+ "fmt"
136
+ "syscall/js"
137
+ )
138
+
139
+ // Example Go function to be called from JavaScript
140
+ func add(this js.Value, args []js.Value) interface{} {
141
+ if len(args) != 2 {
142
+ return js.ValueOf("Error: Expected two arguments")
143
+ }
144
+
145
+ a := args[0].Int()
146
+ b := args[1].Int()
147
+ return js.ValueOf(a + b)
148
+ }
149
+
150
+ // Process complex data in Go
151
+ func processData(this js.Value, args []js.Value) interface{} {
152
+ if len(args) == 0 {
153
+ return js.ValueOf("Error: Expected at least one argument")
154
+ }
155
+
156
+ // Get input data
157
+ data := args[0]
158
+ if data.Type() != js.TypeObject {
159
+ return js.ValueOf("Error: Expected JSON object")
160
+ }
161
+
162
+ // Convert JS object to Go map
163
+ jsonStr := js.Global().Get("JSON").Call("stringify", data).String()
164
+ var inputMap map[string]interface{}
165
+ if err := json.Unmarshal([]byte(jsonStr), &inputMap); err != nil {
166
+ return js.ValueOf(fmt.Sprintf("Error parsing JSON: %s", err.Error()))
167
+ }
168
+
169
+ // Add new fields
170
+ inputMap["processed"] = true
171
+ inputMap["processor"] = "Go WASM"
172
+
173
+ // Add some computed fields
174
+ if values, ok := inputMap["values"].([]interface{}); ok {
175
+ sum := 0.0
176
+ for _, v := range values {
177
+ if num, ok := v.(float64); ok {
178
+ sum += num
179
+ }
180
+ }
181
+ inputMap["sum"] = sum
182
+ }
183
+
184
+ // Convert back to JS
185
+ resultJSON, err := json.Marshal(inputMap)
186
+ if err != nil {
187
+ return js.ValueOf(fmt.Sprintf("Error generating JSON: %s", err.Error()))
188
+ }
189
+
190
+ return js.ValueOf(string(resultJSON))
191
+ }
192
+
193
+ func main() {
194
+ fmt.Println("Go WASM Module initialized")
195
+
196
+ // Register functions to be callable from JavaScript
197
+ js.Global().Set("goAdd", js.FuncOf(add))
198
+ js.Global().Set("goProcessData", js.FuncOf(processData))
199
+
200
+ // Keep the program running
201
+ <-make(chan bool)
202
+ }
203
+ `;
204
+
205
+ fs.writeFileSync(exampleGoFile, exampleGoContent);
206
+ console.log(`Created example Go file at ${exampleGoFile}`);
207
+
208
+ // Build the example file
209
+ console.log('Building example Go file...');
210
+ buildWasmModules();
211
+ }
212
+ }
213
+
214
+ // Run the build process
215
+ buildWasmModules().catch(error => {
216
+ console.error('Build failed:', error);
217
+ process.exit(1);
218
+ });