@napi-rs/cli 3.0.0-alpha.1 → 3.0.0-alpha.100

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 (176) hide show
  1. package/cli.mjs +1 -1
  2. package/dist/api/__tests__/create-npm-dirs.spec.d.ts +1 -0
  3. package/dist/api/__tests__/new.spec.d.ts +1 -0
  4. package/dist/api/build.d.ts +2 -2
  5. package/dist/api/create-npm-dirs.d.ts +5 -0
  6. package/dist/api/templates/index.d.ts +0 -7
  7. package/dist/api/templates/js-binding.d.ts +2 -1
  8. package/dist/api/templates/load-wasi-template.d.ts +2 -0
  9. package/dist/api/templates/wasi-worker-template.d.ts +2 -0
  10. package/dist/cli.js +3961 -14
  11. package/dist/def/artifacts.d.ts +21 -1
  12. package/dist/def/build.d.ts +167 -4
  13. package/dist/def/create-npm-dirs.d.ts +10 -0
  14. package/dist/def/new.d.ts +25 -7
  15. package/dist/def/pre-publish.d.ts +21 -2
  16. package/dist/def/rename.d.ts +16 -6
  17. package/dist/def/universalize.d.ts +10 -0
  18. package/dist/def/version.d.ts +10 -0
  19. package/dist/index.cjs +10142 -20524
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +3711 -29
  22. package/dist/utils/__tests__/config.spec.d.ts +1 -0
  23. package/dist/utils/config.d.ts +70 -6
  24. package/dist/utils/index.d.ts +1 -1
  25. package/dist/utils/metadata.d.ts +13 -1
  26. package/dist/utils/misc.d.ts +3 -3
  27. package/dist/utils/read-config.d.ts +7 -0
  28. package/dist/utils/target.d.ts +9 -6
  29. package/dist/utils/typegen.d.ts +4 -1
  30. package/dist/utils/version.d.ts +2 -1
  31. package/package.json +60 -24
  32. package/src/api/__tests__/create-npm-dirs.spec.ts +210 -0
  33. package/src/api/__tests__/new.spec.ts +429 -0
  34. package/src/api/artifacts.ts +83 -8
  35. package/src/api/build.ts +682 -134
  36. package/src/api/create-npm-dirs.ts +64 -13
  37. package/src/api/new.ts +389 -125
  38. package/src/api/pre-publish.ts +27 -16
  39. package/src/api/rename.ts +103 -17
  40. package/src/api/templates/index.ts +0 -7
  41. package/src/api/templates/js-binding.ts +212 -107
  42. package/src/api/templates/load-wasi-template.ts +216 -0
  43. package/src/api/templates/wasi-worker-template.ts +122 -0
  44. package/src/api/universalize.ts +13 -8
  45. package/src/api/version.ts +5 -2
  46. package/src/commands/artifacts.ts +2 -2
  47. package/src/commands/build.ts +1 -1
  48. package/src/commands/new.ts +46 -49
  49. package/src/def/artifacts.ts +22 -3
  50. package/src/def/build.ts +83 -8
  51. package/src/def/create-npm-dirs.ts +9 -0
  52. package/src/def/new.ts +28 -3
  53. package/src/def/pre-publish.ts +24 -3
  54. package/src/def/rename.ts +11 -2
  55. package/src/def/universalize.ts +9 -0
  56. package/src/def/version.ts +9 -0
  57. package/src/index.ts +2 -0
  58. package/src/utils/__tests__/__fixtures__/napi_type_def +130 -130
  59. package/src/utils/__tests__/__snapshots__/config.spec.ts.md +97 -0
  60. package/src/utils/__tests__/__snapshots__/config.spec.ts.snap +0 -0
  61. package/src/utils/__tests__/__snapshots__/target.spec.ts.md +56 -0
  62. package/src/utils/__tests__/__snapshots__/target.spec.ts.snap +0 -0
  63. package/src/utils/__tests__/__snapshots__/typegen.spec.ts.md +703 -164
  64. package/src/utils/__tests__/__snapshots__/typegen.spec.ts.snap +0 -0
  65. package/src/utils/__tests__/__snapshots__/version.spec.ts.md +9 -8
  66. package/src/utils/__tests__/__snapshots__/version.spec.ts.snap +0 -0
  67. package/src/utils/__tests__/config.spec.ts +81 -0
  68. package/src/utils/__tests__/typegen.spec.ts +19 -4
  69. package/src/utils/cargo.ts +2 -2
  70. package/src/utils/config.ts +147 -13
  71. package/src/utils/index.ts +1 -1
  72. package/src/utils/log.ts +1 -1
  73. package/src/utils/metadata.ts +52 -14
  74. package/src/utils/misc.ts +21 -7
  75. package/src/utils/read-config.ts +20 -0
  76. package/src/utils/target.ts +53 -9
  77. package/src/utils/typegen.ts +100 -40
  78. package/src/utils/version.ts +11 -9
  79. package/dist/api/artifacts.js +0 -50
  80. package/dist/api/build.js +0 -404
  81. package/dist/api/create-npm-dirs.js +0 -63
  82. package/dist/api/new.js +0 -154
  83. package/dist/api/pre-publish.js +0 -157
  84. package/dist/api/rename.js +0 -28
  85. package/dist/api/templates/.gitignore.d.ts +0 -1
  86. package/dist/api/templates/.gitignore.js +0 -198
  87. package/dist/api/templates/.npmignore.d.ts +0 -1
  88. package/dist/api/templates/.npmignore.js +0 -14
  89. package/dist/api/templates/build.rs.d.ts +0 -1
  90. package/dist/api/templates/build.rs.js +0 -4
  91. package/dist/api/templates/cargo.toml.d.ts +0 -6
  92. package/dist/api/templates/cargo.toml.js +0 -25
  93. package/dist/api/templates/ci-template.d.ts +0 -1
  94. package/dist/api/templates/ci-template.js +0 -566
  95. package/dist/api/templates/ci.yml.d.ts +0 -1
  96. package/dist/api/templates/ci.yml.js +0 -92
  97. package/dist/api/templates/index.js +0 -8
  98. package/dist/api/templates/js-binding.js +0 -124
  99. package/dist/api/templates/lib.rs.d.ts +0 -1
  100. package/dist/api/templates/lib.rs.js +0 -10
  101. package/dist/api/templates/package.json.d.ts +0 -8
  102. package/dist/api/templates/package.json.js +0 -30
  103. package/dist/api/universalize.js +0 -38
  104. package/dist/api/version.js +0 -16
  105. package/dist/commands/artifacts.js +0 -19
  106. package/dist/commands/build.js +0 -34
  107. package/dist/commands/create-npm-dirs.js +0 -7
  108. package/dist/commands/help.js +0 -12
  109. package/dist/commands/new.js +0 -112
  110. package/dist/commands/pre-publish.js +0 -8
  111. package/dist/commands/rename.js +0 -7
  112. package/dist/commands/universalize.js +0 -7
  113. package/dist/commands/version.js +0 -7
  114. package/dist/def/artifacts.js +0 -38
  115. package/dist/def/build.js +0 -105
  116. package/dist/def/commands/artifacts.d.ts +0 -15
  117. package/dist/def/commands/artifacts.js +0 -29
  118. package/dist/def/commands/build.d.ts +0 -53
  119. package/dist/def/commands/build.js +0 -105
  120. package/dist/def/commands/create-npm-dirs.d.ts +0 -15
  121. package/dist/def/commands/create-npm-dirs.js +0 -29
  122. package/dist/def/commands/new.d.ts +0 -27
  123. package/dist/def/commands/new.js +0 -53
  124. package/dist/def/commands/pre-publish.d.ts +0 -23
  125. package/dist/def/commands/pre-publish.js +0 -45
  126. package/dist/def/commands/rename.d.ts +0 -25
  127. package/dist/def/commands/rename.js +0 -49
  128. package/dist/def/commands/universalize.d.ts +0 -13
  129. package/dist/def/commands/universalize.js +0 -25
  130. package/dist/def/commands/version.d.ts +0 -13
  131. package/dist/def/commands/version.js +0 -25
  132. package/dist/def/create-npm-dirs.js +0 -38
  133. package/dist/def/new.js +0 -66
  134. package/dist/def/options/artifacts.d.ts +0 -35
  135. package/dist/def/options/artifacts.js +0 -11
  136. package/dist/def/options/build.d.ts +0 -97
  137. package/dist/def/options/build.js +0 -3
  138. package/dist/def/options/create-npm-dirs.d.ts +0 -35
  139. package/dist/def/options/create-npm-dirs.js +0 -11
  140. package/dist/def/options/new.d.ts +0 -79
  141. package/dist/def/options/new.js +0 -15
  142. package/dist/def/options/pre-publish.d.ts +0 -65
  143. package/dist/def/options/pre-publish.js +0 -13
  144. package/dist/def/options/rename.d.ts +0 -75
  145. package/dist/def/options/rename.js +0 -11
  146. package/dist/def/options/universalize.d.ts +0 -28
  147. package/dist/def/options/universalize.js +0 -10
  148. package/dist/def/options/version.d.ts +0 -28
  149. package/dist/def/options/version.js +0 -10
  150. package/dist/def/pre-publish.js +0 -56
  151. package/dist/def/rename.js +0 -58
  152. package/dist/def/universalize.js +0 -33
  153. package/dist/def/version.js +0 -33
  154. package/dist/utils/__tests__/target.spec.js +0 -10
  155. package/dist/utils/__tests__/typegen.spec.js +0 -37
  156. package/dist/utils/__tests__/version.spec.js +0 -5
  157. package/dist/utils/cargo.js +0 -33
  158. package/dist/utils/ci.d.ts +0 -11
  159. package/dist/utils/ci.js +0 -86
  160. package/dist/utils/config.js +0 -42
  161. package/dist/utils/index.js +0 -9
  162. package/dist/utils/log.js +0 -14
  163. package/dist/utils/metadata.js +0 -19
  164. package/dist/utils/misc.js +0 -35
  165. package/dist/utils/target.js +0 -109
  166. package/dist/utils/typegen.js +0 -158
  167. package/dist/utils/version.js +0 -59
  168. package/src/api/templates/.gitignore.ts +0 -198
  169. package/src/api/templates/.npmignore.ts +0 -14
  170. package/src/api/templates/build.rs.ts +0 -4
  171. package/src/api/templates/cargo.toml.ts +0 -35
  172. package/src/api/templates/ci-template.ts +0 -566
  173. package/src/api/templates/ci.yml.ts +0 -116
  174. package/src/api/templates/lib.rs.ts +0 -10
  175. package/src/api/templates/package.json.ts +0 -44
  176. package/src/utils/ci.ts +0 -102
