isolate-package 1.3.2 → 1.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,964 @@
1
+ // src/isolate.ts
2
+ import fs15 from "fs-extra";
3
+ import assert6 from "node:assert";
4
+ import path15 from "node:path";
5
+
6
+ // src/utils/filter-object-undefined.ts
7
+ function filterObjectUndefined(object) {
8
+ return Object.fromEntries(
9
+ Object.entries(object).filter(([_, value]) => value !== void 0)
10
+ );
11
+ }
12
+
13
+ // src/utils/get-dirname.ts
14
+ import { fileURLToPath } from "url";
15
+ function getDirname(importMetaUrl) {
16
+ return fileURLToPath(new URL(".", importMetaUrl));
17
+ }
18
+
19
+ // src/utils/get-error-message.ts
20
+ function getErrorMessage(error) {
21
+ return toErrorWithMessage(error).message;
22
+ }
23
+ function isErrorWithMessage(error) {
24
+ return typeof error === "object" && error !== null && "message" in error;
25
+ }
26
+ function toErrorWithMessage(maybeError) {
27
+ if (isErrorWithMessage(maybeError))
28
+ return maybeError;
29
+ try {
30
+ return new Error(JSON.stringify(maybeError));
31
+ } catch {
32
+ return new Error(String(maybeError));
33
+ }
34
+ }
35
+
36
+ // src/utils/get-relative-path.ts
37
+ function getRootRelativePath(path16, rootPath) {
38
+ const strippedPath = path16.replace(rootPath, "");
39
+ return strippedPath.startsWith("/") ? `(root)${strippedPath}` : `(root)/${strippedPath}`;
40
+ }
41
+ function getIsolateRelativePath(path16, isolatePath) {
42
+ const strippedPath = path16.replace(isolatePath, "");
43
+ return strippedPath.startsWith("/") ? `(isolate)${strippedPath}` : `(isolate)/${strippedPath}`;
44
+ }
45
+
46
+ // src/utils/inspect-value.ts
47
+ import { inspect } from "node:util";
48
+ function inspectValue(value) {
49
+ return inspect(value, false, 4, true);
50
+ }
51
+
52
+ // src/utils/is-present.ts
53
+ function isDefined(t) {
54
+ return t !== void 0;
55
+ }
56
+
57
+ // src/utils/json.ts
58
+ import fs from "fs-extra";
59
+ import stripJsonComments from "strip-json-comments";
60
+ function readTypedJsonSync(filePath) {
61
+ try {
62
+ const rawContent = fs.readFileSync(filePath, "utf-8");
63
+ const data = JSON.parse(stripJsonComments(rawContent));
64
+ return data;
65
+ } catch (err) {
66
+ throw new Error(
67
+ `Failed to read JSON from ${filePath}: ${getErrorMessage(err)}`
68
+ );
69
+ }
70
+ }
71
+ async function readTypedJson(filePath) {
72
+ try {
73
+ const rawContent = await fs.readFile(filePath, "utf-8");
74
+ const data = JSON.parse(rawContent);
75
+ return data;
76
+ } catch (err) {
77
+ throw new Error(
78
+ `Failed to read JSON from ${filePath}: ${getErrorMessage(err)}`
79
+ );
80
+ }
81
+ }
82
+
83
+ // src/utils/logger.ts
84
+ import chalk from "chalk";
85
+ var _loggerHandlers = {
86
+ debug(...args) {
87
+ console.log(chalk.blue("debug"), ...args);
88
+ },
89
+ info(...args) {
90
+ console.log(chalk.green("info"), ...args);
91
+ },
92
+ warn(...args) {
93
+ console.log(chalk.yellow("warning"), ...args);
94
+ },
95
+ error(...args) {
96
+ console.log(chalk.red("error"), ...args);
97
+ }
98
+ };
99
+ var _logger = {
100
+ debug(...args) {
101
+ if (_logLevel === "debug") {
102
+ _loggerHandlers.debug(...args);
103
+ }
104
+ },
105
+ info(...args) {
106
+ if (_logLevel === "debug" || _logLevel === "info") {
107
+ _loggerHandlers.info(...args);
108
+ }
109
+ },
110
+ warn(...args) {
111
+ if (_logLevel === "debug" || _logLevel === "info" || _logLevel === "warn") {
112
+ _loggerHandlers.warn(...args);
113
+ }
114
+ },
115
+ error(...args) {
116
+ _loggerHandlers.error(...args);
117
+ }
118
+ };
119
+ var _logLevel = "info";
120
+ function setLogger(logger) {
121
+ _loggerHandlers = logger;
122
+ return _logger;
123
+ }
124
+ function setLogLevel(logLevel) {
125
+ _logLevel = logLevel;
126
+ return _logger;
127
+ }
128
+ function useLogger() {
129
+ return _logger;
130
+ }
131
+
132
+ // src/utils/pack.ts
133
+ import fs2 from "fs-extra";
134
+ import { exec } from "node:child_process";
135
+ import path from "node:path";
136
+ async function pack(srcDir, dstDir, usePnpmPack = false) {
137
+ const execOptions = {
138
+ maxBuffer: 10 * 1024 * 1024
139
+ };
140
+ const log = useLogger();
141
+ const previousCwd = process.cwd();
142
+ process.chdir(srcDir);
143
+ const stdout = usePnpmPack ? await new Promise((resolve, reject) => {
144
+ exec(
145
+ `pnpm pack --pack-destination ${dstDir}`,
146
+ execOptions,
147
+ (err, stdout2, stderr) => {
148
+ if (err) {
149
+ log.error(stderr);
150
+ return reject(err);
151
+ }
152
+ resolve(stdout2);
153
+ }
154
+ );
155
+ }) : await new Promise((resolve, reject) => {
156
+ exec(
157
+ `npm pack --pack-destination ${dstDir}`,
158
+ execOptions,
159
+ (err, stdout2) => {
160
+ if (err) {
161
+ return reject(err);
162
+ }
163
+ resolve(stdout2);
164
+ }
165
+ );
166
+ });
167
+ const fileName = path.basename(stdout.trim());
168
+ const filePath = path.join(dstDir, fileName);
169
+ if (!fs2.existsSync(filePath)) {
170
+ log.error(
171
+ `The response from pack could not be resolved to an existing file: ${filePath}`
172
+ );
173
+ } else {
174
+ log.debug(`Packed (temp)/${fileName}`);
175
+ }
176
+ process.chdir(previousCwd);
177
+ return filePath;
178
+ }
179
+
180
+ // src/utils/unpack.ts
181
+ import fs3 from "fs-extra";
182
+ import tar from "tar-fs";
183
+ import { createGunzip } from "zlib";
184
+ async function unpack(filePath, unpackDir) {
185
+ await new Promise((resolve, reject) => {
186
+ fs3.createReadStream(filePath).pipe(createGunzip()).pipe(tar.extract(unpackDir)).on("finish", () => resolve()).on("error", (err) => reject(err));
187
+ });
188
+ }
189
+
190
+ // src/utils/yaml.ts
191
+ import fs4 from "fs-extra";
192
+ import yaml from "yaml";
193
+ function readTypedYamlSync(filePath) {
194
+ try {
195
+ const rawContent = fs4.readFileSync(filePath, "utf-8");
196
+ const data = yaml.parse(rawContent);
197
+ return data;
198
+ } catch (err) {
199
+ throw new Error(
200
+ `Failed to read YAML from ${filePath}: ${getErrorMessage(err)}`
201
+ );
202
+ }
203
+ }
204
+
205
+ // src/helpers/adapt-internal-package-manifests.ts
206
+ import fs9 from "fs-extra";
207
+ import { omit as omit2 } from "lodash-es";
208
+ import path8 from "node:path";
209
+
210
+ // src/helpers/adapt-manifest-internal-deps.ts
211
+ import { omit } from "lodash-es";
212
+
213
+ // src/helpers/patch-internal-entries.ts
214
+ import path2 from "node:path";
215
+ function patchInternalEntries(dependencies, packagesRegistry, parentRootRelativeDir) {
216
+ const log = useLogger();
217
+ const allWorkspacePackageNames = Object.keys(packagesRegistry);
218
+ return Object.fromEntries(
219
+ Object.entries(dependencies).map(([key, value]) => {
220
+ if (allWorkspacePackageNames.includes(key)) {
221
+ const def = packagesRegistry[key];
222
+ const relativePath = parentRootRelativeDir ? path2.relative(parentRootRelativeDir, `./${def.rootRelativeDir}`) : `./${def.rootRelativeDir}`;
223
+ const linkPath = `file:${relativePath}`;
224
+ log.debug(`Linking dependency ${key} to ${linkPath}`);
225
+ return [key, linkPath];
226
+ } else {
227
+ return [key, value];
228
+ }
229
+ })
230
+ );
231
+ }
232
+
233
+ // src/helpers/adapt-manifest-internal-deps.ts
234
+ function adaptManifestInternalDeps({
235
+ manifest,
236
+ packagesRegistry,
237
+ parentRootRelativeDir
238
+ }, opts = {}) {
239
+ return Object.assign(
240
+ omit(manifest, ["devDependencies"]),
241
+ filterObjectUndefined({
242
+ dependencies: manifest.dependencies ? patchInternalEntries(
243
+ manifest.dependencies,
244
+ packagesRegistry,
245
+ parentRootRelativeDir
246
+ ) : void 0,
247
+ devDependencies: opts.includeDevDependencies && manifest.devDependencies ? patchInternalEntries(
248
+ manifest.devDependencies,
249
+ packagesRegistry,
250
+ parentRootRelativeDir
251
+ ) : void 0
252
+ })
253
+ );
254
+ }
255
+
256
+ // src/helpers/config.ts
257
+ import fs5 from "fs-extra";
258
+ import { isEmpty } from "lodash-es";
259
+ import assert from "node:assert";
260
+ import path3 from "node:path";
261
+ var configDefaults = {
262
+ buildDirName: void 0,
263
+ includeDevDependencies: false,
264
+ isolateDirName: "isolate",
265
+ logLevel: "info",
266
+ targetPackagePath: void 0,
267
+ tsconfigPath: "./tsconfig.json",
268
+ workspacePackages: void 0,
269
+ workspaceRoot: "../..",
270
+ excludeLockfile: false,
271
+ avoidPnpmPack: false
272
+ };
273
+ var _resolvedConfig;
274
+ var _user_defined_config;
275
+ var validConfigKeys = Object.keys(configDefaults);
276
+ var CONFIG_FILE_NAME = "isolate.config.json";
277
+ function setUserConfig(config) {
278
+ _user_defined_config = config;
279
+ if (config.logLevel) {
280
+ setLogLevel(config.logLevel);
281
+ }
282
+ }
283
+ function useConfig() {
284
+ if (_resolvedConfig) {
285
+ return _resolvedConfig;
286
+ } else {
287
+ throw new Error("Called useConfig before config was made available");
288
+ }
289
+ }
290
+ function resolveConfig() {
291
+ if (_resolvedConfig) {
292
+ return _resolvedConfig;
293
+ }
294
+ setLogLevel(process.env.DEBUG_ISOLATE_CONFIG ? "debug" : "info");
295
+ const log = useLogger();
296
+ const configFilePath = path3.join(process.cwd(), CONFIG_FILE_NAME);
297
+ if (_user_defined_config) {
298
+ log.debug(`Using user defined config:`, inspectValue(_user_defined_config));
299
+ } else {
300
+ log.debug(`Attempting to load config from ${configFilePath}`);
301
+ _user_defined_config = fs5.existsSync(configFilePath) ? readTypedJsonSync(configFilePath) : {};
302
+ }
303
+ const foreignKeys = Object.keys(_user_defined_config).filter(
304
+ (key) => !validConfigKeys.includes(key)
305
+ );
306
+ if (!isEmpty(foreignKeys)) {
307
+ log.warn(`Found invalid config settings:`, foreignKeys.join(", "));
308
+ }
309
+ const config = Object.assign(
310
+ {},
311
+ configDefaults,
312
+ _user_defined_config
313
+ );
314
+ log.debug("Using configuration:", inspectValue(config));
315
+ _resolvedConfig = config;
316
+ return config;
317
+ }
318
+ function getUserDefinedConfig() {
319
+ assert(
320
+ _user_defined_config,
321
+ "Called getUserDefinedConfig before user config was made available"
322
+ );
323
+ return _user_defined_config;
324
+ }
325
+
326
+ // src/helpers/detect-package-manager.ts
327
+ import fs8 from "fs-extra";
328
+ import assert3 from "node:assert";
329
+ import { execSync } from "node:child_process";
330
+ import path7 from "node:path";
331
+
332
+ // src/helpers/process-lockfile.ts
333
+ import fs7 from "fs-extra";
334
+ import { mapValues } from "lodash-es";
335
+ import path6 from "node:path";
336
+
337
+ // src/helpers/generate-npm-lockfile.ts
338
+ import Arborist from "@npmcli/arborist";
339
+ import fs6 from "node:fs/promises";
340
+ import path4 from "node:path";
341
+
342
+ // src/helpers/generate-pnpm-lockfile.ts
343
+ import {
344
+ getLockfileImporterId,
345
+ readWantedLockfile,
346
+ writeWantedLockfile
347
+ } from "@pnpm/lockfile-file";
348
+ import { pick } from "lodash-es";
349
+ import assert2 from "node:assert";
350
+ import path5 from "node:path";
351
+ async function generatePnpmLockfile({
352
+ workspaceRootDir,
353
+ targetPackageDir,
354
+ isolateDir,
355
+ internalDepPackageNames,
356
+ packagesRegistry
357
+ }) {
358
+ const { includeDevDependencies } = useConfig();
359
+ const log = useLogger();
360
+ log.debug("Generating PNPM lockfile");
361
+ const lockfile = await readWantedLockfile(workspaceRootDir, {
362
+ ignoreIncompatible: false
363
+ });
364
+ assert2(lockfile, "No lockfile found");
365
+ const targetImporterId = getLockfileImporterId(
366
+ workspaceRootDir,
367
+ targetPackageDir
368
+ );
369
+ const directoryByPackageName = Object.fromEntries(
370
+ internalDepPackageNames.map((name) => {
371
+ const pkg = packagesRegistry[name];
372
+ assert2(pkg, `Package ${name} not found in packages registry`);
373
+ return [name, pkg.rootRelativeDir];
374
+ })
375
+ );
376
+ const relevantImporterIds = [
377
+ targetImporterId,
378
+ /**
379
+ * The directory paths happen to correspond with what PNPM calls the
380
+ * importer ids in the context of a lockfile.
381
+ */
382
+ ...Object.values(directoryByPackageName)
383
+ ];
384
+ log.debug("Relevant importer ids:", relevantImporterIds);
385
+ lockfile.importers = Object.fromEntries(
386
+ Object.entries(pick(lockfile.importers, relevantImporterIds)).map(
387
+ ([importerId, importer]) => {
388
+ if (importerId === targetImporterId) {
389
+ log.debug("Setting target package importer on root");
390
+ return [
391
+ ".",
392
+ pnpmMapImporter(importer, {
393
+ includeDevDependencies,
394
+ directoryByPackageName
395
+ })
396
+ ];
397
+ }
398
+ log.debug("Setting internal package importer:", importerId);
399
+ return [
400
+ importerId,
401
+ pnpmMapImporter(importer, {
402
+ includeDevDependencies,
403
+ directoryByPackageName
404
+ })
405
+ ];
406
+ }
407
+ )
408
+ );
409
+ await writeWantedLockfile(isolateDir, lockfile);
410
+ log.debug("Created lockfile at", path5.join(isolateDir, "pnpm-lock.yaml"));
411
+ }
412
+
413
+ // src/helpers/process-lockfile.ts
414
+ function getLockfileFileName(name) {
415
+ switch (name) {
416
+ case "pnpm":
417
+ return "pnpm-lock.yaml";
418
+ case "yarn":
419
+ return "yarn.lock";
420
+ case "npm":
421
+ return "package-lock.json";
422
+ }
423
+ }
424
+ function pnpmMapImporter({ dependencies, devDependencies, ...rest }, {
425
+ includeDevDependencies,
426
+ directoryByPackageName
427
+ }) {
428
+ return {
429
+ dependencies: dependencies ? pnpmMapDependenciesLinks(dependencies, directoryByPackageName) : void 0,
430
+ devDependencies: includeDevDependencies && devDependencies ? pnpmMapDependenciesLinks(devDependencies, directoryByPackageName) : void 0,
431
+ ...rest
432
+ };
433
+ }
434
+ function pnpmMapDependenciesLinks(def, directoryByPackageName) {
435
+ return mapValues(
436
+ def,
437
+ (version, name) => version.startsWith("link:") ? `link:./${directoryByPackageName[name]}` : version
438
+ );
439
+ }
440
+ async function processLockfile({
441
+ workspaceRootDir,
442
+ packagesRegistry,
443
+ isolateDir,
444
+ internalDepPackageNames,
445
+ targetPackageDir,
446
+ targetPackageName
447
+ }) {
448
+ const log = useLogger();
449
+ const { name } = usePackageManager();
450
+ const fileName = getLockfileFileName(name);
451
+ const lockfileSrcPath = path6.join(workspaceRootDir, fileName);
452
+ const lockfileDstPath = path6.join(isolateDir, fileName);
453
+ switch (name) {
454
+ case "npm": {
455
+ const shrinkwrapSrcPath = path6.join(
456
+ workspaceRootDir,
457
+ "npm-shrinkwrap.json"
458
+ );
459
+ const shrinkwrapDstPath = path6.join(isolateDir, "npm-shrinkwrap.json");
460
+ if (fs7.existsSync(shrinkwrapSrcPath)) {
461
+ fs7.copyFileSync(shrinkwrapSrcPath, shrinkwrapDstPath);
462
+ log.debug("Copied shrinkwrap to", shrinkwrapDstPath);
463
+ } else {
464
+ fs7.copyFileSync(lockfileSrcPath, lockfileDstPath);
465
+ log.debug("Copied lockfile to", lockfileDstPath);
466
+ }
467
+ if (false) {
468
+ await generateNpmLockfile({
469
+ workspaceRootDir,
470
+ targetPackageName,
471
+ isolateDir,
472
+ packagesRegistry
473
+ });
474
+ }
475
+ break;
476
+ }
477
+ case "yarn": {
478
+ fs7.copyFileSync(lockfileSrcPath, lockfileDstPath);
479
+ log.debug("Copied lockfile to", lockfileDstPath);
480
+ break;
481
+ }
482
+ case "pnpm": {
483
+ await generatePnpmLockfile({
484
+ workspaceRootDir,
485
+ targetPackageDir,
486
+ isolateDir,
487
+ internalDepPackageNames,
488
+ packagesRegistry
489
+ });
490
+ break;
491
+ }
492
+ default:
493
+ log.warn(`Unexpected package manager ${name}`);
494
+ }
495
+ }
496
+
497
+ // src/helpers/detect-package-manager.ts
498
+ var supportedPackageManagerNames = ["pnpm", "yarn", "npm"];
499
+ var packageManager;
500
+ function detectPackageManager(workspaceRoot) {
501
+ packageManager = inferFromManifest(workspaceRoot) ?? inferFromFiles(workspaceRoot);
502
+ return packageManager;
503
+ }
504
+ function inferFromManifest(workspaceRoot) {
505
+ const log = useLogger();
506
+ const rootManifest = readTypedJsonSync(
507
+ path7.join(workspaceRoot, "package.json")
508
+ );
509
+ if (!rootManifest.packageManager) {
510
+ log.debug("No packageManager field found in root manifest");
511
+ return;
512
+ }
513
+ const [name, version = "*"] = rootManifest.packageManager.split("@");
514
+ assert3(
515
+ supportedPackageManagerNames.includes(name),
516
+ `Package manager "${name}" is not currently supported`
517
+ );
518
+ const lockfileName = getLockfileFileName(name);
519
+ assert3(
520
+ fs8.existsSync(path7.join(workspaceRoot, lockfileName)),
521
+ `Manifest declares ${name} to be the packageManager, but failed to find ${lockfileName} in workspace root`
522
+ );
523
+ return { name, version };
524
+ }
525
+ function inferFromFiles(workspaceRoot) {
526
+ for (const name of supportedPackageManagerNames) {
527
+ const lockfileName = getLockfileFileName(name);
528
+ if (fs8.existsSync(path7.join(workspaceRoot, lockfileName))) {
529
+ return { name, version: getVersion(name) };
530
+ }
531
+ }
532
+ if (fs8.existsSync(path7.join(workspaceRoot, "npm-shrinkwrap.json"))) {
533
+ return { name: "npm", version: getVersion("npm") };
534
+ }
535
+ throw new Error(`Failed to detect package manager`);
536
+ }
537
+ function getVersion(packageManagerName) {
538
+ const buffer = execSync(`${packageManagerName} --version`);
539
+ return buffer.toString().trim();
540
+ }
541
+ function usePackageManager() {
542
+ if (!packageManager) {
543
+ throw Error(
544
+ "No package manager detected. Make sure to call detectPackageManager() before usePackageManager()"
545
+ );
546
+ }
547
+ return packageManager;
548
+ }
549
+
550
+ // src/helpers/adapt-internal-package-manifests.ts
551
+ async function adaptInternalPackageManifests(internalPackageNames, packagesRegistry, isolateDir) {
552
+ const packageManager2 = usePackageManager();
553
+ const { includeDevDependencies } = useConfig();
554
+ await Promise.all(
555
+ internalPackageNames.map(async (packageName) => {
556
+ const { manifest, rootRelativeDir } = packagesRegistry[packageName];
557
+ const outputManifest = packageManager2.name === "pnpm" ? Object.assign(
558
+ /**
559
+ * For internal dependencies we want to omit the peerDependencies,
560
+ * because installing these is the responsibility of the consuming
561
+ * app / service, and otherwise the frozen lockfile install will
562
+ * error since the package file contains something that is not
563
+ * referenced in the lockfile.
564
+ */
565
+ omit2(manifest, ["devDependencies", "peerDependencies"]),
566
+ {
567
+ dependencies: manifest.dependencies,
568
+ devDependencies: includeDevDependencies ? manifest.devDependencies : void 0
569
+ }
570
+ ) : adaptManifestInternalDeps(
571
+ {
572
+ manifest,
573
+ packagesRegistry,
574
+ parentRootRelativeDir: rootRelativeDir
575
+ },
576
+ { includeDevDependencies }
577
+ );
578
+ await fs9.writeFile(
579
+ path8.join(isolateDir, rootRelativeDir, "package.json"),
580
+ JSON.stringify(outputManifest, null, 2)
581
+ );
582
+ })
583
+ );
584
+ }
585
+
586
+ // src/helpers/adapt-target-package-manifest.ts
587
+ import fs10 from "fs-extra";
588
+ import { omit as omit3 } from "lodash-es";
589
+ import path9 from "node:path";
590
+ async function adaptTargetPackageManifest(manifest, packagesRegistry, isolateDir) {
591
+ const packageManager2 = usePackageManager();
592
+ const { includeDevDependencies } = useConfig();
593
+ const outputManifest = packageManager2.name === "pnpm" ? Object.assign(omit3(manifest, ["devDependencies", "scripts"]), {
594
+ devDependencies: includeDevDependencies ? manifest.devDependencies : void 0
595
+ }) : adaptManifestInternalDeps(
596
+ {
597
+ manifest,
598
+ packagesRegistry
599
+ },
600
+ { includeDevDependencies }
601
+ );
602
+ await fs10.writeFile(
603
+ path9.join(isolateDir, "package.json"),
604
+ JSON.stringify(outputManifest, null, 2)
605
+ );
606
+ }
607
+
608
+ // src/helpers/create-packages-registry.ts
609
+ import fs11 from "fs-extra";
610
+ import { globSync } from "glob";
611
+ import path11 from "node:path";
612
+
613
+ // src/helpers/find-packages-globs.ts
614
+ import assert4 from "node:assert";
615
+ import path10 from "node:path";
616
+ function findPackagesGlobs(workspaceRootDir) {
617
+ const log = useLogger();
618
+ const packageManager2 = usePackageManager();
619
+ switch (packageManager2.name) {
620
+ case "pnpm": {
621
+ const { packages: globs } = readTypedYamlSync(
622
+ path10.join(workspaceRootDir, "pnpm-workspace.yaml")
623
+ );
624
+ log.debug("Detected pnpm packages globs:", inspectValue(globs));
625
+ return globs;
626
+ }
627
+ case "yarn":
628
+ case "npm": {
629
+ const workspaceRootManifestPath = path10.join(
630
+ workspaceRootDir,
631
+ "package.json"
632
+ );
633
+ const { workspaces } = readTypedJsonSync(
634
+ workspaceRootManifestPath
635
+ );
636
+ if (!workspaces) {
637
+ throw new Error(
638
+ `No workspaces field found in ${workspaceRootManifestPath}`
639
+ );
640
+ }
641
+ if (Array.isArray(workspaces)) {
642
+ return workspaces;
643
+ } else {
644
+ const workspacesObject = workspaces;
645
+ assert4(
646
+ workspacesObject.packages,
647
+ "workspaces.packages must be an array"
648
+ );
649
+ return workspacesObject.packages;
650
+ }
651
+ }
652
+ }
653
+ }
654
+
655
+ // src/helpers/create-packages-registry.ts
656
+ async function createPackagesRegistry(workspaceRootDir, workspacePackagesOverride) {
657
+ const log = useLogger();
658
+ if (workspacePackagesOverride) {
659
+ log.debug(
660
+ `Override workspace packages via config: ${workspacePackagesOverride}`
661
+ );
662
+ }
663
+ const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);
664
+ const cwd = process.cwd();
665
+ process.chdir(workspaceRootDir);
666
+ const allPackages = packagesGlobs.flatMap((glob) => globSync(glob)).filter((dir) => fs11.lstatSync(dir).isDirectory());
667
+ const registry = (await Promise.all(
668
+ allPackages.map(async (rootRelativeDir) => {
669
+ const manifestPath = path11.join(rootRelativeDir, "package.json");
670
+ if (!fs11.existsSync(manifestPath)) {
671
+ log.warn(
672
+ `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file`
673
+ );
674
+ return;
675
+ } else {
676
+ log.debug(`Registering package ./${rootRelativeDir}`);
677
+ const manifest = await readTypedJson(
678
+ path11.join(rootRelativeDir, "package.json")
679
+ );
680
+ return {
681
+ manifest,
682
+ rootRelativeDir,
683
+ absoluteDir: path11.join(workspaceRootDir, rootRelativeDir)
684
+ };
685
+ }
686
+ })
687
+ )).reduce((acc, info) => {
688
+ if (info) {
689
+ acc[info.manifest.name] = info;
690
+ }
691
+ return acc;
692
+ }, {});
693
+ process.chdir(cwd);
694
+ return registry;
695
+ }
696
+
697
+ // src/helpers/get-build-output-dir.ts
698
+ import fs12 from "fs-extra";
699
+ import path12 from "node:path";
700
+ import outdent from "outdent";
701
+ async function getBuildOutputDir(targetPackageDir) {
702
+ const config = useConfig();
703
+ const log = useLogger();
704
+ if (config.buildDirName) {
705
+ log.debug("Using buildDirName from config:", config.buildDirName);
706
+ return path12.join(targetPackageDir, config.buildDirName);
707
+ }
708
+ const tsconfigPath = path12.join(targetPackageDir, config.tsconfigPath);
709
+ if (fs12.existsSync(tsconfigPath)) {
710
+ log.debug("Found tsconfig at:", config.tsconfigPath);
711
+ const tsconfig = await readTypedJson(tsconfigPath);
712
+ const outDir = tsconfig.compilerOptions?.outDir;
713
+ if (outDir) {
714
+ return path12.join(targetPackageDir, outDir);
715
+ } else {
716
+ throw new Error(outdent`
717
+ Failed to find outDir in tsconfig. If you are executing isolate from the root of a monorepo you should specify the buildDirName in isolate.config.json.
718
+ `);
719
+ }
720
+ } else {
721
+ log.warn("Failed to find tsconfig at:", tsconfigPath);
722
+ throw new Error(outdent`
723
+ Failed to infer the build output directory from either the isolate config buildDirName or a Typescript config file. See the documentation on how to configure one of these options.
724
+ `);
725
+ }
726
+ }
727
+
728
+ // src/helpers/list-internal-packages.ts
729
+ import { uniq } from "lodash-es";
730
+ function listInternalPackages(manifest, packagesRegistry, { includeDevDependencies = false } = {}) {
731
+ const allWorkspacePackageNames = Object.keys(packagesRegistry);
732
+ const internalPackageNames = (includeDevDependencies ? [
733
+ ...Object.keys(manifest.dependencies ?? {}),
734
+ ...Object.keys(manifest.devDependencies ?? {})
735
+ ] : Object.keys(manifest.dependencies ?? {})).filter((name) => allWorkspacePackageNames.includes(name));
736
+ const nestedInternalPackageNames = internalPackageNames.flatMap(
737
+ (packageName) => listInternalPackages(
738
+ packagesRegistry[packageName].manifest,
739
+ packagesRegistry,
740
+ { includeDevDependencies }
741
+ )
742
+ );
743
+ return uniq(internalPackageNames.concat(nestedInternalPackageNames));
744
+ }
745
+
746
+ // src/helpers/pack-dependencies.ts
747
+ import assert5 from "node:assert";
748
+ async function packDependencies({
749
+ /** All packages found in the monorepo by workspaces declaration */
750
+ packagesRegistry,
751
+ /** The dependencies that appear to be internal packages */
752
+ internalPackageNames,
753
+ /**
754
+ * The directory where the isolated package and all its dependencies will end
755
+ * up. This is also the directory from where the package will be deployed. By
756
+ * default it is a subfolder in targetPackageDir called "isolate" but you can
757
+ * configure it.
758
+ */
759
+ packDestinationDir
760
+ }) {
761
+ const config = useConfig();
762
+ const log = useLogger();
763
+ const packedFileByName = {};
764
+ const { name, version } = usePackageManager();
765
+ const versionMajor = parseInt(version.split(".")[0], 10);
766
+ const usePnpmPack = !config.avoidPnpmPack && name === "pnpm" && versionMajor >= 8;
767
+ if (usePnpmPack) {
768
+ log.debug("Using PNPM pack instead of NPM pack");
769
+ }
770
+ for (const dependency of internalPackageNames) {
771
+ const def = packagesRegistry[dependency];
772
+ assert5(dependency, `Failed to find package definition for ${dependency}`);
773
+ const { name: name2 } = def.manifest;
774
+ if (packedFileByName[name2]) {
775
+ log.debug(`Skipping ${name2} because it has already been packed`);
776
+ continue;
777
+ }
778
+ packedFileByName[name2] = await pack(
779
+ def.absoluteDir,
780
+ packDestinationDir,
781
+ usePnpmPack
782
+ );
783
+ }
784
+ return packedFileByName;
785
+ }
786
+
787
+ // src/helpers/process-build-output-files.ts
788
+ import fs13 from "fs-extra";
789
+ import path13 from "node:path";
790
+ var TIMEOUT_MS = 5e3;
791
+ async function processBuildOutputFiles({
792
+ targetPackageDir,
793
+ tmpDir,
794
+ isolateDir
795
+ }) {
796
+ const log = useLogger();
797
+ const packedFilePath = await pack(targetPackageDir, tmpDir);
798
+ const unpackDir = path13.join(tmpDir, "target");
799
+ const now = Date.now();
800
+ let isWaitingYet = false;
801
+ while (!fs13.existsSync(packedFilePath) && Date.now() - now < TIMEOUT_MS) {
802
+ if (!isWaitingYet) {
803
+ log.debug(`Waiting for ${packedFilePath} to become available...`);
804
+ }
805
+ isWaitingYet = true;
806
+ await new Promise((resolve) => setTimeout(resolve, 100));
807
+ }
808
+ await unpack(packedFilePath, unpackDir);
809
+ await fs13.copy(path13.join(unpackDir, "package"), isolateDir);
810
+ }
811
+
812
+ // src/helpers/unpack-dependencies.ts
813
+ import fs14 from "fs-extra";
814
+ import path14, { join } from "node:path";
815
+ async function unpackDependencies(packedFilesByName, packagesRegistry, tmpDir, isolateDir) {
816
+ const log = useLogger();
817
+ await Promise.all(
818
+ Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {
819
+ const dir = packagesRegistry[packageName].rootRelativeDir;
820
+ const unpackDir = join(tmpDir, dir);
821
+ log.debug("Unpacking", `(temp)/${path14.basename(filePath)}`);
822
+ await unpack(filePath, unpackDir);
823
+ const destinationDir = join(isolateDir, dir);
824
+ await fs14.ensureDir(destinationDir);
825
+ await fs14.move(join(unpackDir, "package"), destinationDir, {
826
+ overwrite: true
827
+ });
828
+ log.debug(
829
+ `Moved package files to ${getIsolateRelativePath(
830
+ destinationDir,
831
+ isolateDir
832
+ )}`
833
+ );
834
+ })
835
+ );
836
+ }
837
+
838
+ // src/isolate.ts
839
+ var __dirname = getDirname(import.meta.url);
840
+ async function isolate(options = {}) {
841
+ if (options.logger) {
842
+ setLogger(options.logger);
843
+ }
844
+ if (options.config) {
845
+ setUserConfig(options.config);
846
+ }
847
+ const config = resolveConfig();
848
+ setLogLevel(config.logLevel);
849
+ const log = useLogger();
850
+ const thisPackageManifest = await readTypedJson(
851
+ path15.join(path15.join(__dirname, "..", "package.json"))
852
+ );
853
+ log.debug("Using isolate-package version", thisPackageManifest.version);
854
+ const targetPackageDir = config.targetPackagePath ? path15.join(process.cwd(), config.targetPackagePath) : process.cwd();
855
+ const workspaceRootDir = config.targetPackagePath ? process.cwd() : path15.join(targetPackageDir, config.workspaceRoot);
856
+ const buildOutputDir = await getBuildOutputDir(targetPackageDir);
857
+ assert6(
858
+ fs15.existsSync(buildOutputDir),
859
+ `Failed to find build output path at ${buildOutputDir}. Please make sure you build the source before isolating it.`
860
+ );
861
+ log.debug("Workspace root resolved to", workspaceRootDir);
862
+ log.debug(
863
+ "Isolate target package",
864
+ getRootRelativePath(targetPackageDir, workspaceRootDir)
865
+ );
866
+ const isolateDir = path15.join(targetPackageDir, config.isolateDirName);
867
+ log.debug(
868
+ "Isolate output directory",
869
+ getRootRelativePath(isolateDir, workspaceRootDir)
870
+ );
871
+ if (fs15.existsSync(isolateDir)) {
872
+ await fs15.remove(isolateDir);
873
+ log.debug("Cleaned the existing isolate output directory");
874
+ }
875
+ await fs15.ensureDir(isolateDir);
876
+ const tmpDir = path15.join(isolateDir, "__tmp");
877
+ await fs15.ensureDir(tmpDir);
878
+ const targetPackageManifest = await readTypedJson(
879
+ path15.join(targetPackageDir, "package.json")
880
+ );
881
+ const packageManager2 = detectPackageManager(workspaceRootDir);
882
+ log.debug(
883
+ "Detected package manager",
884
+ packageManager2.name,
885
+ packageManager2.version
886
+ );
887
+ const packagesRegistry = await createPackagesRegistry(
888
+ workspaceRootDir,
889
+ config.workspacePackages
890
+ );
891
+ const internalPackageNames = listInternalPackages(
892
+ targetPackageManifest,
893
+ packagesRegistry,
894
+ {
895
+ includeDevDependencies: config.includeDevDependencies
896
+ }
897
+ );
898
+ const packedFilesByName = await packDependencies({
899
+ internalPackageNames,
900
+ packagesRegistry,
901
+ packDestinationDir: tmpDir
902
+ });
903
+ await unpackDependencies(
904
+ packedFilesByName,
905
+ packagesRegistry,
906
+ tmpDir,
907
+ isolateDir
908
+ );
909
+ await adaptInternalPackageManifests(
910
+ internalPackageNames,
911
+ packagesRegistry,
912
+ isolateDir
913
+ );
914
+ await processBuildOutputFiles({
915
+ targetPackageDir,
916
+ tmpDir,
917
+ isolateDir
918
+ });
919
+ await adaptTargetPackageManifest(
920
+ targetPackageManifest,
921
+ packagesRegistry,
922
+ isolateDir
923
+ );
924
+ const userDefinedConfig = getUserDefinedConfig();
925
+ if (!isDefined(userDefinedConfig.excludeLockfile)) {
926
+ if (packageManager2.name === "npm" || packageManager2.name === "yarn") {
927
+ config.excludeLockfile = true;
928
+ }
929
+ }
930
+ if (config.excludeLockfile) {
931
+ log.warn("Excluding the lockfile from the isolate output");
932
+ } else {
933
+ await processLockfile({
934
+ workspaceRootDir,
935
+ isolateDir,
936
+ packagesRegistry,
937
+ internalDepPackageNames: internalPackageNames,
938
+ targetPackageDir,
939
+ targetPackageName: targetPackageManifest.name
940
+ });
941
+ }
942
+ if (packageManager2.name === "pnpm") {
943
+ fs15.copyFileSync(
944
+ path15.join(workspaceRootDir, "pnpm-workspace.yaml"),
945
+ path15.join(isolateDir, "pnpm-workspace.yaml")
946
+ );
947
+ }
948
+ const npmrcPath = path15.join(workspaceRootDir, ".npmrc");
949
+ if (fs15.existsSync(npmrcPath)) {
950
+ fs15.copyFileSync(npmrcPath, path15.join(isolateDir, ".npmrc"));
951
+ log.debug("Copied .npmrc file to the isolate output");
952
+ }
953
+ log.debug(
954
+ "Deleting temp directory",
955
+ getRootRelativePath(tmpDir, workspaceRootDir)
956
+ );
957
+ await fs15.remove(tmpDir);
958
+ log.info("Isolate completed at", isolateDir);
959
+ }
960
+
961
+ export {
962
+ isolate
963
+ };
964
+ //# sourceMappingURL=chunk-PXDYN4JI.mjs.map