forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBridgeJSCommandPlugin.swift
More file actions
216 lines (192 loc) · 7.62 KB
/
BridgeJSCommandPlugin.swift
File metadata and controls
216 lines (192 loc) · 7.62 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
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
#if canImport(PackagePlugin)
import PackagePlugin
@preconcurrency import Foundation
/// Command plugin for ahead-of-time (AOT) code generation with BridgeJS.
/// This plugin allows you to generate bridge code between Swift and JavaScript
/// before the build process, improving build times for larger projects.
/// See documentation: Ahead-of-Time-Code-Generation.md
@main
struct BridgeJSCommandPlugin: CommandPlugin {
static let JAVASCRIPTKIT_PACKAGE_NAME: String = "JavaScriptKit"
struct Options {
var targets: [String]
var verbose: Bool
static func parse(extractor: inout ArgumentExtractor) -> Options {
let targets = extractor.extractOption(named: "target")
let verbose = extractor.extractFlag(named: "verbose")
return Options(targets: targets, verbose: verbose != 0)
}
static func help() -> String {
return """
OVERVIEW: Generate ahead-of-time (AOT) bridge code between Swift and JavaScript.
This command generates bridge code before the build process, which can significantly
improve build times for larger projects by avoiding runtime code generation.
Generated code will be placed in the target's 'Generated' directory.
OPTIONS:
--target <target> Specify target(s) to generate bridge code for. If omitted,
generates for all targets with JavaScriptKit dependency.
--verbose Print verbose output.
"""
}
}
func performCommand(context: PluginContext, arguments: [String]) throws {
// Check for help flags to display usage information
if arguments.contains(where: { ["-h", "--help"].contains($0) }) {
printStderr(Options.help())
return
}
var extractor = ArgumentExtractor(arguments)
let options = Options.parse(extractor: &extractor)
let remainingArguments = extractor.remainingArguments
let context = Context(options: options, context: context)
if options.targets.isEmpty {
try context.runOnTargets(
remainingArguments: remainingArguments,
where: { target in
target.hasDependency(named: Self.JAVASCRIPTKIT_PACKAGE_NAME)
}
)
} else {
try context.runOnTargets(
remainingArguments: remainingArguments,
where: { options.targets.contains($0.name) }
)
}
}
struct Context {
let options: Options
let context: PluginContext
}
}
extension BridgeJSCommandPlugin.Context {
func runOnTargets(
remainingArguments: [String],
where predicate: (SwiftSourceModuleTarget) -> Bool
) throws {
for target in context.package.targets {
guard let target = target as? SwiftSourceModuleTarget else {
continue
}
let configFilePath = target.directoryURL.appending(path: "bridge-js.config.json")
if !FileManager.default.fileExists(atPath: configFilePath.path) {
printVerbose("No bridge-js.config.json found for \(target.name), skipping...")
continue
}
guard predicate(target) else {
continue
}
try runSingleTarget(target: target, remainingArguments: remainingArguments)
}
}
private func runSingleTarget(
target: SwiftSourceModuleTarget,
remainingArguments: [String]
) throws {
printStderr("Generating bridge code for \(target.name)...")
printVerbose("Exporting Swift API for \(target.name)...")
let generatedDirectory = target.directoryURL.appending(path: "Generated")
let generatedJavaScriptDirectory = generatedDirectory.appending(path: "JavaScript")
try runBridgeJSTool(
arguments: [
"export",
"--module-name",
target.name,
"--target-dir",
target.directoryURL.path,
"--output-skeleton",
generatedJavaScriptDirectory.appending(path: "BridgeJS.ExportSwift.json").path,
"--output-swift",
generatedDirectory.appending(path: "BridgeJS.ExportSwift.swift").path,
"--verbose",
options.verbose ? "true" : "false",
]
+ target.sourceFiles.filter {
!$0.url.path.hasPrefix(generatedDirectory.path + "/")
}.map(\.url.path) + remainingArguments
)
printVerbose("Importing TypeScript API for \(target.name)...")
let bridgeDtsPath = target.directoryURL.appending(path: "bridge-js.d.ts")
// Execute import only if bridge-js.d.ts exists
if FileManager.default.fileExists(atPath: bridgeDtsPath.path) {
try runBridgeJSTool(
arguments: [
"import",
"--target-dir",
target.directoryURL.path,
"--output-skeleton",
generatedJavaScriptDirectory.appending(path: "BridgeJS.ImportTS.json").path,
"--output-swift",
generatedDirectory.appending(path: "BridgeJS.ImportTS.swift").path,
"--verbose",
options.verbose ? "true" : "false",
"--module-name",
target.name,
"--project",
context.package.directoryURL.appending(path: "tsconfig.json").path,
bridgeDtsPath.path,
] + remainingArguments
)
}
}
private func runBridgeJSTool(arguments: [String]) throws {
let tool = try context.tool(named: "BridgeJSTool").url
printVerbose("$ \(tool.path) \(arguments.joined(separator: " "))")
let process = Process()
process.executableURL = tool
process.arguments = arguments
try process.forwardTerminationSignals {
try process.run()
process.waitUntilExit()
}
if process.terminationStatus != 0 {
exit(process.terminationStatus)
}
}
private func printVerbose(_ message: String) {
if options.verbose {
printStderr(message)
}
}
}
private func printStderr(_ message: String) {
fputs(message + "\n", stderr)
}
extension SwiftSourceModuleTarget {
func hasDependency(named name: String) -> Bool {
return dependencies.contains(where: {
switch $0 {
case .product(let product):
return product.name == name
case .target(let target):
return target.name == name
@unknown default:
return false
}
})
}
}
extension Foundation.Process {
// Monitor termination/interrruption signals to forward them to child process
func setSignalForwarding(_ signalNo: Int32) -> DispatchSourceSignal {
let signalSource = DispatchSource.makeSignalSource(signal: signalNo)
signalSource.setEventHandler { [self] in
signalSource.cancel()
kill(processIdentifier, signalNo)
}
signalSource.resume()
return signalSource
}
func forwardTerminationSignals(_ body: () throws -> Void) rethrows {
let sources = [
setSignalForwarding(SIGINT),
setSignalForwarding(SIGTERM),
]
defer {
for source in sources {
source.cancel()
}
}
try body()
}
}
#endif