package/dist/api/build.js DELETED
@@ -1,404 +0,0 @@
1
- import { spawn } from 'child_process';
2
- import { createHash } from 'crypto';
3
- import { tmpdir } from 'os';
4
- import { parse, join, resolve } from 'path';
5
- import * as colors from 'colorette';
6
- import { CLI_VERSION, copyFileAsync, debugFactory, DEFAULT_TYPE_DEF_HEADER, fileExists, getSystemDefaultTarget, getTargetLinker, mkdirAsync, parseMetadata, parseTriple, processTypeDef, readNapiConfig, targetToEnvVar, tryInstallCargoBinary, unlinkAsync, writeFileAsync, } from '../utils/index.js';
7
- import { createJsBinding } from './templates/index.js';
8
- const debug = debugFactory('build');
9
- export async function buildProject(options) {
10
- debug('napi build command receive options: %O', options);
11
- const cwd = options.cwd ?? process.cwd();
12
- const resolvePath = (...paths) => resolve(cwd, ...paths);
13
- const manifestPath = resolvePath(options.manifestPath ?? 'Cargo.toml');
14
- const metadata = parseMetadata(manifestPath);
15
- const pkg = metadata.packages.find((p) => {
16
- // package with given name
17
- if (options.package) {
18
- return p.name === options.package;
19
- }
20
- else {
21
- return p.manifest_path === manifestPath;
22
- }
23
- });
24
- if (!pkg) {
25
- throw new Error('Unable to find crate to build. It seems you are trying to build a crate in a workspace, try using `--package` option to specify the package to build.');
26
- }
27
- const crateDir = parse(pkg.manifest_path).dir;
28
- const builder = new Builder(options, pkg, cwd, options.target
29
- ? parseTriple(options.target)
30
- : process.env.CARGO_BUILD_TARGET
31
- ? parseTriple(process.env.CARGO_BUILD_TARGET)
32
- : getSystemDefaultTarget(), crateDir, resolvePath(options.outputDir ?? crateDir), options.targetDir ??
33
- process.env.CARGO_BUILD_TARGET_DIR ??
34
- metadata.target_directory, await readNapiConfig(resolvePath(options.packageJsonPath ?? 'package.json')));
35
- return builder.build();
36
- }
37
- class Builder {
38
- options;
39
- crate;
40
- cwd;
41
- target;
42
- crateDir;
43
- outputDir;
44
- targetDir;
45
- config;
46
- args = [];
47
- envs = {};
48
- outputs = [];
49
- constructor(options, crate, cwd, target, crateDir, outputDir, targetDir, config) {
50
- this.options = options;
51
- this.crate = crate;
52
- this.cwd = cwd;
53
- this.target = target;
54
- this.crateDir = crateDir;
55
- this.outputDir = outputDir;
56
- this.targetDir = targetDir;
57
- this.config = config;
58
- }
59
- get cdyLibName() {
60
- return this.crate.targets.find((t) => t.crate_types.includes('cdylib'))
61
- ?.name;
62
- }
63
- get binName() {
64
- return (this.options.bin ??
65
- // only available if not cdylib or bin name specified
66
- (this.cdyLibName
67
- ? null
68
- : this.crate.targets.find((t) => t.crate_types.includes('bin'))?.name));
69
- }
70
- build() {
71
- if (!this.cdyLibName) {
72
- const warning = 'Missing `crate-type = ["cdylib"]` in [lib] config. The build result will not be available as node addon.';
73
- if (this.binName) {
74
- debug.warn(warning);
75
- }
76
- else {
77
- throw new Error(warning);
78
- }
79
- }
80
- return this.pickBinary()
81
- .setPackage()
82
- .setFeatures()
83
- .setTarget()
84
- .setEnvs()
85
- .setBypassArgs()
86
- .exec();
87
- }
88
- exec() {
89
- debug(`Start building crate: ${this.crate.name}`);
90
- debug(' %i', `cargo ${this.args.join(' ')}`);
91
- const controller = new AbortController();
92
- const buildTask = new Promise((resolve, reject) => {
93
- const buildProcess = spawn('cargo', this.args, {
94
- env: {
95
- ...process.env,
96
- ...this.envs,
97
- },
98
- stdio: 'inherit',
99
- cwd: this.cwd,
100
- signal: controller.signal,
101
- });
102
- buildProcess.once('exit', (code) => {
103
- if (code === 0) {
104
- debug('%i', `Build crate ${this.crate.name} successfully!`);
105
- resolve();
106
- }
107
- else {
108
- reject(new Error(`Build failed with exit code ${code}`));
109
- }
110
- });
111
- buildProcess.once('error', (e) => {
112
- reject(new Error(`Build failed with error: ${e.message}`, {
113
- cause: e,
114
- }));
115
- });
116
- });
117
- return {
118
- task: buildTask.then(() => this.postBuild()),
119
- abort: () => controller.abort(),
120
- };
121
- }
122
- pickBinary() {
123
- let set = false;
124
- if (this.options.watch) {
125
- if (process.env.CI) {
126
- debug.warn('Watch mode is not supported in CI environment');
127
- }
128
- else {
129
- debug('Use %i', 'cargo-watch');
130
- tryInstallCargoBinary('cargo-watch', 'watch');
131
- // yarn napi watch --target x86_64-unknown-linux-gnu [--cross-compile]
132
- // ===>
133
- // cargo watch [...] -- build --target x86_64-unknown-linux-gnu
134
- // cargo watch [...] -- zigbuild --target x86_64-unknown-linux-gnu
135
- this.args.push('watch', '--why', '-i', '*.{js,ts,node}', '-w', this.crateDir, '--', 'cargo');
136
- set = true;
137
- }
138
- }
139
- if (this.options.crossCompile) {
140
- if (this.target.platform === 'win32') {
141
- if (process.platform === 'win32') {
142
- debug.warn('You are trying to cross compile to win32 platform on win32 platform which is unnecessary.');
143
- }
144
- else {
145
- // use cargo-xwin to cross compile to win32 platform
146
- debug('Use %i', 'cargo-xwin');
147
- tryInstallCargoBinary('cargo-xwin', 'xwin');
148
- this.args.push('xwin', 'build');
149
- if (this.target.arch === 'ia32') {
150
- this.envs.XWIN_ARCH = 'x86';
151
- }
152
- set = true;
153
- }
154
- }
155
- else {
156
- if (this.target.platform === 'linux' &&
157
- process.platform === 'linux' &&
158
- this.target.arch === process.arch &&
159
- (function (abi) {
160
- const glibcVersionRuntime =
161
- // @ts-expect-error
162
- process.report?.getReport()?.header?.glibcVersionRuntime;
163
- const libc = glibcVersionRuntime ? 'gnu' : 'musl';
164
- return abi === libc;
165
- })(this.target.abi)) {
166
- debug.warn('You are trying to cross compile to linux target on linux platform which is unnecessary.');
167
- }
168
- else if (this.target.platform === 'darwin' &&
169
- process.platform === 'darwin') {
170
- debug.warn('You are trying to cross compile to darwin target on darwin platform which is unnecessary.');
171
- }
172
- else {
173
- // use cargo-zigbuild to cross compile to other platforms
174
- debug('Use %i', 'cargo-zigbuild');
175
- tryInstallCargoBinary('cargo-zigbuild', 'zigbuild');
176
- this.args.push('zigbuild');
177
- set = true;
178
- }
179
- }
180
- }
181
- if (!set) {
182
- this.args.push('build');
183
- }
184
- return this;
185
- }
186
- setPackage() {
187
- const args = [];
188
- if (this.options.package) {
189
- args.push('--package', this.options.package);
190
- }
191
- if (this.binName) {
192
- args.push('--bin', this.binName);
193
- }
194
- if (args.length) {
195
- debug('Set package flags: ');
196
- debug(' %O', args);
197
- this.args.push(...args);
198
- }
199
- return this;
200
- }
201
- setTarget() {
202
- debug('Set compiling target to: ');
203
- debug(' %i', this.target.triple);
204
- this.args.push('--target', this.target.triple);
205
- return this;
206
- }
207
- setEnvs() {
208
- // type definition intermediate file
209
- this.envs.TYPE_DEF_TMP_PATH = this.getIntermediateTypeFile();
210
- this.envs.CARGO_CFG_NAPI_RS_CLI_VERSION = CLI_VERSION;
211
- // RUSTFLAGS
212
- let rustflags = process.env.RUSTFLAGS ?? process.env.CARGO_BUILD_RUSTFLAGS ?? '';
213
- if (this.target.abi?.includes('musl') &&
214
- !rustflags.includes('target-feature=-crt-static')) {
215
- rustflags += ' -C target-feature=-crt-static';
216
- }
217
- if (this.options.strip && !rustflags.includes('link-arg=-s')) {
218
- rustflags += ' -C link-arg=-s';
219
- }
220
- if (rustflags.length) {
221
- this.envs.RUSTFLAGS = rustflags;
222
- }
223
- // END RUSTFLAGS
224
- // LINKER
225
- const linker = getTargetLinker(this.target.triple);
226
- if (linker &&
227
- !process.env.RUSTC_LINKER &&
228
- !process.env[`CARGET_TARGET_${targetToEnvVar(this.target.triple)}_LINKER`]) {
229
- this.envs.RUSTC_LINKER = linker;
230
- }
231
- if (this.target.platform === 'android') {
232
- const { ANDROID_NDK_LATEST_HOME } = process.env;
233
- if (!ANDROID_NDK_LATEST_HOME) {
234
- debug.warn(`${colors.red('ANDROID_NDK_LATEST_HOME')} environment variable is missing`);
235
- }
236
- const targetArch = this.target.arch === 'arm' ? 'armv7a' : 'aarch64';
237
- const targetPlatform = this.target.arch === 'arm' ? 'androideabi24' : 'android24';
238
- Object.assign(this.envs, {
239
- CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/${targetArch}-linux-android24-clang`,
240
- CARGO_TARGET_ARMV7_LINUX_ANDROIDEABI_LINKER: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/${targetArch}-linux-androideabi24-clang`,
241
- CC: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/${targetArch}-linux-${targetPlatform}-clang`,
242
- CXX: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/${targetArch}-linux-${targetPlatform}-clang++`,
243
- AR: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar`,
244
- ANDROID_NDK: ANDROID_NDK_LATEST_HOME,
245
- PATH: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin:${process.env.PATH}`,
246
- });
247
- }
248
- // END LINKER
249
- debug('Set envs: ');
250
- Object.entries(this.envs).forEach(([k, v]) => {
251
- debug(' %i', `${k}=${v}`);
252
- });
253
- return this;
254
- }
255
- setFeatures() {
256
- const args = [];
257
- if (this.options.allFeatures) {
258
- args.push('--all-features');
259
- }
260
- else if (this.options.noDefaultFeatures) {
261
- args.push('--no-default-features');
262
- }
263
- else if (this.options.features) {
264
- args.push('--features', ...this.options.features);
265
- }
266
- debug('Set features flags: ');
267
- debug(' %O', args);
268
- this.args.push(...args);
269
- return this;
270
- }
271
- setBypassArgs() {
272
- if (this.options.release) {
273
- this.args.push('--release');
274
- }
275
- if (this.options.verbose) {
276
- this.args.push('--verbose');
277
- }
278
- if (this.options.targetDir) {
279
- this.args.push('--target-dir', this.options.targetDir);
280
- }
281
- if (this.options.cargoOptions?.length) {
282
- this.args.push(...this.options.cargoOptions);
283
- }
284
- return this;
285
- }
286
- getIntermediateTypeFile() {
287
- return join(tmpdir(), `${this.crate.name}-${createHash('sha256')
288
- .update(this.crate.manifest_path)
289
- .update(CLI_VERSION)
290
- .digest('hex')
291
- .substring(0, 8)}.napi_type_def.tmp`);
292
- }
293
- async postBuild() {
294
- try {
295
- debug(`Try to create output directory:`);
296
- debug(' %i', this.outputDir);
297
- await mkdirAsync(this.outputDir, { recursive: true });
298
- debug(`Output directory created`);
299
- }
300
- catch (e) {
301
- throw new Error(`Failed to create output directory ${this.outputDir}`, {
302
- cause: e,
303
- });
304
- }
305
- await this.copyArtifact();
306
- // only for cdylib
307
- if (this.cdyLibName) {
308
- await this.generateTypeDef();
309
- await this.writeJsBinding();
310
- }
311
- return this.outputs;
312
- }
313
- async copyArtifact() {
314
- const [srcName, destName] = this.getArtifactNames();
315
- if (!srcName || !destName) {
316
- return;
317
- }
318
- const src = join(this.targetDir, this.target.triple, this.options.release ? 'release' : 'debug', srcName);
319
- const dest = join(this.outputDir, destName);
320
- try {
321
- if (await fileExists(dest)) {
322
- debug('Old artifact found, remove it first');
323
- await unlinkAsync(dest);
324
- }
325
- debug('Copy artifact to:');
326
- debug(' %i', dest);
327
- await copyFileAsync(src, dest);
328
- this.outputs.push({
329
- kind: dest.endsWith('.node') ? 'node' : 'exe',
330
- path: dest,
331
- });
332
- }
333
- catch (e) {
334
- throw new Error('Failed to copy artifact', {
335
- cause: e,
336
- });
337
- }
338
- }
339
- getArtifactNames() {
340
- if (this.cdyLibName) {
341
- const cdyLib = this.cdyLibName.replace(/-/g, '_');
342
- const srcName = this.target.platform === 'darwin'
343
- ? `lib${cdyLib}.dylib`
344
- : this.target.platform === 'win32'
345
- ? `${cdyLib}.dll`
346
- : `lib${cdyLib}.so`;
347
- let destName = this.config.binaryName;
348
- // add platform suffix to binary name
349
- // index[.linux-x64-gnu].node
350
- // ^^^^^^^^^^^^^^
351
- if (this.options.platform) {
352
- destName += `.${this.target.platformArchABI}`;
353
- }
354
- destName += '.node';
355
- return [srcName, destName];
356
- }
357
- else if (this.binName) {
358
- const srcName = this.target.platform === 'win32' ? `${this.binName}.exe` : this.binName;
359
- return [srcName, srcName];
360
- }
361
- return [];
362
- }
363
- async generateTypeDef() {
364
- if (!(await fileExists(this.envs.TYPE_DEF_TMP_PATH))) {
365
- return;
366
- }
367
- const dest = join(this.outputDir, this.options.dts ?? 'index.d.ts');
368
- const dts = await processTypeDef(this.envs.TYPE_DEF_TMP_PATH, !this.options.noDtsHeader
369
- ? this.options.dtsHeader ?? DEFAULT_TYPE_DEF_HEADER
370
- : '');
371
- try {
372
- debug('Writing type def to:');
373
- debug(' %i', dest);
374
- await writeFileAsync(dest, dts, 'utf-8');
375
- this.outputs.push({
376
- kind: 'dts',
377
- path: dest,
378
- });
379
- }
380
- catch (e) {
381
- debug.error('Failed to write type def file');
382
- debug.error(e);
383
- }
384
- }
385
- async writeJsBinding() {
386
- if (!this.options.platform || this.options.noJsBinding) {
387
- return;
388
- }
389
- const dest = join(this.outputDir, this.options.jsBinding ?? 'index.js');
390
- const js = createJsBinding(this.config.binaryName, this.config.packageName);
391
- try {
392
- debug('Writing js binding to:');
393
- debug(' %i', dest);
394
- await writeFileAsync(dest, js, 'utf-8');
395
- this.outputs.push({
396
- kind: 'js',
397
- path: dest,
398
- });
399
- }
400
- catch (e) {
401
- throw new Error('Failed to write js binding file', { cause: e });
402
- }
403
- }
404
- }
@@ -1,63 +0,0 @@
1
- import { join, resolve } from 'path';
2
- import { applyDefaultCreateNpmDirsOptions, } from '../def/create-npm-dirs.js';
3
- import { debugFactory, readNapiConfig, mkdirAsync as rawMkdirAsync, pick, writeFileAsync as rawWriteFileAsync, } from '../utils/index.js';
4
- const debug = debugFactory('create-npm-dirs');
5
- export async function createNpmDirs(userOptions) {
6
- const options = applyDefaultCreateNpmDirsOptions(userOptions);
7
- async function mkdirAsync(dir) {
8
- debug('Try to create dir: %i', dir);
9
- if (options.dryRun) {
10
- return;
11
- }
12
- await rawMkdirAsync(dir, {
13
- recursive: true,
14
- });
15
- }
16
- async function writeFileAsync(file, content) {
17
- debug('Writing file %i', file);
18
- if (options.dryRun) {
19
- debug(content);
20
- return;
21
- }
22
- await rawWriteFileAsync(file, content);
23
- }
24
- const packageJsonPath = resolve(options.cwd, options.packageJsonPath);
25
- const npmPath = resolve(options.cwd, options.npmDir);
26
- debug(`Read content from [${packageJsonPath}]`);
27
- const { targets, binaryName, packageName, packageJson } = await readNapiConfig(packageJsonPath);
28
- for (const target of targets) {
29
- const targetDir = join(npmPath, `${target.platformArchABI}`);
30
- await mkdirAsync(targetDir);
31
- const binaryFileName = `${binaryName}.${target.platformArchABI}.node`;
32
- const scopedPackageJson = {
33
- name: `${packageName}-${target.platformArchABI}`,
34
- version: packageJson.version,
35
- os: [target.platform],
36
- cpu: target.arch !== 'universal' ? [target.arch] : undefined,
37
- main: binaryFileName,
38
- files: [binaryFileName],
39
- ...pick(packageJson, 'description', 'keywords', 'author', 'authors', 'homepage', 'license', 'engines', 'publishConfig', 'repository', 'bugs'),
40
- };
41
- // Only works with yarn 3.1+
42
- // https://github.com/yarnpkg/berry/pull/3981
43
- if (target.abi === 'gnu') {
44
- // @ts-expect-error
45
- scopedPackageJson.libc = ['glibc'];
46
- }
47
- else if (target.abi === 'musl') {
48
- // @ts-expect-error
49
- scopedPackageJson.libc = ['musl'];
50
- }
51
- const targetPackageJson = join(targetDir, 'package.json');
52
- await writeFileAsync(targetPackageJson, JSON.stringify(scopedPackageJson, null, 2));
53
- const targetReadme = join(targetDir, 'README.md');
54
- await writeFileAsync(targetReadme, readme(packageName, target));
55
- debug.info(`${packageName}-${target.platformArchABI} created`);
56
- }
57
- }
58
- function readme(packageName, target) {
59
- return `# \`${packageName}-${target.platformArchABI}\`
60
-
61
- This is the **${target.triple}** binary for \`${packageName}\`
62
- `;
63
- }
package/dist/api/new.js DELETED
@@ -1,154 +0,0 @@
1
- import path from 'path';
2
- import { applyDefaultNewOptions, } from '../def/new.js';
3
- import { AVAILABLE_TARGETS, CLI_VERSION, debugFactory, DEFAULT_TARGETS, mkdirAsync, writeFileAsync, } from '../utils/index.js';
4
- import { napiEngineRequirement } from '../utils/version.js';
5
- import { createBuildRs, createCargoToml, createGithubActionsCIYml, createLibRs, createPackageJson, gitIgnore, npmIgnore, } from './templates/index.js';
6
- const debug = debugFactory('new');
7
- function processOptions(options) {
8
- debug('Processing options...');
9
- options.path = path.resolve(process.cwd(), options.path);
10
- debug(`Resolved target path to: ${options.path}`);
11
- if (!options.name) {
12
- options.name = path.parse(options.path).base;
13
- debug(`No project name provided, fix it to dir name: ${options.name}`);
14
- }
15
- if (!options.targets?.length) {
16
- if (options.enableAllTargets) {
17
- options.targets = AVAILABLE_TARGETS.concat();
18
- debug('Enable all targets');
19
- }
20
- else if (options.enableDefaultTargets) {
21
- options.targets = DEFAULT_TARGETS.concat();
22
- debug('Enable default targets');
23
- }
24
- else {
25
- throw new Error('At least one target must be enabled');
26
- }
27
- }
28
- return applyDefaultNewOptions(options);
29
- }
30
- export async function newProject(userOptions) {
31
- debug('Will create napi-rs project with given options:');
32
- debug(userOptions);
33
- const options = processOptions(userOptions);
34
- debug('Targets to be enabled:');
35
- debug(options.targets);
36
- const outputs = generateFiles(options);
37
- try {
38
- debug(`Try to create target directory: ${options.path}`);
39
- if (!options.dryRun) {
40
- await mkdirAsync(options.path, { recursive: true });
41
- }
42
- }
43
- catch (e) {
44
- throw new Error(`Failed to create target directory: ${options.path}`, {
45
- cause: e,
46
- });
47
- }
48
- await dumpOutputs(outputs, options.dryRun);
49
- debug(`Project created at: ${options.path}`);
50
- }
51
- function generateFiles(options) {
52
- return [
53
- generateCargoToml,
54
- generateLibRs,
55
- generateBuildRs,
56
- generatePackageJson,
57
- generateGithubWorkflow,
58
- generateIgnoreFiles,
59
- ].flatMap((generator) => {
60
- const output = generator(options);
61
- if (!output) {
62
- return [];
63
- }
64
- if (Array.isArray(output)) {
65
- return output.map((o) => ({
66
- ...o,
67
- target: path.join(options.path, o.target),
68
- }));
69
- }
70
- else {
71
- return [{ ...output, target: path.join(options.path, output.target) }];
72
- }
73
- });
74
- }
75
- function generateCargoToml(options) {
76
- return {
77
- target: './Cargo.toml',
78
- content: createCargoToml({
79
- name: options.name,
80
- license: options.license,
81
- features: [`napi${options.minNodeApiVersion}`],
82
- deriveFeatures: options.enableTypeDef ? ['type-def'] : [],
83
- }),
84
- };
85
- }
86
- function generateLibRs(_options) {
87
- return {
88
- target: './src/lib.rs',
89
- content: createLibRs(),
90
- };
91
- }
92
- function generateBuildRs(_options) {
93
- return {
94
- target: './build.rs',
95
- content: createBuildRs(),
96
- };
97
- }
98
- function generatePackageJson(options) {
99
- return {
100
- target: './package.json',
101
- content: createPackageJson({
102
- name: options.name,
103
- binaryName: getBinaryName(options.name),
104
- targets: options.targets,
105
- license: options.license,
106
- engineRequirement: napiEngineRequirement(options.minNodeApiVersion),
107
- cliVersion: CLI_VERSION,
108
- }),
109
- };
110
- }
111
- function generateGithubWorkflow(options) {
112
- if (!options.enableGithubActions) {
113
- return null;
114
- }
115
- return {
116
- target: './.github/workflows/ci.yml',
117
- content: createGithubActionsCIYml(getBinaryName(options.name), options.targets),
118
- };
119
- }
120
- function generateIgnoreFiles(_options) {
121
- return [
122
- {
123
- target: './.gitignore',
124
- content: gitIgnore,
125
- },
126
- {
127
- target: './.npmignore',
128
- content: npmIgnore,
129
- },
130
- ];
131
- }
132
- async function dumpOutputs(outputs, dryRun) {
133
- for (const output of outputs) {
134
- if (!output) {
135
- continue;
136
- }
137
- debug(`Writing project file: ${output.target}`);
138
- // only output content to logger instead of writing to file system
139
- if (dryRun) {
140
- debug(output.content);
141
- continue;
142
- }
143
- try {
144
- await mkdirAsync(path.dirname(output.target), { recursive: true });
145
- await writeFileAsync(output.target, output.content, 'utf-8');
146
- }
147
- catch (e) {
148
- throw new Error(`Failed to write file: ${output.target}`, { cause: e });
149
- }
150
- }
151
- }
152
- function getBinaryName(name) {
153
- return name.split('/').pop();
154
- }