-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot.zig
More file actions
86 lines (74 loc) · 2.4 KB
/
root.zig
File metadata and controls
86 lines (74 loc) · 2.4 KB
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
const std = @import("std");
const c = @import("c.zig").c;
const Convert = @import("Convert.zig");
const NodeValues = @import("node_values.zig");
pub const NodeContext = @import("Node.zig").NodeContext;
pub const NodeValue = NodeValues.NodeValue;
pub const NodeObject = NodeValues.NodeObject;
pub const NodeArray = NodeValues.NodeArray;
pub const NodeFunction = NodeValues.NodeFunction;
/// Exports the specified comptime value as a native Node-API module.
///
/// Example:
///
/// ```
/// const std = @import("std");
/// const node_api = @import("node-api");
///
/// comptime {
/// node_api.@"export"(.{
/// .fn = function,
/// .Class = Class,
/// });
/// }
/// ```
pub fn @"export"(comptime value: anytype) void {
const module = opaque {
pub fn napi_register_module_v1(env: c.napi_env, _: c.napi_value) callconv(.c) c.napi_value {
const node = NodeContext.init(env);
const exports = node.serialize(value) catch |err| {
node.handleError(err);
return null;
};
return exports.napi_value;
}
};
registerModule(&module.napi_register_module_v1);
}
/// Initializes a native Node-API module by returning a runtime-known value.
///
/// Example:
///
/// ```
/// const std = @import("std");
/// const node_api = @import("node-api");
///
/// comptime {
/// node_api.register(init);
/// }
///
/// fn init(node: node_api.Node.NodeContext) !node_api.Node.NodeValue {
/// std.log.info("TEST MODULE INIT (from Zig)", .{});
/// return try node.createString("hello!");
/// }
/// ```
pub fn init(comptime f: InitFunction) void {
const module = opaque {
pub fn napi_register_module_v1(env: c.napi_env, _: c.napi_value) callconv(.c) c.napi_value {
const node = NodeContext.init(env);
const exports = f(node) catch |err| {
node.handleError(err);
return null;
};
return exports.napi_value;
}
};
registerModule(&module.napi_register_module_v1);
}
/// The InitFunction to pass to the `register` method. The `ctx` parameter
/// represents the Node context. The returned value becomes the `exports` value
/// of the JS module.
pub const InitFunction = fn (ctx: NodeContext) anyerror!NodeValue;
inline fn registerModule(comptime ptr: *const anyopaque) void {
@export(ptr, .{ .name = "napi_register_module_v1" });
}