amberjs 1.17.0

JavaScript/TypeScript runtime built with Rust and V8
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Official modern standard library for Amber (`amber:std`, `amber:std/*`).

pub mod assert;
pub mod cli;
pub mod crypto;
pub mod dotenv;
pub mod fs;

use anyhow::Result;
use rusty_v8 as v8;
use std::path::Path;

/// Register standard library APIs in the V8 context
pub fn setup_std_api(
    scope: &mut v8::ContextScope<v8::HandleScope>,
    context: &v8::Local<v8::Context>,
) -> Result<()> {
    let global = context.global(scope);

    // 1. Native callbacks for std_lib
    let dotenv_parse_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let content = if args.length() > 0 {
                args.get(0).to_rust_string_lossy(scope)
            } else {
                String::new()
            };

            let parsed = dotenv::parse_dotenv(&content);
            let json_str = serde_json::to_string(&parsed).unwrap_or_else(|_| "{}".to_string());
            let v8_str = v8::String::new(scope, &json_str).unwrap();
            retval.set(v8_str.into());
        },
    )
    .get_function(scope)
    .unwrap();

    let cli_table_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let headers_json = if args.length() > 0 {
                args.get(0).to_rust_string_lossy(scope)
            } else {
                "[]".to_string()
            };
            let rows_json = if args.length() > 1 {
                args.get(1).to_rust_string_lossy(scope)
            } else {
                "[]".to_string()
            };

            let headers: Vec<String> = serde_json::from_str(&headers_json).unwrap_or_default();
            let rows: Vec<Vec<String>> = serde_json::from_str(&rows_json).unwrap_or_default();

            let table_str = cli::format_table(&headers, &rows);
            let v8_str = v8::String::new(scope, &table_str).unwrap();
            retval.set(v8_str.into());
        },
    )
    .get_function(scope)
    .unwrap();

    let fs_walk_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let dir_str = if args.length() > 0 {
                args.get(0).to_rust_string_lossy(scope)
            } else {
                ".".to_string()
            };
            let max_depth = if args.length() > 1 && !args.get(1).is_undefined() {
                args.get(1).uint32_value(scope).map(|d| d as usize)
            } else {
                None
            };
            let exts_json = if args.length() > 2 && !args.get(2).is_undefined() {
                Some(args.get(2).to_rust_string_lossy(scope))
            } else {
                None
            };

            let exts: Option<Vec<String>> = exts_json.and_then(|j| serde_json::from_str(&j).ok());

            match fs::walk_dir_sync(Path::new(&dir_str), max_depth, exts.as_deref()) {
                Ok(entries) => {
                    let json_entries: Vec<serde_json::Value> = entries
                        .into_iter()
                        .map(|e| {
                            serde_json::json!({
                                "path": e.path,
                                "name": e.name,
                                "isFile": e.is_file,
                                "isDirectory": e.is_dir,
                                "size": e.size
                            })
                        })
                        .collect();
                    let json_str =
                        serde_json::to_string(&json_entries).unwrap_or_else(|_| "[]".to_string());
                    let v8_str = v8::String::new(scope, &json_str).unwrap();
                    retval.set(v8_str.into());
                }
                Err(e) => {
                    let err_msg = v8::String::new(scope, &format!("walkDir error: {}", e)).unwrap();
                    let exception = v8::Exception::error(scope, err_msg);
                    scope.throw_exception(exception);
                }
            }
        },
    )
    .get_function(scope)
    .unwrap();

    let fs_copy_dir_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let src = if args.length() > 0 {
                args.get(0).to_rust_string_lossy(scope)
            } else {
                String::new()
            };
            let dest = if args.length() > 1 {
                args.get(1).to_rust_string_lossy(scope)
            } else {
                String::new()
            };

            match fs::copy_dir_sync(Path::new(&src), Path::new(&dest)) {
                Ok(()) => {
                    retval.set(v8::undefined(scope).into());
                }
                Err(e) => {
                    let err_msg = v8::String::new(scope, &format!("copyDir error: {}", e)).unwrap();
                    let exception = v8::Exception::error(scope, err_msg);
                    scope.throw_exception(exception);
                }
            }
        },
    )
    .get_function(scope)
    .unwrap();

    let fs_empty_dir_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let dir = if args.length() > 0 {
                args.get(0).to_rust_string_lossy(scope)
            } else {
                String::new()
            };

            match fs::empty_dir_sync(Path::new(&dir)) {
                Ok(()) => {
                    retval.set(v8::undefined(scope).into());
                }
                Err(e) => {
                    let err_msg =
                        v8::String::new(scope, &format!("emptyDir error: {}", e)).unwrap();
                    let exception = v8::Exception::error(scope, err_msg);
                    scope.throw_exception(exception);
                }
            }
        },
    )
    .get_function(scope)
    .unwrap();

    let crypto_uuid_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         _args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let uuid_str = crypto::generate_uuid_v4();
            let v8_str = v8::String::new(scope, &uuid_str).unwrap();
            retval.set(v8_str.into());
        },
    )
    .get_function(scope)
    .unwrap();

    let crypto_uuidv7_fn = v8::FunctionTemplate::new(
        scope,
        |scope: &mut v8::PinScope,
         _args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            let uuid_str = crypto::generate_uuid_v7();
            let v8_str = v8::String::new(scope, &uuid_str).unwrap();
            retval.set(v8_str.into());
        },
    )
    .get_function(scope)
    .unwrap();

    // Attach native callbacks to __amber_std_native
    let std_internal = v8::Object::new(scope);
    let k_dotenv = v8::String::new(scope, "dotenvParse").unwrap();
    let k_table = v8::String::new(scope, "cliTable").unwrap();
    let k_walk = v8::String::new(scope, "fsWalk").unwrap();
    let k_copydir = v8::String::new(scope, "fsCopyDir").unwrap();
    let k_emptydir = v8::String::new(scope, "fsEmptyDir").unwrap();
    let k_uuid = v8::String::new(scope, "uuid").unwrap();
    let k_uuidv7 = v8::String::new(scope, "uuidv7").unwrap();

    std_internal.set(scope, k_dotenv.into(), dotenv_parse_fn.into());
    std_internal.set(scope, k_table.into(), cli_table_fn.into());
    std_internal.set(scope, k_walk.into(), fs_walk_fn.into());
    std_internal.set(scope, k_copydir.into(), fs_copy_dir_fn.into());
    std_internal.set(scope, k_emptydir.into(), fs_empty_dir_fn.into());
    std_internal.set(scope, k_uuid.into(), crypto_uuid_fn.into());
    std_internal.set(scope, k_uuidv7.into(), crypto_uuidv7_fn.into());

    let k_std_native = v8::String::new(scope, "__amber_std_native").unwrap();
    global.set(scope, k_std_native.into(), std_internal.into());

    // 2. Load assert JS implementation
    let assert_src = v8::String::new(scope, assert::ASSERT_JS_CODE).unwrap();
    if let Some(script) = v8::Script::compile(scope, assert_src, None) {
        let _ = script.run(scope);
    }

    // 3. Inject rich JavaScript standard modules
    let js_code = r#"
    (function() {
        const native = globalThis.__amber_std_native;
        const assertModule = globalThis.__amber_assert;

        // ==========================================
        // 1. dotenv: Environment Variables
        // ==========================================
        const dotenv = {
            parse(src) {
                if (typeof src !== 'string') return {};
                return JSON.parse(native.dotenvParse(src));
            },
            config(options = {}) {
                const fs = require('fs');
                const path = require('path');
                const envPath = options.path || '.env';
                const resolved = path.resolve(process.cwd(), envPath);
                const override = Boolean(options.override);

                if (!fs.existsSync(resolved)) {
                    return { parsed: {}, error: new Error(`File not found: ${resolved}`) };
                }

                try {
                    const content = fs.readFileSync(resolved, 'utf8');
                    const parsed = this.parse(content);
                    for (const [key, value] of Object.entries(parsed)) {
                        if (override || process.env[key] === undefined) {
                            process.env[key] = value;
                        }
                    }
                    return { parsed };
                } catch (err) {
                    return { parsed: {}, error: err };
                }
            }
        };

        // ==========================================
        // 2. cli: Colors, Tables, Progress & Prompt
        // ==========================================
        const colorCodes = {
            reset: '\x1b[0m',
            bold: '\x1b[1m',
            dim: '\x1b[2m',
            italic: '\x1b[3m',
            underline: '\x1b[4m',
            red: '\x1b[31m',
            green: '\x1b[32m',
            yellow: '\x1b[33m',
            blue: '\x1b[34m',
            magenta: '\x1b[35m',
            cyan: '\x1b[36m',
            white: '\x1b[37m',
            gray: '\x1b[90m',
            bgRed: '\x1b[41m',
            bgGreen: '\x1b[42m',
            bgYellow: '\x1b[43m',
            bgBlue: '\x1b[44m'
        };

        const colors = {};
        for (const [name, code] of Object.entries(colorCodes)) {
            colors[name] = function(str) {
                return `${code}${str}${colorCodes.reset}`;
            };
        }

        const cli = {
            colors,
            table(data, columns = null) {
                if (!Array.isArray(data) || data.length === 0) return '';
                const headers = columns || Object.keys(data[0]);
                const rows = data.map(item => {
                    return headers.map(h => {
                        const val = item[h];
                        return val !== undefined && val !== null ? String(val) : '';
                    });
                });
                return native.cliTable(JSON.stringify(headers), JSON.stringify(rows));
            },
            progressBar(options = {}) {
                const total = options.total || 100;
                const width = options.width || 30;
                let current = 0;

                return {
                    tick(delta = 1) {
                        current = Math.min(total, current + delta);
                        this.render();
                    },
                    render() {
                        const percent = Math.floor((current / total) * 100);
                        const filled = Math.floor((current / total) * width);
                        const empty = width - filled;
                        const bar = '█'.repeat(filled) + '░'.repeat(empty);
                        process.stdout.write(`\r[${bar}] ${percent}% (${current}/${total})`);
                        if (current >= total) {
                            process.stdout.write('\n');
                        }
                    },
                    complete() {
                        current = total;
                        this.render();
                    }
                };
            },
            async prompt(question, defaultValue = '') {
                const readline = require('readline');
                const rl = readline.createInterface({
                    input: process.stdin,
                    output: process.stdout
                });
                return new Promise(resolve => {
                    const q = defaultValue ? `${question} (${defaultValue}): ` : `${question}: `;
                    rl.question(q, answer => {
                        rl.close();
                        resolve(answer.trim() || defaultValue);
                    });
                });
            }
        };

        // ==========================================
        // 3. fs: High-level Directory & File Utils
        // ==========================================
        const stdFs = {
            walkDir(dir = '.', options = {}) {
                const maxDepth = options.maxDepth !== undefined ? options.maxDepth : undefined;
                const exts = options.exts ? JSON.stringify(options.exts) : undefined;
                const raw = native.fsWalk(String(dir), maxDepth, exts);
                return JSON.parse(raw);
            },
            copyDir(src, dest) {
                native.fsCopyDir(String(src), String(dest));
            },
            emptyDir(dir) {
                native.fsEmptyDir(String(dir));
            },
            ensureDir(dir) {
                const fs = require('fs');
                if (!fs.existsSync(dir)) {
                    fs.mkdirSync(dir, { recursive: true });
                }
            },
            ensureFile(file) {
                const fs = require('fs');
                const path = require('path');
                this.ensureDir(path.dirname(file));
                if (!fs.existsSync(file)) {
                    fs.writeFileSync(file, '');
                }
            }
        };

        // ==========================================
        // 4. crypto: JWT, Hashes & UUIDs
        // ==========================================
        function base64UrlEncode(str) {
            const buf = Buffer.from(str);
            return buf.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
        }

        function base64UrlDecode(str) {
            let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
            while (base64.length % 4) {
                base64 += '=';
            }
            return Buffer.from(base64, 'base64').toString('utf8');
        }

        const stdCrypto = {
            uuid() {
                return native.uuid();
            },
            uuidv7() {
                return native.uuidv7();
            },
            hash(algorithm, data, encoding = 'hex') {
                const crypto = require('crypto');
                return crypto.createHash(algorithm).update(data).digest(encoding);
            },
            jwt: {
                sign(payload, secret, options = {}) {
                    const crypto = require('crypto');
                    const header = {
                        alg: 'HS256',
                        typ: 'JWT'
                    };
                    const iat = Math.floor(Date.now() / 1000);
                    const body = { iat, ...payload };
                    if (options.expiresIn) {
                        const secs = typeof options.expiresIn === 'number'
                            ? options.expiresIn
                            : parseInt(options.expiresIn, 10);
                        body.exp = iat + secs;
                    }

                    const encodedHeader = base64UrlEncode(JSON.stringify(header));
                    const encodedPayload = base64UrlEncode(JSON.stringify(body));
                    const dataToSign = `${encodedHeader}.${encodedPayload}`;

                    const signature = crypto.createHmac('sha256', secret)
                        .update(dataToSign)
                        .digest('base64')
                        .replace(/=/g, '')
                        .replace(/\+/g, '-')
                        .replace(/\//g, '_');

                    return `${dataToSign}.${signature}`;
                },
                verify(token, secret) {
                    const crypto = require('crypto');
                    const parts = String(token).split('.');
                    if (parts.length !== 3) {
                        throw new Error('Invalid JWT format');
                    }
                    const [encodedHeader, encodedPayload, signature] = parts;
                    const dataToSign = `${encodedHeader}.${encodedPayload}`;
                    const expectedSig = crypto.createHmac('sha256', secret)
                        .update(dataToSign)
                        .digest('base64')
                        .replace(/=/g, '')
                        .replace(/\+/g, '-')
                        .replace(/\//g, '_');

                    if (signature !== expectedSig) {
                        throw new Error('JWT signature mismatch');
                    }

                    const payload = JSON.parse(base64UrlDecode(encodedPayload));
                    if (payload.exp && Math.floor(Date.now() / 1000) > payload.exp) {
                        throw new Error('JWT token expired');
                    }
                    return payload;
                }
            }
        };

        // ==========================================
        // 5. Global & Modules Binding
        // ==========================================
        const beeStd = {
            dotenv,
            cli,
            fs: stdFs,
            crypto: stdCrypto,
            assert: assertModule.assert,
            assertEquals: assertModule.assertEquals,
            assertNotEquals: assertModule.assertNotEquals,
            assertThrows: assertModule.assertThrows,
            version: '1.4.0'
        };

        globalThis.__amber_std = beeStd;
        globalThis.__amber_std_dotenv = dotenv;
        globalThis.__amber_std_cli = cli;
        globalThis.__amber_std_fs = stdFs;
        globalThis.__amber_std_crypto = stdCrypto;
        globalThis.__amber_std_assert = assertModule;
        globalThis.std = beeStd;
    })();
    "#;

    let script_source = v8::String::new(scope, js_code).unwrap();
    if let Some(script) = v8::Script::compile(scope, script_source, None) {
        let _ = script.run(scope);
    }

    Ok(())
}