mhs-lang 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +90 -2
  2. package/assets/logo.png +0 -0
  3. package/bin/mhs.js +171 -0
  4. package/examples/__pycache__/alat_py.cpython-312.pyc +0 -0
  5. package/examples/alat_py.py +7 -0
  6. package/examples/demo_lengkap.mhs +19 -0
  7. package/examples/halo.mhs +20 -0
  8. package/examples/python_native.mhs +16 -0
  9. package/examples/rumus_elektronika.mhs +10 -0
  10. package/examples/tes_semua_modul.mhs +48 -0
  11. package/examples/utama_impor.mhs +11 -0
  12. package/package.json +33 -4
  13. package/src/index.js +186 -0
  14. package/src/modules/berkas.js +19 -0
  15. package/src/modules/data_json.js +9 -0
  16. package/src/modules/index.js +29 -0
  17. package/src/modules/jaringan.js +28 -0
  18. package/src/modules/koleksi.js +43 -0
  19. package/src/modules/kripto.js +9 -0
  20. package/src/modules/matematika.js +55 -0
  21. package/src/modules/modul_acak.js +36 -0
  22. package/src/modules/pola.js +13 -0
  23. package/src/modules/sistem.js +13 -0
  24. package/src/modules/uji.js +52 -0
  25. package/src/modules/waktu.js +49 -0
  26. package/src/py_bridge.js +111 -0
  27. package/src/py_modules/__pycache__/berkas.cpython-312.pyc +0 -0
  28. package/src/py_modules/__pycache__/data_json.cpython-312.pyc +0 -0
  29. package/src/py_modules/__pycache__/jaringan.cpython-312.pyc +0 -0
  30. package/src/py_modules/__pycache__/koleksi.cpython-312.pyc +0 -0
  31. package/src/py_modules/__pycache__/kripto.cpython-312.pyc +0 -0
  32. package/src/py_modules/__pycache__/matematika.cpython-312.pyc +0 -0
  33. package/src/py_modules/__pycache__/modul_acak.cpython-312.pyc +0 -0
  34. package/src/py_modules/__pycache__/pola.cpython-312.pyc +0 -0
  35. package/src/py_modules/__pycache__/sistem.cpython-312.pyc +0 -0
  36. package/src/py_modules/__pycache__/uji.cpython-312.pyc +0 -0
  37. package/src/py_modules/__pycache__/waktu.cpython-312.pyc +0 -0
  38. package/src/py_modules/berkas.py +26 -0
  39. package/src/py_modules/data_json.py +14 -0
  40. package/src/py_modules/jaringan.py +15 -0
  41. package/src/py_modules/koleksi.py +24 -0
  42. package/src/py_modules/kripto.py +18 -0
  43. package/src/py_modules/matematika.py +30 -0
  44. package/src/py_modules/modul_acak.py +14 -0
  45. package/src/py_modules/pola.py +17 -0
  46. package/src/py_modules/sistem.py +11 -0
  47. package/src/py_modules/uji.py +39 -0
  48. package/src/py_modules/waktu.py +19 -0
  49. package/src/py_transpiler.js +231 -0
  50. package/src/stdlib.js +164 -0
  51. package/src/transpiler.js +401 -0
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="./assets/logo.png" alt="Logo mhs-lang" width="180" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # mhs-lang v2.0 (`.mhs`)
6
+
7
+ Bahasa pemrograman **Python dalam Bahasa Indonesia** yang bisa diunduh lewat `npm` dan dijalankan di IDE apa pun. Hadir dengan **Dual-Engine**:
8
+ 1. **Engine Node.js + Python Bridge** (`mhs file.mhs`): langsung jalan tanpa Python, tapi otomatis bisa memanggil modul `.py` / `pip` lewat `impor_py` atau `impor "./alat.py"`.
9
+ 2. **Engine Python 3 Native** (`mhs --py file.mhs`): mengubah `.mhs` ke Python 3 murni 1-on-1 sehingga mendukung **100% fitur & library Python asli** (`numpy`, `cv2`, `slicing`, `class`, `decorator`, `with`, dll.).
10
+
11
+ 📦 **[Unduh mhs-lang dari npm](https://www.npmjs.com/package/mhs-lang)**
12
+
13
+ ## 1. Cara Install & Menjalankan
14
+
15
+ Cara paling cepat tanpa instalasi permanen:
16
+
17
+ ```bash
18
+ npx --yes mhs-lang halo.mhs
19
+ ```
20
+
21
+ Atau pasang sekali agar perintah `mhs` bisa digunakan di mana saja:
22
+
23
+ ```bash
24
+ npm install -g mhs-lang
25
+ ```
26
+
27
+ Setelah itu, mulai proyek contoh dan jalankan:
28
+
29
+ ```bash
30
+ mhs init
31
+ mhs halo.mhs
32
+ ```
33
+
34
+ Untuk memakai Python 3 Native engine, jalankan `mhs --py halo.mhs`.
35
+
36
+ ### Logo dan ikon file `.mhs` di VS Code
37
+
38
+ Logo proyek menggunakan gambar di `assets/logo.png`. Tema ikon MHS mempertahankan ikon Material, termasuk ikon `.py`, dan memakai PNG itu untuk file `.mhs`. Untuk memasang tema dari repositori sumber:
39
+
40
+ ```powershell
41
+ cd vscode-mhs-icons
42
+ npx --yes @vscode/vsce package
43
+ code --install-extension .\mhs-file-icons-1.2.0.vsix
44
+ ```
45
+
46
+ Setelah ekstensi terpasang, file `.mhs` memakai grammar MHS (jadi kata seperti `fungsi` tidak diperiksa sebagai sintaks Python), dan toolbar editor menampilkan tombol ▶. Tombol menyimpan file lalu menjalankannya dengan `mhs --py`. Tema ikon mempertahankan ikon Material, termasuk ikon `.py`, dan memakai PNG proyek untuk `.mhs`.
47
+
48
+ ### Cara Publish ke npm:
49
+ ```bash
50
+ npm login
51
+ npm publish --access public
52
+ ```
53
+
54
+ ---
55
+
56
+ ## 2. Daftar 11 Modul Standar Bahasa Indonesia
57
+
58
+ Semua modul berikut dapat langsung diimpor baik di mode Node.js (`mhs`) maupun mode Python 3 Native (`mhs --py`):
59
+
60
+ | Modul `.mhs` | Padanan Python | Fungsi Utama |
61
+ | :--- | :--- | :--- |
62
+ | `matematika` | `math` | `pi`, `e`, `akar`, `pangkat`, `sin`, `cos`, `tan`, `log`, `faktorial`, `fpb`, `kpk`, `derajat`, `radian` |
63
+ | `modul_acak` | `random` | `bulat`, `desimal`, `pilih`, `sampel`, `kocok` |
64
+ | `waktu` | `time` / `datetime` | `sekarang`, `tidur`, `tanggal_sekarang`, `jam_sekarang`, `info_waktu` |
65
+ | `berkas` | `os` / `pathlib` | `baca`, `tulis`, `tambah_isi`, `ada`, `hapus`, `daftar_isi`, `buat_folder`, `gabung_jalur` |
66
+ | `sistem` | `sys` / `platform` | `argumen`, `platform`, `arsitektur`, `lingkungan`, `keluar` |
67
+ | `data_json` | `json` | `urai`, `ubah_ke_teks`, `baca_berkas`, `tulis_berkas` |
68
+ | `pola` | `re` | `cocok`, `cari`, `cari_semua`, `ganti`, `pisah` |
69
+ | `koleksi` | `collections` / `statistics` | `hitung`, `unik`, `rata_rata`, `median`, `pasangkan`, `kelompokkan` |
70
+ | `kripto` | `hashlib` / `base64` | `sha256`, `md5`, `acak_hex`, `encode_base64`, `decode_base64` |
71
+ | `jaringan` | `urllib` | `urai_url`, `ambil` |
72
+ | `uji` | `unittest` | `sama`, `benar`, `salah`, `lempar_galat`, `ringkasan` |
73
+
74
+ ---
75
+
76
+ ## 3. Kamus Sintaks `.mhs` vs Python
77
+
78
+ | Python Asli | Sintaks `.mhs` |
79
+ | :--- | :--- |
80
+ | `print(...)` / `input(...)` | `cetak(...)` / `masukan(...)` |
81
+ | `if` / `elif` / `else` | `jika` / `atau_jika` / `selain_itu` |
82
+ | `for x in col:` / `while cond:` | `untuk x dalam col:` / `selama cond:` |
83
+ | `def fn(a):` / `return` | `fungsi fn(a):` / `kembalikan` |
84
+ | `class Foo:` / `self` | `kelas Foo:` / `diri` |
85
+ | `try:` / `except Exception as e:` / `finally:` | `coba:` / `tangkap e:` / `akhirnya:` |
86
+ | `raise Exception(...)` / `assert` | `lempar ...` / `pastikan` |
87
+ | `import mod as alias` / `from mod import x` | `impor mod sebagai alias` / `dari mod impor x` |
88
+ | `True` / `False` / `None` | `Benar` / `Salah` / `Kosong` |
89
+ | `and` / `or` / `not` / `in` | `dan` / `atau` / `bukan` / `dalam` |
90
+ | `break` / `continue` / `pass` | `berhenti` / `lanjut` / `lewat` |
91
+ | `[x*2 for x in range(5)]` | `[x*2 untuk x dalam rentang(5)]` |
Binary file
package/bin/mhs.js ADDED
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const readline = require('readline');
6
+ const { transpile, transpileToPython, runCode, runFile } = require('../src/index');
7
+ const pkg = require('../package.json');
8
+
9
+ function printHelp() {
10
+ console.log(`
11
+ mhs-lang v${pkg.version} — Bahasa pemrograman Python dalam Bahasa Indonesia (.mhs)
12
+
13
+ Penggunaan:
14
+ mhs <file.mhs> Menjalankan .mhs (Otomatis Native Python 3 jika tersedia, fallback ke Node.js)
15
+ mhs --py <file.mhs> Memaksa eksekusi dengan Engine Python 3 Native
16
+ mhs --node <file.mhs> Memaksa eksekusi dengan Engine Node.js
17
+ mhs run <file.mhs> Menjalankan .mhs
18
+ mhs --emit-py <file.mhs> Menampilkan hasil konversi ke Python 3 (.py)
19
+ mhs --js <file.mhs> Menampilkan hasil konversi ke JavaScript
20
+ mhs init Membuat contoh halo.mhs & konfigurasi VS Code
21
+ mhs Membuka mode interaktif (REPL)
22
+ mhs --version, -v Menampilkan versi
23
+ mhs --help, -h Menampilkan bantuan ini
24
+ `);
25
+ }
26
+
27
+ function initProject() {
28
+ const samplePath = path.join(process.cwd(), 'halo.mhs');
29
+ if (!fs.existsSync(samplePath)) {
30
+ fs.writeFileSync(
31
+ samplePath,
32
+ `# Program pertama menggunakan bahasa .mhs
33
+ nama = "Mahes"
34
+ cetak(f"Halo, {nama}! Selamat datang di bahasa pemrograman .mhs")
35
+
36
+ fungsi hitung_luas_persegi(sisi):
37
+ kembalikan sisi * sisi
38
+
39
+ untuk i dalam rentang(1, 5):
40
+ cetak(f"Luas persegi sisi {i} = {hitung_luas_persegi(i)}")
41
+ `,
42
+ 'utf8'
43
+ );
44
+ console.log('Berhasil membuat halo.mhs');
45
+ }
46
+
47
+ const vscodeDir = path.join(process.cwd(), '.vscode');
48
+ const tasksPath = path.join(vscodeDir, 'tasks.json');
49
+ if (!fs.existsSync(tasksPath)) {
50
+ fs.mkdirSync(vscodeDir, { recursive: true });
51
+ fs.writeFileSync(
52
+ tasksPath,
53
+ JSON.stringify(
54
+ {
55
+ version: '2.0.0',
56
+ tasks: [
57
+ {
58
+ label: 'Jalankan File .mhs',
59
+ type: 'shell',
60
+ command: 'npx mhs-lang "${file}"',
61
+ group: {
62
+ kind: 'build',
63
+ isDefault: true,
64
+ },
65
+ presentation: {
66
+ reveal: 'always',
67
+ panel: 'shared',
68
+ },
69
+ },
70
+ ],
71
+ },
72
+ null,
73
+ 2
74
+ ),
75
+ 'utf8'
76
+ );
77
+ console.log('Berhasil membuat .vscode/tasks.json (tekan Ctrl+Shift+B di VS Code untuk menjalankan file .mhs)');
78
+ }
79
+ }
80
+
81
+ function startRepl() {
82
+ console.log(`mhs-lang v${pkg.version} (Mode Interaktif). Ketik "keluar" untuk berhenti.`);
83
+ const rl = readline.createInterface({
84
+ input: process.stdin,
85
+ output: process.stdout,
86
+ prompt: 'mhs> ',
87
+ });
88
+ rl.prompt();
89
+ rl.on('line', (line) => {
90
+ const trimmed = line.trim();
91
+ if (trimmed === 'keluar' || trimmed === 'exit') {
92
+ rl.close();
93
+ return;
94
+ }
95
+ if (trimmed) {
96
+ try {
97
+ runCode(trimmed, '<repl>');
98
+ } catch (err) {
99
+ console.error('Kesalahan:', err.message);
100
+ }
101
+ }
102
+ rl.prompt();
103
+ });
104
+ }
105
+
106
+ function main() {
107
+ const args = process.argv.slice(2);
108
+
109
+ if (args.length === 0) {
110
+ startRepl();
111
+ return;
112
+ }
113
+
114
+ const cmd = args[0];
115
+
116
+ if (cmd === '--help' || cmd === '-h') {
117
+ printHelp();
118
+ return;
119
+ }
120
+
121
+ if (cmd === '--version' || cmd === '-v') {
122
+ console.log(pkg.version);
123
+ return;
124
+ }
125
+
126
+ if (cmd === 'init') {
127
+ initProject();
128
+ return;
129
+ }
130
+
131
+ if (cmd === '--js' || cmd === '--emit-py') {
132
+ const target = args[1];
133
+ if (!target) {
134
+ console.error(`Kesalahan: Harap sertakan nama file .mhs. Contoh: mhs ${cmd} halo.mhs`);
135
+ process.exit(1);
136
+ }
137
+ const source = fs.readFileSync(path.resolve(target), 'utf8');
138
+ console.log(cmd === '--emit-py' ? transpileToPython(source) : transpile(source));
139
+ return;
140
+ }
141
+
142
+ if (cmd === '--py' || cmd === '--node') {
143
+ const target = args[1];
144
+ if (!target) {
145
+ console.error(`Kesalahan: Harap sertakan nama file .mhs. Contoh: mhs ${cmd} halo.mhs`);
146
+ process.exit(1);
147
+ }
148
+ try {
149
+ runFile(target, { engine: cmd === '--py' ? 'py' : 'node' });
150
+ } catch (err) {
151
+ console.error(`[MHS Error] ${err.message}`);
152
+ process.exit(1);
153
+ }
154
+ return;
155
+ }
156
+
157
+ const fileTarget = cmd === 'run' ? args[1] : cmd;
158
+ if (!fileTarget) {
159
+ printHelp();
160
+ process.exit(1);
161
+ }
162
+
163
+ try {
164
+ runFile(fileTarget, { engine: 'auto' });
165
+ } catch (err) {
166
+ console.error(`[MHS Error] ${err.message}`);
167
+ process.exit(1);
168
+ }
169
+ }
170
+
171
+ main();
@@ -0,0 +1,7 @@
1
+ # Modul Python asli (.py) yang bisa diimpor oleh .mhs
2
+ def sapa_python(nama):
3
+ return f"Halo {nama}, ini pesan langsung dari Python!"
4
+
5
+ def hitung_frekuensi_rc(r_ohm, c_farad):
6
+ import math
7
+ return round(1 / (2 * math.pi * r_ohm * c_farad), 2)
@@ -0,0 +1,19 @@
1
+ # Demo Lengkap mhs-lang v2.0 (Bisa dijalankan di mode Node.js maupun `mhs --py`)
2
+ impor_py "math" sebagai m_py
3
+ dari "./rumus_elektronika.mhs" impor hitung_arus
4
+ impor "./alat_py.py" sebagai alat
5
+
6
+ # 1. List comprehension ala Python
7
+ kuadrat = [x * x untuk x dalam rentang(1, 6)]
8
+ cetak("Kuadrat 1..5:", kuadrat)
9
+
10
+ # 2. Memanggil fungsi Python asli dari .mhs
11
+ cetak(alat.sapa_python("Mahes"))
12
+ cetak("Akar 144 via Python math:", m_py.sqrt(144))
13
+
14
+ # 3. Memanggil modul .mhs lain
15
+ cetak("Arus 12V / 4 Ohm:", hitung_arus(12, 4), "A")
16
+
17
+ # 4. Penanganan error & pastikan
18
+ pastikan panjang(kuadrat) == 5, "Panjang harus 5"
19
+ cetak("Semua fitur berjalan lancar!")
@@ -0,0 +1,20 @@
1
+ # Contoh Program .mhs (Python Bahasa Indonesia)
2
+ nama = "Maheswara"
3
+ jurusan = "Teknik Mekatronika"
4
+
5
+ cetak(f"Halo! Saya {nama} dari jurusan {jurusan}.")
6
+
7
+ fungsi hitung_hambatan_seri(daftar_resistor):
8
+ total = 0
9
+ untuk r dalam daftar_resistor:
10
+ total = total + r
11
+ kembalikan total
12
+
13
+ resistor = [220, 470, 1000]
14
+ total_r = hitung_hambatan_seri(resistor)
15
+ cetak(f"Total hambatan seri: {total_r} Ohm")
16
+
17
+ jika total_r > 1000:
18
+ cetak("Status: Hambatan di atas 1 kOhm")
19
+ selain_itu:
20
+ cetak("Status: Hambatan di bawah atau sama dengan 1 kOhm")
@@ -0,0 +1,16 @@
1
+ # Contoh penggunaan library Python secara NATIVE langsung di .mhs
2
+ impor math sebagai m
3
+ impor json
4
+ impor statistics sebagai stat
5
+ dari datetime impor datetime
6
+ dari pathlib impor Path
7
+ impor "./alat_py.py" sebagai alat
8
+
9
+ # Library Python standar berjalan langsung secara native
10
+ data = [10, 20, 30, 40, 50]
11
+ cetak("Rata-rata (statistics.mean):", stat.mean(data))
12
+ cetak("Akar 256 (math.sqrt):", m.sqrt(256))
13
+ cetak("JSON:", json.dumps({"bahasa": "mhs", "native_python": Benar}))
14
+ cetak("Tahun sekarang (datetime):", datetime.now().year)
15
+ cetak("Ekstensi file (pathlib.Path):", Path("proyek/utama.mhs").suffix)
16
+ cetak(alat.sapa_python("Mahes"))
@@ -0,0 +1,10 @@
1
+ # Modul rumus elektronika dalam bahasa .mhs
2
+ tegang_baterai = 12
3
+
4
+ fungsi hitung_arus(tegangan, hambatan):
5
+ jika hambatan == 0:
6
+ lempar "Hambatan tidak boleh nol"
7
+ kembalikan tegangan / hambatan
8
+
9
+ fungsi hitung_daya(tegangan, arus):
10
+ kembalikan tegangan * arus
@@ -0,0 +1,48 @@
1
+ # Uji Kelengkapan Semua Modul Bahasa Indonesia di mhs-lang
2
+ impor matematika
3
+ impor modul_acak
4
+ impor waktu
5
+ impor berkas
6
+ impor sistem
7
+ impor data_json
8
+ impor pola
9
+ impor koleksi
10
+ impor kripto
11
+ impor jaringan
12
+ impor uji
13
+
14
+ # 1. Matematika
15
+ uji.sama(matematika.fpb(12, 18), 6)
16
+ uji.sama(matematika.faktorial(5), 120)
17
+
18
+ # 2. Modul Acak
19
+ angka_acak = modul_acak.bulat(1, 10)
20
+ uji.benar(angka_acak >= 1 dan angka_acak <= 10)
21
+
22
+ # 3. Waktu & Sistem
23
+ uji.benar(panjang(waktu.tanggal_sekarang()) == 10)
24
+ uji.benar(panjang(sistem.platform()) > 0)
25
+
26
+ # 4. Data JSON & Pola (Regex)
27
+ teks_json = data_json.ubah_ke_teks({"bahasa": "mhs", "versi": 2})
28
+ obj = data_json.urai(teks_json)
29
+ uji.sama(obj["bahasa"], "mhs")
30
+ uji.sama(pola.cari_semua("[0-9]+", "v2 tahun 2026"), ["2", "2026"])
31
+
32
+ # 5. Koleksi
33
+ uji.sama(koleksi.rata_rata([10, 20, 30]), 20)
34
+ uji.sama(koleksi.unik([1, 2, 2, 3]), [1, 2, 3])
35
+
36
+ # 6. Kripto & Jaringan (URL parser)
37
+ b64 = kripto.encode_base64("mhs")
38
+ uji.sama(kripto.decode_base64(b64), "mhs")
39
+ url_info = jaringan.urai_url("https://contoh.id/belajar?lang=mhs")
40
+ uji.sama(url_info["host"], "contoh.id")
41
+
42
+ # 7. Berkas (tulis, baca, hapus)
43
+ jalur_tmp = berkas.gabung_jalur(berkas.folder_kerja(), "_uji_mhs_tmp.txt")
44
+ berkas.tulis(jalur_tmp, "Halo .mhs!")
45
+ uji.sama(berkas.baca(jalur_tmp), "Halo .mhs!")
46
+ berkas.hapus(jalur_tmp)
47
+
48
+ cetak("Ringkasan uji semua modul:", uji.ringkasan())
@@ -0,0 +1,11 @@
1
+ # Contoh Program Utama yang mengimpor modul .mhs lain dan modul sistem
2
+ dari "./rumus_elektronika.mhs" impor hitung_arus, hitung_daya, tegang_baterai
3
+ impor sistem
4
+
5
+ r = 24
6
+ arus = hitung_arus(tegang_baterai, r)
7
+ daya = hitung_daya(tegang_baterai, arus)
8
+
9
+ cetak(f"Berjalan di sistem: {sistem.platform()}")
10
+ cetak(f"Tegangan: {tegang_baterai}V, Hambatan: {r} Ohm")
11
+ cetak(f"Arus: {arus} A, Daya: {daya} Watt")
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "mhs-lang",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "Bahasa pemrograman Python dalam Bahasa Indonesia (.mhs) dengan dual-engine Node.js + Python 3 native, dukungan impor .mhs, npm, dan modul Python (.py/pip).",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "mhs": "bin/mhs.js",
8
+ "mhs-lang": "bin/mhs.js"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "assets/",
14
+ "examples/",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "test": "node test/run_tests.js"
19
+ },
20
+ "keywords": [
21
+ "bahasa-pemrograman",
22
+ "indonesia",
23
+ "python-indonesia",
24
+ "mhs",
25
+ "transpiler",
26
+ "cli",
27
+ "python",
28
+ "nodejs"
29
+ ],
30
+ "author": "Maheswara",
31
+ "license": "MIT",
32
+ "engines": {
33
+ "node": ">=16.0.0"
34
+ }
35
+ }
package/src/index.js ADDED
@@ -0,0 +1,186 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const vm = require('vm');
5
+ const Module = require('module');
6
+ const { execFileSync } = require('child_process');
7
+ const { transpile } = require('./transpiler');
8
+ const { transpileToPython } = require('./py_transpiler');
9
+ const { importPythonModule } = require('./py_bridge');
10
+ const { stdlib } = require('./stdlib');
11
+ const { STD_MODULES } = require('./modules/index');
12
+
13
+ let _hasPythonCache = null;
14
+ function getPythonCommand() {
15
+ return process.platform === 'win32' ? 'python' : 'python3';
16
+ }
17
+
18
+ function hasPython3() {
19
+ if (_hasPythonCache !== null) return _hasPythonCache;
20
+ try {
21
+ execFileSync(getPythonCommand(), ['--version'], { stdio: 'ignore' });
22
+ _hasPythonCache = true;
23
+ } catch {
24
+ _hasPythonCache = false;
25
+ }
26
+ return _hasPythonCache;
27
+ }
28
+
29
+ function resolveMhsModule(target, baseDir) {
30
+ const candidates = [];
31
+ if (target.endsWith('.mhs')) {
32
+ candidates.push(path.resolve(baseDir, target));
33
+ } else {
34
+ candidates.push(path.resolve(baseDir, `${target}.mhs`));
35
+ candidates.push(path.resolve(baseDir, target, 'index.mhs'));
36
+ }
37
+ for (const cand of candidates) {
38
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) {
39
+ return cand;
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ function resolvePyFile(target, baseDir) {
46
+ if (target.endsWith('.py')) {
47
+ const cand = path.resolve(baseDir, target);
48
+ if (fs.existsSync(cand) && fs.statSync(cand).isFile()) return cand;
49
+ }
50
+ const candPy = path.resolve(baseDir, `${target}.py`);
51
+ if (fs.existsSync(candPy) && fs.statSync(candPy).isFile()) return candPy;
52
+ return null;
53
+ }
54
+
55
+ function createImporter(baseDir, moduleCache) {
56
+ const localRequire = Module.createRequire(path.join(baseDir, 'index.js'));
57
+
58
+ return function __mhs_impor(target) {
59
+ const mhsPath = resolveMhsModule(target, baseDir);
60
+ if (mhsPath) {
61
+ if (moduleCache.has(mhsPath)) {
62
+ return moduleCache.get(mhsPath);
63
+ }
64
+ const exportsPlaceholder = {};
65
+ moduleCache.set(mhsPath, exportsPlaceholder);
66
+ const source = fs.readFileSync(mhsPath, 'utf8');
67
+ const { exports } = executeMhs(source, mhsPath, moduleCache);
68
+ Object.assign(exportsPlaceholder, exports);
69
+ return exportsPlaceholder;
70
+ }
71
+
72
+ if (Object.prototype.hasOwnProperty.call(STD_MODULES, target)) {
73
+ return STD_MODULES[target];
74
+ }
75
+
76
+ const pyPath = resolvePyFile(target, baseDir);
77
+ if (pyPath) {
78
+ return importPythonModule(pyPath, baseDir);
79
+ }
80
+
81
+ try {
82
+ return localRequire(target);
83
+ } catch (err) {
84
+ try {
85
+ return importPythonModule(target, baseDir);
86
+ } catch (pyErr) {
87
+ throw new Error(`Modul "${target}" tidak ditemukan sebagai modul standar .mhs, file lokal, paket npm/Node.js, maupun modul Python.`);
88
+ }
89
+ }
90
+ };
91
+ }
92
+
93
+ function executeMhs(source, filename = '<mhs>', moduleCache = new Map()) {
94
+ const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
95
+ const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
96
+
97
+ const jsCode = transpile(source);
98
+ const context = {
99
+ ...stdlib,
100
+ __mhs_impor: createImporter(baseDir, moduleCache),
101
+ __mhs_impor_py: (modName) => importPythonModule(modName, baseDir),
102
+ __mhs_exports__: {},
103
+ console,
104
+ Math,
105
+ JSON,
106
+ Date,
107
+ Array,
108
+ Object,
109
+ String,
110
+ Number,
111
+ Boolean,
112
+ Error,
113
+ __filename: absFilename,
114
+ __dirname: baseDir,
115
+ };
116
+ vm.createContext(context);
117
+ const result = vm.runInContext(jsCode, context, { filename: absFilename });
118
+ return { result, exports: context.__mhs_exports__ };
119
+ }
120
+
121
+ function runCode(source, filename = '<mhs>') {
122
+ return executeMhs(source, filename).result;
123
+ }
124
+
125
+ function runFile(filePath, { engine = 'auto' } = {}) {
126
+ const absPath = path.resolve(filePath);
127
+ if (!fs.existsSync(absPath)) {
128
+ throw new Error(`File tidak ditemukan: ${absPath}`);
129
+ }
130
+ const source = fs.readFileSync(absPath, 'utf8');
131
+
132
+ if (engine === 'py' || (engine === 'auto' && hasPython3())) {
133
+ return runPyCode(source, absPath);
134
+ }
135
+ return runCode(source, absPath);
136
+ }
137
+
138
+ function runPyCode(source, filename = '<mhs>') {
139
+ const absFilename = filename.startsWith('<') ? filename : path.resolve(filename);
140
+ const baseDir = filename.startsWith('<') ? process.cwd() : path.dirname(absFilename);
141
+ const pyModulesDir = path.resolve(__dirname, 'py_modules');
142
+
143
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mhs-py-'));
144
+ try {
145
+ if (fs.existsSync(baseDir)) {
146
+ for (const entry of fs.readdirSync(baseDir)) {
147
+ if (entry.endsWith('.mhs')) {
148
+ const mhsSrc = fs.readFileSync(path.join(baseDir, entry), 'utf8');
149
+ const pyOut = transpileToPython(mhsSrc);
150
+ const pyName = entry.replace(/\.mhs$/i, '.py');
151
+ fs.writeFileSync(path.join(tmpDir, pyName), pyOut, 'utf8');
152
+ }
153
+ }
154
+ }
155
+
156
+ const pyCode = transpileToPython(source);
157
+ const pythonCmd = getPythonCommand();
158
+ const env = {
159
+ ...process.env,
160
+ PYTHONPATH: [tmpDir, pyModulesDir, baseDir, process.env.PYTHONPATH || ''].filter(Boolean).join(path.delimiter),
161
+ };
162
+ return execFileSync(pythonCmd, ['-c', pyCode], {
163
+ cwd: baseDir,
164
+ env,
165
+ stdio: 'inherit',
166
+ });
167
+ } finally {
168
+ fs.rmSync(tmpDir, { recursive: true, force: true });
169
+ }
170
+ }
171
+
172
+ function runPyFile(filePath) {
173
+ return runFile(filePath, { engine: 'py' });
174
+ }
175
+
176
+ module.exports = {
177
+ transpile,
178
+ transpileToPython,
179
+ runCode,
180
+ runFile,
181
+ runPyCode,
182
+ runPyFile,
183
+ hasPython3,
184
+ stdlib,
185
+ STD_MODULES,
186
+ };
@@ -0,0 +1,19 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ module.exports = {
5
+ baca: (jalur, encoding = 'utf8') => fs.readFileSync(jalur, encoding),
6
+ tulis: (jalur, isi, encoding = 'utf8') => fs.writeFileSync(jalur, String(isi), encoding),
7
+ tambah_isi: (jalur, isi, encoding = 'utf8') => fs.appendFileSync(jalur, String(isi), encoding),
8
+ ada: (jalur) => fs.existsSync(jalur),
9
+ hapus: (jalur) => fs.unlinkSync(jalur),
10
+ daftar_isi: (folder = '.') => fs.readdirSync(folder),
11
+ buat_folder: (jalur) => fs.mkdirSync(jalur, { recursive: true }),
12
+ hapus_folder: (jalur) => fs.rmSync(jalur, { recursive: true, force: true }),
13
+ gabung_jalur: (...bagian) => path.join(...bagian),
14
+ nama_berkas: (jalur) => path.basename(jalur),
15
+ folder_induk: (jalur) => path.dirname(jalur),
16
+ ekstensi: (jalur) => path.extname(jalur),
17
+ ukuran: (jalur) => fs.statSync(jalur).size,
18
+ folder_kerja: () => process.cwd(),
19
+ };
@@ -0,0 +1,9 @@
1
+ const fs = require('fs');
2
+
3
+ module.exports = {
4
+ urai: (teks) => JSON.parse(teks),
5
+ ubah_ke_teks: (objek, rapi = false) => JSON.stringify(objek, null, rapi ? 2 : 0),
6
+ baca_berkas: (jalur) => JSON.parse(fs.readFileSync(jalur, 'utf8')),
7
+ tulis_berkas: (jalur, objek, rapi = true) =>
8
+ fs.writeFileSync(jalur, JSON.stringify(objek, null, rapi ? 2 : 0), 'utf8'),
9
+ };