@smoothbricks/nx-plugin 0.3.13 → 0.4.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.
@@ -0,0 +1,419 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { existsSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { join, resolve } from 'node:path';
6
+ function createWorkspaceNxRequire(workspaceRoot) {
7
+ const requireFromWorkspace = createRequire(join(workspaceRoot, 'package.json'));
8
+ return function requireNx(specifier) {
9
+ return requireFromWorkspace(specifier);
10
+ };
11
+ }
12
+ /** A full hit carries no payload, so it is the same value every time. */
13
+ const HIT = Object.freeze({ disposition: 'hit' });
14
+ const NO_TASK_RESULTS = Object.freeze({});
15
+ export function parseTargetSelector(spec) {
16
+ const parts = spec.split(':');
17
+ if (parts.length < 2 || parts.length > 3) {
18
+ return null;
19
+ }
20
+ for (const part of parts) {
21
+ if (part.length === 0) {
22
+ return null;
23
+ }
24
+ }
25
+ return { project: parts[0], target: parts[1], configuration: parts[2] };
26
+ }
27
+ export function describeMiss(reason) {
28
+ switch (reason.kind) {
29
+ case 'uncacheable':
30
+ return `${reason.taskId} is not cacheable, so it must run`;
31
+ case 'unhashable':
32
+ return `${reason.taskId} did not produce a task hash`;
33
+ case 'not-cached':
34
+ return `${reason.taskId} has no cached result for its current inputs`;
35
+ case 'cached-failure':
36
+ return `${reason.taskId} last failed with exit code ${reason.code}`;
37
+ case 'stale-outputs':
38
+ return `${reason.taskId} outputs are missing or modified on disk`;
39
+ case 'cache-disabled':
40
+ return `the Nx cache is disabled, so ${reason.taskId} must run`;
41
+ case 'no-daemon':
42
+ return `the Nx daemon is disabled, so ${reason.taskId} cannot be checked without running it`;
43
+ }
44
+ }
45
+ /**
46
+ * First reason the task set cannot be replayed, considering only recorded
47
+ * results — no filesystem access. `null` means every task is a recorded
48
+ * success, and the on-disk check is worth paying for.
49
+ *
50
+ * A cached *failure* counts as a miss even though Nx replays one when
51
+ * `NX_CACHE_FAILURES` is set: this facility exists to hand the process over to
52
+ * a binary, and replaying a failed build would hand over a stale one.
53
+ */
54
+ export function firstCacheMiss(tasks, cachedCodeByHash) {
55
+ for (const task of tasks) {
56
+ if (!task.cache) {
57
+ return { kind: 'uncacheable', taskId: task.id };
58
+ }
59
+ // A custom hasher is outside Nx's type guarantees and may return an empty
60
+ // value. Without a hash there is no cache key to query.
61
+ if (!task.hash) {
62
+ return { kind: 'unhashable', taskId: task.id };
63
+ }
64
+ const code = cachedCodeByHash.get(task.hash);
65
+ if (code === undefined) {
66
+ return { kind: 'not-cached', taskId: task.id };
67
+ }
68
+ if (code !== 0) {
69
+ return { kind: 'cached-failure', taskId: task.id, code };
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+ /**
75
+ * First task whose recorded outputs are no longer the bytes on disk.
76
+ *
77
+ * `matches[index]` is the daemon's verdict for `tasks[index]`. A short or
78
+ * ragged array counts as stale rather than as a hit: a missing verdict is not a
79
+ * positive one, and being wrong here means exec'ing a binary that was deleted.
80
+ */
81
+ export function firstStaleOutputs(tasks, matches) {
82
+ for (let index = 0; index < tasks.length; index += 1) {
83
+ if (matches[index] !== true) {
84
+ return { kind: 'stale-outputs', taskId: tasks[index].id };
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+ /**
90
+ * Make sure an Nx target's outputs are on disk, doing as little as possible
91
+ * when they already are.
92
+ *
93
+ * "Already built" is the hot path, because a checkout-local CLI wrapper pays it
94
+ * on every invocation. So it never spawns the `nx` CLI: the project graph, the
95
+ * task hashes and the on-disk output verification are daemon round-trips, the
96
+ * cache lookup is a local SQLite read, and Nx's task runner is only invoked
97
+ * once something is known to need running.
98
+ *
99
+ * With the daemon disabled there is no probe to make — hashing would have to
100
+ * build the project graph in this process, and no service holds the recorded
101
+ * output hashes to check the working tree against — so the target is handed to
102
+ * the workspace's own `nx` CLI unconditionally.
103
+ */
104
+ export async function ensureBuilt(options) {
105
+ const selector = parseTargetSelector(options.target);
106
+ if (!selector) {
107
+ throw new Error(`ensureBuilt: '${options.target}' is not a project:target[:configuration] selector`);
108
+ }
109
+ // Resolved before the chdir below, so a relative `cwd` still means what the
110
+ // caller meant.
111
+ const workspaceRoot = resolve(options.cwd);
112
+ const callerCwd = process.cwd();
113
+ const callerEnv = { ...process.env };
114
+ try {
115
+ // `cd <root> && nx run ...` is the invocation whose hashes are in the
116
+ // cache. Everything below — plugin hooks, `runtime` inputs, and the hasher,
117
+ // which keys against `process.cwd()` — has to see the same directory or the
118
+ // probe keys differently from the CLI and never hits.
119
+ process.chdir(workspaceRoot);
120
+ return await ensureBuiltInWorkspace(workspaceRoot, selector, options.onMiss ?? 'stream');
121
+ }
122
+ finally {
123
+ // Nx configures itself through the environment and this function runs
124
+ // in-process, so without this the caller — and anything it goes on to exec
125
+ // — would inherit NX_WORKSPACE_ROOT_PATH, the stream/prefix flags, and
126
+ // whatever a plugin's preTasksExecution hook injected. The wrapper this
127
+ // replaces got that isolation for free by running Nx in a child.
128
+ process.chdir(callerCwd);
129
+ for (const key of Object.keys(process.env)) {
130
+ if (!(key in callerEnv)) {
131
+ delete process.env[key];
132
+ }
133
+ }
134
+ for (const [key, value] of Object.entries(callerEnv)) {
135
+ if (process.env[key] !== value) {
136
+ process.env[key] = value;
137
+ }
138
+ }
139
+ }
140
+ }
141
+ async function ensureBuiltInWorkspace(workspaceRoot, selector, onMiss) {
142
+ // The environment has precedence over nx.json. Avoid loading Nx at all on
143
+ // this explicit fallback path, which also lets a deliberately minimal
144
+ // checkout-local CLI stand in for Nx.
145
+ if (process.env.NX_DAEMON === 'false') {
146
+ return runViaCli(workspaceRoot, selector);
147
+ }
148
+ // Nx rejects daemon access when the client package's version differs from
149
+ // the workspace's running daemon. Resolve every runtime module from the
150
+ // target checkout rather than this package's own dependency: a reusable
151
+ // wrapper must keep using the daemon after the workspace takes an Nx patch.
152
+ const requireNx = createWorkspaceNxRequire(workspaceRoot);
153
+ bindWorkspaceRoot(workspaceRoot, requireNx);
154
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
155
+ if (!daemonClient.enabled()) {
156
+ return runViaCli(workspaceRoot, selector);
157
+ }
158
+ // An outer Nx task exports its own cache-bypass setting to the process it
159
+ // launches. That setting describes the outer task, not the nested target:
160
+ // inheriting it makes the inner runner refuse cache writes forever. Outside
161
+ // an Nx task child, however, the same variables are the caller's explicit
162
+ // request to force this target to rebuild and must remain authoritative.
163
+ if (process.env.NX_TASK_TARGET_PROJECT !== undefined || process.env.NX_TASK_TARGET_TARGET !== undefined) {
164
+ delete process.env.NX_SKIP_NX_CACHE;
165
+ delete process.env.NX_DISABLE_NX_CACHE;
166
+ }
167
+ const { readNxJson } = requireNx('nx/src/config/nx-json');
168
+ const { splitArgsIntoNxArgsAndOverrides } = requireNx('nx/src/utils/command-line-utils');
169
+ const { setEnvVarsBasedOnArgs } = requireNx('nx/src/tasks-runner/run-command');
170
+ const hooks = requireNx('nx/src/project-graph/plugins/tasks-execution-hooks');
171
+ const nxJson = readNxJson();
172
+ // Reproduce `nx run <selector> --outputStyle=<style>` exactly. Task hashes
173
+ // are derived from these arguments, so anything hand-rolled here instead of
174
+ // routed through Nx's own argument normalization would key the cache
175
+ // differently from the CLI and turn every probe into a miss.
176
+ const { nxArgs, overrides } = splitArgsIntoNxArgsAndOverrides({ targets: [selector.target], configuration: selector.configuration, outputStyle: onMiss }, 'run-one', { printWarnings: false }, nxJson);
177
+ const loadDotEnvFiles = process.env.NX_LOAD_DOT_ENV_FILES !== 'false';
178
+ // Sets NX_LOAD_DOT_ENV_FILES and the stream/prefix flags, which the hasher
179
+ // reads through each task's environment. It has to happen before hashing or
180
+ // the probe keys differently from the CLI.
181
+ setEnvVarsBasedOnArgs(nxArgs, loadDotEnvFiles);
182
+ const runId = randomUUID();
183
+ const startTime = Date.now();
184
+ // Plugin `preTasksExecution` hooks inject environment variables, and declared
185
+ // `env` inputs hash against them. Skipping the hook would not merely cost
186
+ // hits: the run below would then execute with a different environment than
187
+ // the CLI does, record a hash the CLI never looks up, and thrash the cache.
188
+ await hooks.runPreTasksExecution({
189
+ id: runId,
190
+ workspaceRoot,
191
+ nxJsonConfiguration: nxJson,
192
+ argv: process.argv,
193
+ });
194
+ performance.mark('ensureBuilt:probe:start');
195
+ let reason;
196
+ if (process.env.NX_SKIP_NX_CACHE === 'true' || process.env.NX_DISABLE_NX_CACHE === 'true') {
197
+ const taskId = selector.configuration === undefined
198
+ ? `${selector.project}:${selector.target}`
199
+ : `${selector.project}:${selector.target}:${selector.configuration}`;
200
+ reason = { kind: 'cache-disabled', taskId };
201
+ }
202
+ else {
203
+ reason = await probe(nxJson, nxArgs, overrides, selector, requireNx);
204
+ }
205
+ performance.measure('ensureBuilt:probe', 'ensureBuilt:probe:start');
206
+ const outcome = reason === null
207
+ ? { result: HIT, taskResults: NO_TASK_RESULTS }
208
+ : await runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx);
209
+ await hooks.runPostTasksExecution({
210
+ id: runId,
211
+ taskResults: outcome.taskResults,
212
+ workspaceRoot,
213
+ nxJsonConfiguration: nxJson,
214
+ argv: process.argv,
215
+ startTime,
216
+ endTime: Date.now(),
217
+ });
218
+ return outcome.result;
219
+ }
220
+ /**
221
+ * Nx computes `workspaceRoot` once, at module load, from
222
+ * `NX_WORKSPACE_ROOT_PATH` or the current directory — and its daemon client is
223
+ * a module-level singleton that reads `nx.json` from that root. So the root has
224
+ * to be bound before the first Nx module loads, which is why this module
225
+ * imports Nx dynamically throughout. A static import at the top of the file
226
+ * would bind the caller's launch directory instead.
227
+ */
228
+ function bindWorkspaceRoot(workspaceRoot, requireNx) {
229
+ process.env.NX_WORKSPACE_ROOT_PATH = workspaceRoot;
230
+ if (process.env.NX_PERF_LOGGING === 'true') {
231
+ // Installs Nx's PerformanceObserver, which reports every `performance
232
+ // .measure` this module and Nx itself record. Loading it unconditionally
233
+ // would add an observer to hot paths that never want one.
234
+ requireNx('nx/src/utils/perf-logging');
235
+ }
236
+ const { workspaceRoot: boundRoot } = requireNx('nx/src/utils/workspace-root');
237
+ if (boundRoot !== workspaceRoot) {
238
+ // One process cannot serve two workspaces: the constant and the daemon
239
+ // client singleton are already bound. Say so rather than silently probing
240
+ // the wrong checkout.
241
+ throw new Error(`ensureBuilt: Nx is already bound to workspace root ${boundRoot}, cannot switch to ${workspaceRoot}`);
242
+ }
243
+ }
244
+ /** `null` when the target is already built; otherwise the first reason it is not. */
245
+ async function probe(nxJson, nxArgs, overrides, selector, requireNx) {
246
+ const { daemonClient } = requireNx('nx/src/daemon/client/client');
247
+ const { createTaskGraph } = requireNx('nx/src/tasks-runner/create-task-graph');
248
+ const { DaemonBasedTaskHasher } = requireNx('nx/src/hasher/task-hasher');
249
+ const { getTaskDetails, hashTasks } = requireNx('nx/src/hasher/hash-task');
250
+ const { getTaskSpecificEnv } = requireNx('nx/src/tasks-runner/task-env');
251
+ const { getCache } = requireNx('nx/src/tasks-runner/cache');
252
+ const { getRunnerOptions } = requireNx('nx/src/tasks-runner/run-command');
253
+ performance.mark('ensureBuilt:graph:start');
254
+ const { projectGraph } = await daemonClient.getProjectGraphAndSourceMaps();
255
+ requireProject(projectGraph, selector.project);
256
+ const taskGraph = createTaskGraph(projectGraph, {}, [selector.project], [selector.target], selector.configuration, overrides, false);
257
+ const tasks = Object.values(taskGraph.tasks);
258
+ performance.measure('ensureBuilt:graph', 'ensureBuilt:graph:start');
259
+ // `isCloudDefault: false` because these options are only read here by the
260
+ // hasher, which looks at `selectivelyHashTsConfig`; the cloud credentials the
261
+ // flag would add belong to the cloud runner, and the run path calls Nx's own
262
+ // `getRunner` to obtain them.
263
+ const runnerOptions = getRunnerOptions('default', nxJson, nxArgs, false);
264
+ const hasher = new DaemonBasedTaskHasher(daemonClient, runnerOptions);
265
+ performance.mark('ensureBuilt:hash:start');
266
+ // Every task, each against its own environment — per-project and per-target
267
+ // `.env` files and custom hashers that read env participate in the hash, so
268
+ // one shared environment would compute keys the CLI never wrote.
269
+ //
270
+ // `hashTasksThatDoNotDependOnOutputsOfOtherTasks` is the wrong helper here
271
+ // even though it is what Nx's runner warms up with: it deliberately skips
272
+ // tasks whose inputs include another task's outputs, leaving them unhashed
273
+ // for the orchestrator to hash once their dependencies finish. In a probe,
274
+ // "already built" means those outputs are already final, so hashing them now
275
+ // is both possible and exactly what the cache was keyed on. Skipping them
276
+ // instead would make every graph that uses `dependentTasksOutputFiles` — the
277
+ // normal shape for a multi-package build — permanently miss.
278
+ const perTaskEnvs = {};
279
+ for (const task of tasks) {
280
+ perTaskEnvs[task.id] = getTaskSpecificEnv(task, projectGraph);
281
+ }
282
+ await hashTasks(hasher, projectGraph, taskGraph, perTaskEnvs, getTaskDetails(), tasks);
283
+ performance.measure('ensureBuilt:hash', 'ensureBuilt:hash:start');
284
+ // Nx's own factory, but deliberately never `init()`ed: that is what makes
285
+ // this a local-only, side-effect-free question. `init()` attaches the remote
286
+ // cache — a network round-trip, and a download is precisely the work this
287
+ // probe exists to detect — and asserts that the cache directory matches the
288
+ // database. Neither matters here: a hit is only declared when the outputs on
289
+ // disk already match, so the cache directory is never read.
290
+ performance.mark('ensureBuilt:cache:start');
291
+ const cache = getCache(runnerOptions);
292
+ const cachedResults = await cache.getBatch(tasks.filter((task) => task.cache && task.hash));
293
+ const cachedCodeByHash = new Map();
294
+ for (const [hash, result] of cachedResults) {
295
+ cachedCodeByHash.set(hash, result.code);
296
+ }
297
+ const cacheMiss = firstCacheMiss(tasks, cachedCodeByHash);
298
+ performance.measure('ensureBuilt:cache', 'ensureBuilt:cache:start');
299
+ if (cacheMiss) {
300
+ return cacheMiss;
301
+ }
302
+ // A cache record only proves the task once succeeded with these inputs. The
303
+ // artifact this facility is about — the binary that is about to be exec'd —
304
+ // lives in the working tree, where anything may have deleted or rewritten it
305
+ // since. Only the daemon can settle that, because it holds the recorded
306
+ // output hashes.
307
+ const withOutputs = [];
308
+ const outputEntries = [];
309
+ for (const task of tasks) {
310
+ const hash = task.hash;
311
+ if (task.outputs.length === 0 || hash === undefined) {
312
+ continue;
313
+ }
314
+ withOutputs.push(task);
315
+ outputEntries.push({ outputs: task.outputs, hash });
316
+ }
317
+ performance.mark('ensureBuilt:outputs:start');
318
+ const matches = await daemonClient.outputsHashesMatchBatch(outputEntries);
319
+ performance.measure('ensureBuilt:outputs', 'ensureBuilt:outputs:start');
320
+ return firstStaleOutputs(withOutputs, matches);
321
+ }
322
+ async function runTarget(nxJson, nxArgs, overrides, selector, reason, requireNx) {
323
+ const { runCommandForTasks } = requireNx('nx/src/tasks-runner/run-command');
324
+ const { createProjectGraphAsync } = requireNx('nx/src/project-graph/project-graph');
325
+ const { signalToCode } = requireNx('nx/src/utils/exit-codes');
326
+ // `runCommandForTasks` derives its own task graph and hashes, so the probe's
327
+ // work is not reusable. That duplication is one daemon round-trip on a path
328
+ // that is about to run a build.
329
+ const projectGraph = await createProjectGraphAsync();
330
+ const { taskResults, completed } = await runCommandForTasks([requireProject(projectGraph, selector.project)], projectGraph, { nxJson }, nxArgs, overrides, selector.project, {}, { excludeTaskDependencies: false, loadDotEnvFiles: process.env.NX_LOAD_DOT_ENV_FILES !== 'false' });
331
+ if (!completed) {
332
+ // Nx's own encoding of an interrupted run: `runCommand` reports
333
+ // `signalToCode('SIGINT')` here. The runner does not surface which signal
334
+ // actually arrived, so there is none to forward — only the code Nx's CLI
335
+ // would have exited with.
336
+ return {
337
+ result: { disposition: 'failed', reason, exitCode: signalToCode('SIGINT'), signal: null },
338
+ taskResults,
339
+ };
340
+ }
341
+ for (const taskResult of Object.values(taskResults)) {
342
+ if (taskResult.status === 'failure' || taskResult.status === 'skipped') {
343
+ return { result: { disposition: 'failed', reason, exitCode: 1, signal: null }, taskResults };
344
+ }
345
+ }
346
+ return { result: { disposition: 'built', reason }, taskResults };
347
+ }
348
+ /**
349
+ * The daemon-disabled path: hand the target to the workspace's own `nx`, with
350
+ * stdio inherited.
351
+ *
352
+ * Inheriting rather than piping is the point. The wrapper this facility
353
+ * replaces piped Nx's output so it could read a cache marker out of the log and
354
+ * stay silent on a hit — a text heuristic over ANSI-coloured, format-unstable
355
+ * output. Without a daemon there is nothing to be silent about: no cheap probe
356
+ * exists, so the run is unconditional, the output is the run's own, and the
357
+ * child's exit status is forwarded verbatim.
358
+ */
359
+ async function runViaCli(workspaceRoot, selector) {
360
+ const nxCli = join(workspaceRoot, 'node_modules', '.bin', 'nx');
361
+ if (!existsSync(nxCli)) {
362
+ throw new Error(`ensureBuilt: the Nx daemon is disabled and ${nxCli} does not exist`);
363
+ }
364
+ const reason = { kind: 'no-daemon', taskId: `${selector.project}:${selector.target}` };
365
+ const targetSpec = selector.configuration
366
+ ? `${selector.project}:${selector.target}:${selector.configuration}`
367
+ : `${selector.project}:${selector.target}`;
368
+ const signalToCode = nxSignalToCode;
369
+ const child = spawn(nxCli, ['run', targetSpec, '--outputStyle=stream'], {
370
+ cwd: workspaceRoot,
371
+ stdio: 'inherit',
372
+ });
373
+ // `Promise.withResolvers` would read better but needs lib es2024; this
374
+ // package inherits lib es2022 from tsconfig.base.json.
375
+ const exit = await new Promise((settle, reject) => {
376
+ child.once('error', reject);
377
+ child.once('exit', (code, signal) => settle({ code, signal }));
378
+ });
379
+ return cliExitOutcome(reason, exit, signalToCode);
380
+ }
381
+ function nxSignalToCode(signal) {
382
+ switch (signal) {
383
+ case 'SIGHUP':
384
+ return 129;
385
+ case 'SIGINT':
386
+ return 130;
387
+ case 'SIGQUIT':
388
+ return 131;
389
+ case 'SIGTERM':
390
+ return 143;
391
+ default:
392
+ return 128;
393
+ }
394
+ }
395
+ /**
396
+ * How a child `nx`'s exit becomes a result.
397
+ *
398
+ * A signal is reported as a signal, not flattened into a code, so the caller
399
+ * can re-raise it: a build stopped by Ctrl-C should leave the wrapper looking
400
+ * killed by Ctrl-C to whatever is watching, not merely unsuccessful. The
401
+ * numeric code comes from Nx's own `signalToCode` so it matches what `nx run`
402
+ * would have exited with.
403
+ */
404
+ export function cliExitOutcome(reason, exit, signalToCode) {
405
+ if (exit.signal !== null) {
406
+ return { disposition: 'failed', reason, exitCode: signalToCode(exit.signal), signal: exit.signal };
407
+ }
408
+ if (exit.code !== 0) {
409
+ return { disposition: 'failed', reason, exitCode: exit.code ?? 1, signal: null };
410
+ }
411
+ return { disposition: 'built', reason };
412
+ }
413
+ function requireProject(projectGraph, project) {
414
+ const node = projectGraph.nodes[project];
415
+ if (!node) {
416
+ throw new Error(`ensureBuilt: no project named '${project}' in this workspace`);
417
+ }
418
+ return node;
419
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/typescript-emit/executor.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD,UAAU,qBAAqB;IAC7B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,UAAU,oBAAoB;IAC5B,OAAO,EAAE,OAAO,CAAC;CAClB;AAMD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,cAAc,GAAG,CAAC,UAAU,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAElF,MAAM,CAAC,OAAO,UAAU,sBAAsB,CAC5C,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,oBAAoB,CAAC,CAE/B;AAED,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,qBAAqB,EAC9B,MAAM,EAAE,cAAc,GACrB,OAAO,CAAC,oBAAoB,CAAC,CAqC/B"}
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/typescript-emit/executor.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD,UAAU,qBAAqB;IAC7B,IAAI,EAAE,MAAM,CAAC;CACd;AAED,UAAU,oBAAoB;IAC5B,OAAO,EAAE,OAAO,CAAC;CAClB;AAMD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,MAAM,cAAc,GAAG,CAAC,UAAU,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAElF,MAAM,CAAC,OAAO,UAAU,sBAAsB,CAC5C,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,oBAAoB,CAAC,CAE/B;AAED,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,qBAAqB,EAC9B,MAAM,EAAE,cAAc,GACrB,OAAO,CAAC,oBAAoB,CAAC,CAuC/B"}
@@ -1,8 +1,8 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { once } from 'node:events';
4
- import { rm, writeFile } from 'node:fs/promises';
5
- import { basename, dirname, isAbsolute, join } from 'node:path';
4
+ import { chmod, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
6
  import { readJsonFile } from 'nx/src/devkit-exports.js';
7
7
  export default function typescriptEmitExecutor(options, context) {
8
8
  return runTypeScriptEmit(options, context, runCompiler);
@@ -33,6 +33,7 @@ export async function runTypeScriptEmit(options, context, runner) {
33
33
  if (!javascriptSucceeded) {
34
34
  return { success: false };
35
35
  }
36
+ await makePackageBinsExecutable(cwd, options.executableOutputs ?? []);
36
37
  const declarationsSucceeded = await runner({
37
38
  command: 'tsc',
38
39
  args: ['-p', overlayPath, '--emitDeclarationOnly', '--declaration', '--declarationMap'],
@@ -44,6 +45,23 @@ export async function runTypeScriptEmit(options, context, runner) {
44
45
  await rm(overlayPath, { force: true });
45
46
  }
46
47
  }
48
+ async function makePackageBinsExecutable(cwd, outputs) {
49
+ for (const output of new Set(outputs)) {
50
+ const outputPath = resolve(cwd, output);
51
+ const projectRelative = relative(cwd, outputPath);
52
+ if (projectRelative.length === 0 ||
53
+ projectRelative === '..' ||
54
+ projectRelative.startsWith(`..${sep}`) ||
55
+ isAbsolute(projectRelative)) {
56
+ throw new Error(`Executable output must stay inside the project: ${output}`);
57
+ }
58
+ const outputStat = await stat(outputPath);
59
+ // TypeScript creates emitted files with the process default mode. A package
60
+ // bin that loses its execute bits is present but unusable through
61
+ // node_modules/.bin, so restore the semantic guarantee declared by `bin`.
62
+ await chmod(outputPath, outputStat.mode | 0o111);
63
+ }
64
+ }
47
65
  async function runCompiler(invocation) {
48
66
  const child = spawn(invocation.command, invocation.args, {
49
67
  cwd: invocation.cwd,
@@ -1,4 +1,5 @@
1
1
  export interface TypeScriptEmitOptions {
2
+ executableOutputs?: string[];
2
3
  cwd: string;
3
4
  tsConfig: string;
4
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/executors/typescript-emit/schema.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;CAClB"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../../src/executors/typescript-emit/schema.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IACpC,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,aAAa,EAGnB,MAAM,0BAA0B,CAAC;AAKlC,OAAO,EACL,yBAAyB,EAQ1B,MAAM,sBAAsB,CAAC;AAY9B,OAAO,EAAE,yBAAyB,EAAE,CAAC;AAUrC,KAAK,gBAAgB,GAAG,OAAO,GAAG,KAAK,CAAC;AACxC,KAAK,gBAAgB,GAAG,OAAO,GAAG,OAAO,CAAC;AAE1C,UAAU,YAAY;IACpB,YAAY,EAAE,gBAAgB,CAAC;IAC/B,YAAY,EAAE,gBAAgB,CAAC;CAChC;AAmED,UAAU,oBAAqB,SAAQ,YAAY;IACjD,UAAU,EAAE,MAAM,CAAC;CACpB;AA0CD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,oBAAoB,GAAG,MAAM,CAEhF;AAoMD,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,GAAG,aAAa,CAEvG;AAED,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,aAAa,EAGnB,MAAM,0BAA0B,CAAC;AAKlC,OAAO,EAGL,yBAAyB,EAQ1B,MAAM,sBAAsB,CAAC;AAY9B,OAAO,EAAE,yBAAyB,EAAE,CAAC;AAUrC,KAAK,gBAAgB,GAAG,OAAO,GAAG,KAAK,CAAC;AACxC,KAAK,gBAAgB,GAAG,OAAO,GAAG,OAAO,CAAC;AAE1C,UAAU,YAAY;IACpB,YAAY,EAAE,gBAAgB,CAAC;IAC/B,YAAY,EAAE,gBAAgB,CAAC;CAChC;AA6ED,UAAU,oBAAqB,SAAQ,YAAY;IACjD,UAAU,EAAE,MAAM,CAAC;CACpB;AA0CD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,oBAAoB,GAAG,MAAM,CAEhF;AAyND,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,GAAG,aAAa,CAEvG;AAED,eAAO,MAAM,aAAa,EAAE,aAG3B,CAAC"}