isolate-package 1.3.3 → 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.
package/dist/index.mjs CHANGED
@@ -1,760 +1,7 @@
1
- #!/usr/bin/env node
2
-
3
- // src/index.ts
4
- import fs14 from "fs-extra";
5
- import assert5 from "node:assert";
6
- import path14 from "node:path";
7
- import sourceMaps from "source-map-support";
8
-
9
- // src/helpers/adapt-manifest-files.ts
10
- import fs from "fs-extra";
11
- import path from "node:path";
12
- async function adaptManifestFiles(localDependencies, packagesRegistry, isolateDir) {
13
- await Promise.all(
14
- localDependencies.map(async (packageName) => {
15
- const { manifest, rootRelativeDir } = packagesRegistry[packageName];
16
- const outputManifest = adaptManifestWorkspaceDeps(
17
- { manifest, packagesRegistry, parentRootRelativeDir: rootRelativeDir },
18
- { includeDevDependencies: getConfig().includeDevDependencies }
19
- );
20
- await fs.writeFile(
21
- path.join(isolateDir, rootRelativeDir, "package.json"),
22
- JSON.stringify(outputManifest, null, 2)
23
- );
24
- })
25
- );
26
- }
27
-
28
- // src/helpers/adapt-manifest-workspace-deps.ts
29
- import { omit } from "lodash-es";
30
-
31
- // src/utils/filter-object-undefined.ts
32
- function filterObjectUndefined(object) {
33
- return Object.fromEntries(
34
- Object.entries(object).filter(([_, value]) => value !== void 0)
35
- );
36
- }
37
-
38
- // src/utils/get-dirname.ts
39
- import { fileURLToPath } from "url";
40
- function getDirname(importMetaUrl) {
41
- return fileURLToPath(new URL(".", importMetaUrl));
42
- }
43
-
44
- // src/utils/get-error-message.ts
45
- function getErrorMessage(error) {
46
- return toErrorWithMessage(error).message;
47
- }
48
- function isErrorWithMessage(error) {
49
- return typeof error === "object" && error !== null && "message" in error;
50
- }
51
- function toErrorWithMessage(maybeError) {
52
- if (isErrorWithMessage(maybeError))
53
- return maybeError;
54
- try {
55
- return new Error(JSON.stringify(maybeError));
56
- } catch {
57
- return new Error(String(maybeError));
58
- }
59
- }
60
-
61
- // src/utils/get-relative-path.ts
62
- function getRootRelativePath(path15, rootPath) {
63
- const strippedPath = path15.replace(rootPath, "");
64
- return strippedPath.startsWith("/") ? `(root)${strippedPath}` : `(root)/${strippedPath}`;
65
- }
66
- function getIsolateRelativePath(path15, isolatePath) {
67
- const strippedPath = path15.replace(isolatePath, "");
68
- return strippedPath.startsWith("/") ? `(isolate)${strippedPath}` : `(isolate)/${strippedPath}`;
69
- }
70
-
71
- // src/utils/inspect-value.ts
72
- import { inspect } from "node:util";
73
- function inspectValue(value) {
74
- return inspect(value, false, 4, true);
75
- }
76
-
77
- // src/utils/json.ts
78
- import fs2 from "fs-extra";
79
- import stripJsonComments from "strip-json-comments";
80
- function readTypedJsonSync(filePath) {
81
- try {
82
- const rawContent = fs2.readFileSync(filePath, "utf-8");
83
- const data = JSON.parse(stripJsonComments(rawContent));
84
- return data;
85
- } catch (err) {
86
- throw new Error(
87
- `Failed to read JSON from ${filePath}: ${getErrorMessage(err)}`
88
- );
89
- }
90
- }
91
- async function readTypedJson(filePath) {
92
- try {
93
- const rawContent = await fs2.readFile(filePath, "utf-8");
94
- const data = JSON.parse(rawContent);
95
- return data;
96
- } catch (err) {
97
- throw new Error(
98
- `Failed to read JSON from ${filePath}: ${getErrorMessage(err)}`
99
- );
100
- }
101
- }
102
-
103
- // src/utils/logger.ts
104
- import chalk from "chalk";
105
- function createLogger(logLevel) {
106
- return {
107
- debug(...args) {
108
- if (logLevel === "debug") {
109
- console.log(chalk.blue("debug"), ...args);
110
- }
111
- },
112
- info(...args) {
113
- if (logLevel === "debug" || logLevel === "info") {
114
- console.log(chalk.green("info"), ...args);
115
- }
116
- },
117
- warn(...args) {
118
- if (logLevel === "debug" || logLevel === "info" || logLevel === "warn") {
119
- console.log(chalk.yellow("warning"), ...args);
120
- }
121
- },
122
- error(...args) {
123
- console.log(chalk.red("error"), ...args);
124
- }
125
- };
126
- }
127
-
128
- // src/utils/pack.ts
129
- import fs3 from "fs-extra";
130
- import { exec } from "node:child_process";
131
- import path2 from "node:path";
132
- async function pack(srcDir, dstDir, usePnpmPack = false) {
133
- const execOptions = {
134
- maxBuffer: 10 * 1024 * 1024
135
- };
136
- const log2 = createLogger(getConfig().logLevel);
137
- const previousCwd = process.cwd();
138
- process.chdir(srcDir);
139
- const stdout = usePnpmPack ? await new Promise((resolve, reject) => {
140
- exec(
141
- `pnpm pack --pack-destination ${dstDir}`,
142
- execOptions,
143
- (err, stdout2, stderr) => {
144
- if (err) {
145
- log2.error(stderr);
146
- return reject(err);
147
- }
148
- resolve(stdout2);
149
- }
150
- );
151
- }) : await new Promise((resolve, reject) => {
152
- exec(
153
- `npm pack --pack-destination ${dstDir}`,
154
- execOptions,
155
- (err, stdout2) => {
156
- if (err) {
157
- return reject(err);
158
- }
159
- resolve(stdout2);
160
- }
161
- );
162
- });
163
- const fileName = path2.basename(stdout.trim());
164
- const filePath = path2.join(dstDir, fileName);
165
- if (!fs3.existsSync(filePath)) {
166
- log2.error(
167
- `The response from pack could not be resolved to an existing file: ${filePath}`
168
- );
169
- } else {
170
- log2.debug(`Packed (temp)/${fileName}`);
171
- }
172
- process.chdir(previousCwd);
173
- return filePath;
174
- }
175
-
176
- // src/utils/unpack.ts
177
- import fs4 from "fs-extra";
178
- import tar from "tar-fs";
179
- import { createGunzip } from "zlib";
180
- async function unpack(filePath, unpackDir) {
181
- await new Promise((resolve, reject) => {
182
- fs4.createReadStream(filePath).pipe(createGunzip()).pipe(tar.extract(unpackDir)).on("finish", () => resolve()).on("error", (err) => reject(err));
183
- });
184
- }
185
-
186
- // src/utils/yaml.ts
187
- import fs5 from "fs-extra";
188
- import yaml from "yaml";
189
- function readTypedYamlSync(filePath) {
190
- try {
191
- const rawContent = fs5.readFileSync(filePath, "utf-8");
192
- const data = yaml.parse(rawContent);
193
- return data;
194
- } catch (err) {
195
- throw new Error(
196
- `Failed to read YAML from ${filePath}: ${getErrorMessage(err)}`
197
- );
198
- }
199
- }
200
- function writeTypedYamlSync(filePath, content) {
201
- fs5.writeFileSync(filePath, yaml.stringify(content), "utf-8");
202
- }
203
-
204
- // src/helpers/adapt-manifest-workspace-deps.ts
205
- function adaptManifestWorkspaceDeps({
206
- manifest,
207
- packagesRegistry,
208
- parentRootRelativeDir
209
- }, opts = {}) {
210
- return Object.assign(
211
- omit(manifest, ["devDependencies"]),
212
- filterObjectUndefined({
213
- dependencies: manifest.dependencies ? patchWorkspaceEntries(
214
- manifest.dependencies,
215
- packagesRegistry,
216
- parentRootRelativeDir
217
- ) : void 0,
218
- devDependencies: opts.includeDevDependencies && manifest.devDependencies ? patchWorkspaceEntries(
219
- manifest.devDependencies,
220
- packagesRegistry,
221
- parentRootRelativeDir
222
- ) : void 0
223
- })
224
- );
225
- }
226
-
227
- // src/helpers/adapt-target-package-manifest.ts
228
- import fs6 from "fs-extra";
229
- import path3 from "node:path";
230
- async function adaptTargetPackageManifest(manifest, packagesRegistry, isolateDir) {
231
- const outputManifest = adaptManifestWorkspaceDeps(
232
- {
233
- manifest,
234
- packagesRegistry
235
- },
236
- { includeDevDependencies: getConfig().includeDevDependencies }
237
- );
238
- await fs6.writeFile(
239
- path3.join(isolateDir, "package.json"),
240
- JSON.stringify(outputManifest, null, 2)
241
- );
242
- }
243
-
244
- // src/helpers/config.ts
245
- import fs7 from "fs-extra";
246
- import { isEmpty } from "lodash-es";
247
- import path4 from "node:path";
248
- var configDefaults = {
249
- buildDirName: void 0,
250
- includeDevDependencies: false,
251
- isolateDirName: "isolate",
252
- logLevel: "info",
253
- targetPackagePath: void 0,
254
- tsconfigPath: "./tsconfig.json",
255
- workspacePackages: void 0,
256
- workspaceRoot: "../..",
257
- excludeLockfile: false,
258
- avoidPnpmPack: false
1
+ import {
2
+ isolate
3
+ } from "./chunk-PXDYN4JI.mjs";
4
+ export {
5
+ isolate
259
6
  };
260
- var __config;
261
- var validConfigKeys = Object.keys(configDefaults);
262
- var CONFIG_FILE_NAME = "isolate.config.json";
263
- function getConfig() {
264
- if (__config) {
265
- return __config;
266
- }
267
- const log2 = createLogger(
268
- process.env.ISOLATE_CONFIG_LOG_LEVEL ?? "warn"
269
- );
270
- const configFilePath = path4.join(process.cwd(), CONFIG_FILE_NAME);
271
- log2.debug(`Attempting to load config from ${configFilePath}`);
272
- const configFromFile = fs7.existsSync(configFilePath) ? readTypedJsonSync(configFilePath) : {};
273
- const foreignKeys = Object.keys(configFromFile).filter(
274
- (key) => !validConfigKeys.includes(key)
275
- );
276
- if (!isEmpty(foreignKeys)) {
277
- log2.warn(`Found invalid config settings:`, foreignKeys.join(", "));
278
- }
279
- const config2 = Object.assign(
280
- {},
281
- configDefaults,
282
- configFromFile
283
- );
284
- log2.debug("Using configuration:", inspectValue(config2));
285
- __config = config2;
286
- return config2;
287
- }
288
-
289
- // src/helpers/create-packages-registry.ts
290
- import fs10 from "fs-extra";
291
- import { globSync } from "glob";
292
- import path8 from "node:path";
293
-
294
- // src/helpers/find-packages-globs.ts
295
- import assert3 from "node:assert";
296
- import path7 from "node:path";
297
-
298
- // src/helpers/detect-package-manager.ts
299
- import fs9 from "fs-extra";
300
- import assert2 from "node:assert";
301
- import { execSync } from "node:child_process";
302
- import path6 from "node:path";
303
-
304
- // src/helpers/process-lockfile.ts
305
- import fs8 from "fs-extra";
306
- import assert from "node:assert";
307
- import path5 from "node:path";
308
- function getLockfileFileName(name) {
309
- switch (name) {
310
- case "pnpm":
311
- return "pnpm-lock.yaml";
312
- case "yarn":
313
- return "yarn.lock";
314
- case "npm":
315
- return "package-lock.json";
316
- }
317
- }
318
- function processLockfile({
319
- workspaceRootDir,
320
- targetPackageName,
321
- packagesRegistry,
322
- isolateDir
323
- }) {
324
- const log2 = createLogger(getConfig().logLevel);
325
- const targetPackageRelativeDir = packagesRegistry[targetPackageName].rootRelativeDir;
326
- const { name } = usePackageManager();
327
- const fileName = getLockfileFileName(name);
328
- const lockfileSrcPath = path5.join(workspaceRootDir, fileName);
329
- const lockfileDstPath = path5.join(isolateDir, fileName);
330
- switch (name) {
331
- case "npm": {
332
- const shrinkwrapSrcPath = path5.join(
333
- workspaceRootDir,
334
- "npm-shrinkwrap.json"
335
- );
336
- const shrinkwrapDstPath = path5.join(isolateDir, "npm-shrinkwrap.json");
337
- if (fs8.existsSync(shrinkwrapSrcPath)) {
338
- fs8.copyFileSync(shrinkwrapSrcPath, shrinkwrapDstPath);
339
- log2.debug("Copied shrinkwrap to", shrinkwrapDstPath);
340
- } else {
341
- fs8.copyFileSync(lockfileSrcPath, lockfileDstPath);
342
- log2.debug("Copied lockfile to", lockfileDstPath);
343
- }
344
- return;
345
- }
346
- case "yarn": {
347
- fs8.copyFileSync(lockfileSrcPath, lockfileDstPath);
348
- log2.debug("Copied lockfile to", lockfileDstPath);
349
- return;
350
- }
351
- case "pnpm": {
352
- const origLockfile = readTypedYamlSync(lockfileSrcPath);
353
- log2.debug("Read PNPM lockfile, version:", origLockfile.lockfileVersion);
354
- const adaptedLockfile = structuredClone(origLockfile);
355
- const targetPackageDef = adaptedLockfile.importers[targetPackageRelativeDir];
356
- assert(
357
- targetPackageDef,
358
- `Failed to find target package in lockfile at importers[${targetPackageRelativeDir}]`
359
- );
360
- adaptedLockfile.importers["."] = targetPackageDef;
361
- delete adaptedLockfile.importers[targetPackageRelativeDir];
362
- writeTypedYamlSync(lockfileDstPath, adaptedLockfile);
363
- log2.debug("Stored adapted lockfile at", lockfileDstPath);
364
- return;
365
- }
366
- }
367
- }
368
-
369
- // src/helpers/detect-package-manager.ts
370
- var supportedPackageManagerNames = ["pnpm", "yarn", "npm"];
371
- var packageManager;
372
- function detectPackageManager(workspaceRoot) {
373
- packageManager = inferFromFiles(workspaceRoot);
374
- return packageManager;
375
- }
376
- function inferFromFiles(workspaceRoot) {
377
- for (const name of supportedPackageManagerNames) {
378
- const lockfileName = getLockfileFileName(name);
379
- if (fs9.existsSync(path6.join(workspaceRoot, lockfileName))) {
380
- return { name, version: getVersion(name) };
381
- }
382
- }
383
- if (fs9.existsSync(path6.join(workspaceRoot, "npm-shrinkwrap.json"))) {
384
- return { name: "npm", version: getVersion("npm") };
385
- }
386
- throw new Error(`Failed to detect package manager`);
387
- }
388
- function getVersion(packageManagerName) {
389
- const buffer = execSync(`${packageManagerName} --version`);
390
- return buffer.toString().trim();
391
- }
392
- function usePackageManager() {
393
- if (!packageManager) {
394
- throw Error(
395
- "No package manager detected. Make sure to call detectPackageManager() before usePackageManager()"
396
- );
397
- }
398
- return packageManager;
399
- }
400
-
401
- // src/helpers/find-packages-globs.ts
402
- function findPackagesGlobs(workspaceRootDir) {
403
- const log2 = createLogger(getConfig().logLevel);
404
- const packageManager2 = usePackageManager();
405
- switch (packageManager2.name) {
406
- case "pnpm": {
407
- const { packages: globs } = readTypedYamlSync(
408
- path7.join(workspaceRootDir, "pnpm-workspace.yaml")
409
- );
410
- log2.debug("Detected pnpm packages globs:", inspectValue(globs));
411
- return globs;
412
- }
413
- case "yarn":
414
- case "npm": {
415
- const workspaceRootManifestPath = path7.join(
416
- workspaceRootDir,
417
- "package.json"
418
- );
419
- const { workspaces } = readTypedJsonSync(
420
- workspaceRootManifestPath
421
- );
422
- if (!workspaces) {
423
- throw new Error(
424
- `No workspaces field found in ${workspaceRootManifestPath}`
425
- );
426
- }
427
- if (Array.isArray(workspaces)) {
428
- return workspaces;
429
- } else {
430
- const workspacesObject = workspaces;
431
- assert3(
432
- workspacesObject.packages,
433
- "workspaces.packages must be an array"
434
- );
435
- return workspacesObject.packages;
436
- }
437
- }
438
- }
439
- }
440
-
441
- // src/helpers/create-packages-registry.ts
442
- async function createPackagesRegistry(workspaceRootDir, workspacePackagesOverride) {
443
- const log2 = createLogger(getConfig().logLevel);
444
- if (workspacePackagesOverride) {
445
- log2.debug(
446
- `Override workspace packages via config: ${workspacePackagesOverride}`
447
- );
448
- }
449
- const packagesGlobs = workspacePackagesOverride ?? findPackagesGlobs(workspaceRootDir);
450
- const cwd = process.cwd();
451
- process.chdir(workspaceRootDir);
452
- const allPackages = packagesGlobs.flatMap((glob) => globSync(glob)).filter((dir) => fs10.lstatSync(dir).isDirectory());
453
- const registry = (await Promise.all(
454
- allPackages.map(async (rootRelativeDir) => {
455
- const manifestPath = path8.join(rootRelativeDir, "package.json");
456
- if (!fs10.existsSync(manifestPath)) {
457
- log2.warn(
458
- `Ignoring directory ./${rootRelativeDir} because it does not contain a package.json file`
459
- );
460
- return;
461
- } else {
462
- log2.debug(`Registering package ./${rootRelativeDir}`);
463
- const manifest = await readTypedJson(
464
- path8.join(rootRelativeDir, "package.json")
465
- );
466
- return {
467
- manifest,
468
- rootRelativeDir,
469
- absoluteDir: path8.join(workspaceRootDir, rootRelativeDir)
470
- };
471
- }
472
- })
473
- )).reduce((acc, info) => {
474
- if (info) {
475
- acc[info.manifest.name] = info;
476
- }
477
- return acc;
478
- }, {});
479
- process.chdir(cwd);
480
- return registry;
481
- }
482
-
483
- // src/helpers/get-build-output-dir.ts
484
- import fs11 from "fs-extra";
485
- import path9 from "node:path";
486
- import outdent from "outdent";
487
- async function getBuildOutputDir(targetPackageDir) {
488
- const config2 = getConfig();
489
- const log2 = createLogger(getConfig().logLevel);
490
- if (config2.buildDirName) {
491
- log2.debug("Using buildDirName from config:", config2.buildDirName);
492
- return path9.join(targetPackageDir, config2.buildDirName);
493
- }
494
- const tsconfigPath = path9.join(targetPackageDir, config2.tsconfigPath);
495
- if (fs11.existsSync(tsconfigPath)) {
496
- log2.debug("Found tsconfig at:", config2.tsconfigPath);
497
- const tsconfig = await readTypedJson(tsconfigPath);
498
- const outDir = tsconfig.compilerOptions?.outDir;
499
- if (outDir) {
500
- return path9.join(targetPackageDir, outDir);
501
- } else {
502
- throw new Error(outdent`
503
- 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.
504
- `);
505
- }
506
- } else {
507
- log2.warn("Failed to find tsconfig at:", tsconfigPath);
508
- throw new Error(outdent`
509
- 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.
510
- `);
511
- }
512
- }
513
-
514
- // src/helpers/list-local-dependencies.ts
515
- function listLocalDependencies(manifest, packagesRegistry, { includeDevDependencies = false } = {}) {
516
- const allWorkspacePackageNames = Object.keys(packagesRegistry);
517
- const localDependencyPackageNames = (includeDevDependencies ? [
518
- ...Object.keys(manifest.dependencies ?? {}),
519
- ...Object.keys(manifest.devDependencies ?? {})
520
- ] : Object.keys(manifest.dependencies ?? {})).filter((name) => allWorkspacePackageNames.includes(name));
521
- const nestedLocalDependencies = localDependencyPackageNames.flatMap(
522
- (packageName) => listLocalDependencies(
523
- packagesRegistry[packageName].manifest,
524
- packagesRegistry,
525
- { includeDevDependencies }
526
- )
527
- );
528
- return localDependencyPackageNames.concat(nestedLocalDependencies);
529
- }
530
-
531
- // src/helpers/manifest.ts
532
- import path10 from "node:path";
533
-
534
- // src/helpers/pack-dependencies.ts
535
- import assert4 from "node:assert";
536
- async function packDependencies({
537
- /**
538
- * All packages found in the monorepo by workspaces declaration
539
- */
540
- packagesRegistry,
541
- /**
542
- * The package names that appear to be local dependencies
543
- */
544
- localDependencies,
545
- /**
546
- * The directory where the isolated package and all its dependencies will end
547
- * up. This is also the directory from where the package will be deployed. By
548
- * default it is a subfolder in targetPackageDir called "isolate" but you can
549
- * configure it.
550
- */
551
- packDestinationDir
552
- }) {
553
- const config2 = getConfig();
554
- const log2 = createLogger(config2.logLevel);
555
- const packedFileByName = {};
556
- const { name, version } = usePackageManager();
557
- const versionMajor = parseInt(version.split(".")[0], 10);
558
- const usePnpmPack = !config2.avoidPnpmPack && name === "pnpm" && versionMajor >= 8;
559
- if (usePnpmPack) {
560
- log2.debug("Using PNPM pack instead of NPM pack");
561
- }
562
- for (const dependency of localDependencies) {
563
- const def = packagesRegistry[dependency];
564
- assert4(dependency, `Failed to find package definition for ${dependency}`);
565
- const { name: name2 } = def.manifest;
566
- if (packedFileByName[name2]) {
567
- log2.debug(`Skipping ${name2} because it has already been packed`);
568
- continue;
569
- }
570
- packedFileByName[name2] = await pack(
571
- def.absoluteDir,
572
- packDestinationDir,
573
- usePnpmPack
574
- );
575
- }
576
- return packedFileByName;
577
- }
578
-
579
- // src/helpers/patch-workspace-entries.ts
580
- import path11 from "node:path";
581
- function patchWorkspaceEntries(dependencies, packagesRegistry, parentRootRelativeDir) {
582
- const log2 = createLogger(getConfig().logLevel);
583
- const allWorkspacePackageNames = Object.keys(packagesRegistry);
584
- return Object.fromEntries(
585
- Object.entries(dependencies).map(([key, value]) => {
586
- if (allWorkspacePackageNames.includes(key)) {
587
- const def = packagesRegistry[key];
588
- const relativePath = parentRootRelativeDir ? path11.relative(parentRootRelativeDir, `./${def.rootRelativeDir}`) : `./${def.rootRelativeDir}`;
589
- const linkPath = `file:${relativePath}`;
590
- log2.debug(`Linking dependency ${key} to ${linkPath}`);
591
- return [key, linkPath];
592
- } else {
593
- return [key, value];
594
- }
595
- })
596
- );
597
- }
598
-
599
- // src/helpers/process-build-output-files.ts
600
- import fs12 from "fs-extra";
601
- import path12 from "node:path";
602
- var TIMEOUT_MS = 5e3;
603
- async function processBuildOutputFiles({
604
- targetPackageDir,
605
- tmpDir,
606
- isolateDir
607
- }) {
608
- const log2 = createLogger(getConfig().logLevel);
609
- const packedFilePath = await pack(targetPackageDir, tmpDir);
610
- const unpackDir = path12.join(tmpDir, "target");
611
- const now = Date.now();
612
- let isWaitingYet = false;
613
- while (!fs12.existsSync(packedFilePath) && Date.now() - now < TIMEOUT_MS) {
614
- if (!isWaitingYet) {
615
- log2.debug(`Waiting for ${packedFilePath} to become available...`);
616
- }
617
- isWaitingYet = true;
618
- await new Promise((resolve) => setTimeout(resolve, 100));
619
- }
620
- await unpack(packedFilePath, unpackDir);
621
- await fs12.copy(path12.join(unpackDir, "package"), isolateDir);
622
- }
623
-
624
- // src/helpers/unpack-dependencies.ts
625
- import fs13 from "fs-extra";
626
- import path13, { join } from "node:path";
627
- async function unpackDependencies(packedFilesByName, packagesRegistry, tmpDir, isolateDir) {
628
- const log2 = createLogger(getConfig().logLevel);
629
- await Promise.all(
630
- Object.entries(packedFilesByName).map(async ([packageName, filePath]) => {
631
- const dir = packagesRegistry[packageName].rootRelativeDir;
632
- const unpackDir = join(tmpDir, dir);
633
- log2.debug("Unpacking", `(temp)/${path13.basename(filePath)}`);
634
- await unpack(filePath, unpackDir);
635
- const destinationDir = join(isolateDir, dir);
636
- await fs13.ensureDir(destinationDir);
637
- await fs13.move(join(unpackDir, "package"), destinationDir, {
638
- overwrite: true
639
- });
640
- log2.debug(
641
- `Moved package files to ${getIsolateRelativePath(
642
- destinationDir,
643
- isolateDir
644
- )}`
645
- );
646
- })
647
- );
648
- }
649
-
650
- // src/index.ts
651
- var config = getConfig();
652
- var log = createLogger(config.logLevel);
653
- sourceMaps.install();
654
- async function start() {
655
- const __dirname = getDirname(import.meta.url);
656
- const thisPackageManifest = await readTypedJson(
657
- path14.join(path14.join(__dirname, "..", "package.json"))
658
- );
659
- log.debug("Running isolate-package version", thisPackageManifest.version);
660
- const targetPackageDir = config.targetPackagePath ? path14.join(process.cwd(), config.targetPackagePath) : process.cwd();
661
- const workspaceRootDir = config.targetPackagePath ? process.cwd() : path14.join(targetPackageDir, config.workspaceRoot);
662
- const buildOutputDir = await getBuildOutputDir(targetPackageDir);
663
- assert5(
664
- fs14.existsSync(buildOutputDir),
665
- `Failed to find build output path at ${buildOutputDir}. Please make sure you build the source before isolating it.`
666
- );
667
- log.debug("Workspace root resolved to", workspaceRootDir);
668
- log.debug(
669
- "Isolate target package",
670
- getRootRelativePath(targetPackageDir, workspaceRootDir)
671
- );
672
- const isolateDir = path14.join(targetPackageDir, config.isolateDirName);
673
- log.debug(
674
- "Isolate output directory",
675
- getRootRelativePath(isolateDir, workspaceRootDir)
676
- );
677
- if (fs14.existsSync(isolateDir)) {
678
- await fs14.remove(isolateDir);
679
- log.debug("Cleaned the existing isolate output directory");
680
- }
681
- await fs14.ensureDir(isolateDir);
682
- const tmpDir = path14.join(isolateDir, "__tmp");
683
- await fs14.ensureDir(tmpDir);
684
- const targetPackageManifest = await readTypedJson(
685
- path14.join(targetPackageDir, "package.json")
686
- );
687
- const packageManager2 = detectPackageManager(workspaceRootDir);
688
- log.debug(
689
- "Detected package manager",
690
- packageManager2.name,
691
- packageManager2.version
692
- );
693
- if (packageManager2.name === "pnpm") {
694
- config.excludeLockfile = true;
695
- }
696
- const packagesRegistry = await createPackagesRegistry(
697
- workspaceRootDir,
698
- config.workspacePackages
699
- );
700
- const localDependencies = listLocalDependencies(
701
- targetPackageManifest,
702
- packagesRegistry,
703
- {
704
- includeDevDependencies: config.includeDevDependencies
705
- }
706
- );
707
- const packedFilesByName = await packDependencies({
708
- localDependencies,
709
- packagesRegistry,
710
- packDestinationDir: tmpDir
711
- });
712
- await unpackDependencies(
713
- packedFilesByName,
714
- packagesRegistry,
715
- tmpDir,
716
- isolateDir
717
- );
718
- await adaptManifestFiles(localDependencies, packagesRegistry, isolateDir);
719
- await processBuildOutputFiles({
720
- targetPackageDir,
721
- tmpDir,
722
- isolateDir
723
- });
724
- await adaptTargetPackageManifest(
725
- targetPackageManifest,
726
- packagesRegistry,
727
- isolateDir
728
- );
729
- if (config.excludeLockfile) {
730
- log.warn("Excluding the lockfile from the isolate output");
731
- } else {
732
- await processLockfile({
733
- workspaceRootDir,
734
- targetPackageName: targetPackageManifest.name,
735
- isolateDir,
736
- packagesRegistry
737
- });
738
- }
739
- const npmrcPath = path14.join(workspaceRootDir, ".npmrc");
740
- if (fs14.existsSync(npmrcPath)) {
741
- fs14.copyFileSync(npmrcPath, path14.join(isolateDir, ".npmrc"));
742
- log.debug("Copied .npmrc file to the isolate output");
743
- }
744
- log.debug(
745
- "Deleting temp directory",
746
- getRootRelativePath(tmpDir, workspaceRootDir)
747
- );
748
- await fs14.remove(tmpDir);
749
- log.info("Isolate completed at", isolateDir);
750
- }
751
- start().catch((err) => {
752
- if (err instanceof Error) {
753
- log.error(err.stack);
754
- process.exit(1);
755
- } else {
756
- console.error(err);
757
- }
758
- });
759
- process.on("unhandledRejection", log.error);
760
7
  //# sourceMappingURL=index.mjs.map