@sanity/pkg-utils 9.2.3 → 10.1.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.
Files changed (50) hide show
  1. package/dist/_chunks-es/buildAction.js +151 -2
  2. package/dist/_chunks-es/buildAction.js.map +1 -1
  3. package/dist/_chunks-es/checkAction.js +183 -2
  4. package/dist/_chunks-es/checkAction.js.map +1 -1
  5. package/dist/_chunks-es/createApiExtractorConfig.js +52 -0
  6. package/dist/_chunks-es/createApiExtractorConfig.js.map +1 -0
  7. package/dist/_chunks-es/createTSDocConfig.js +31 -0
  8. package/dist/_chunks-es/createTSDocConfig.js.map +1 -0
  9. package/dist/_chunks-es/defaults.js +36 -0
  10. package/dist/_chunks-es/defaults.js.map +1 -0
  11. package/dist/_chunks-es/define.js +7 -0
  12. package/dist/_chunks-es/define.js.map +1 -0
  13. package/dist/_chunks-es/fileExists.js +12 -0
  14. package/dist/_chunks-es/fileExists.js.map +1 -0
  15. package/dist/_chunks-es/getExtractMessagesConfig.js +83 -0
  16. package/dist/_chunks-es/getExtractMessagesConfig.js.map +1 -0
  17. package/dist/_chunks-es/handleError.js +25 -1
  18. package/dist/_chunks-es/handleError.js.map +1 -1
  19. package/dist/_chunks-es/index.js +8 -212
  20. package/dist/_chunks-es/index.js.map +1 -1
  21. package/dist/_chunks-es/initAction.js +515 -2
  22. package/dist/_chunks-es/initAction.js.map +1 -1
  23. package/dist/_chunks-es/printExtractMessages.js +44 -0
  24. package/dist/_chunks-es/printExtractMessages.js.map +1 -0
  25. package/dist/_chunks-es/{consoleSpy.js → resolveBuildContext.js} +51 -167
  26. package/dist/_chunks-es/resolveBuildContext.js.map +1 -0
  27. package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
  28. package/dist/_chunks-es/watchAction.js +108 -2
  29. package/dist/_chunks-es/watchAction.js.map +1 -1
  30. package/dist/cli.js +1 -1
  31. package/dist/index.d.ts +5 -208
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +3 -18
  34. package/dist/index.js.map +1 -1
  35. package/package.json +8 -14
  36. package/dist/_chunks-es/build.js +0 -150
  37. package/dist/_chunks-es/build.js.map +0 -1
  38. package/dist/_chunks-es/check.js +0 -189
  39. package/dist/_chunks-es/check.js.map +0 -1
  40. package/dist/_chunks-es/consoleSpy.js.map +0 -1
  41. package/dist/_chunks-es/init.js +0 -520
  42. package/dist/_chunks-es/init.js.map +0 -1
  43. package/dist/_chunks-es/isRecord.js +0 -37
  44. package/dist/_chunks-es/isRecord.js.map +0 -1
  45. package/dist/_chunks-es/watch.js +0 -109
  46. package/dist/_chunks-es/watch.js.map +0 -1
  47. package/tsconfig/isolated-declarations.json +0 -11
  48. package/tsconfig/recommended.json +0 -24
  49. package/tsconfig/strict.json +0 -15
  50. package/tsconfig/strictest.json +0 -16
@@ -1,42 +1,26 @@
1
- import path, { resolve } from "node:path";
2
- import { pathToFileURL } from "node:url";
3
- import { packageUp } from "package-up";
4
- import { tsImport } from "tsx/esm/api";
5
- import findConfig from "find-config";
6
- import { fileExists, isRecord } from "./isRecord.js";
1
+ import { parsePackage, _typoMap, ZodError, parseExports } from "@sanity/parse-package-json";
7
2
  import chalk from "chalk";
8
- import { z, ZodError } from "zod/v3";
9
3
  import fs from "node:fs/promises";
4
+ import path, { resolve } from "node:path";
10
5
  import browserslist from "browserslist";
11
- import config from "@sanity/browserslist-config";
6
+ import { DEFAULT_BROWSERSLIST_QUERY } from "./defaults.js";
12
7
  import { existsSync } from "node:fs";
8
+ import { isRecord } from "./handleError.js";
13
9
  import ts from "typescript";
14
10
  import { errorMap } from "zod-validation-error/v3";
15
- const CONFIG_FILE_NAMES = [
16
- "package.config.ts",
17
- "package.config.js",
18
- "package.config.cjs",
19
- "package.config.mts",
20
- "package.config.mjs"
21
- ];
22
- function findConfigFile(cwd) {
23
- const pkgJsonPath = findConfig("package.json", { cwd });
24
- if (!pkgJsonPath) return;
25
- const pkgPath = path.dirname(pkgJsonPath);
26
- for (const fileName of CONFIG_FILE_NAMES) {
27
- const configPath = path.resolve(pkgPath, fileName);
28
- if (fileExists(configPath))
29
- return configPath;
30
- }
31
- }
32
- async function loadConfig(options) {
33
- const { cwd } = options, pkgPath = await packageUp({ cwd });
34
- if (!pkgPath) return;
35
- const root = path.dirname(pkgPath), configFile = findConfigFile(root);
36
- if (!configFile || !configFile.startsWith(cwd))
37
- return;
38
- const mod = await tsImport(pathToFileURL(configFile).toString(), import.meta.url);
39
- return mod?.default || mod || void 0;
11
+ import { z } from "zod/v3";
12
+ function createConsoleSpy(options) {
13
+ const { onRestored } = options || {}, original = {
14
+ log: console.log,
15
+ warn: console.warn,
16
+ error: console.error
17
+ }, messages = [];
18
+ return console.log = (...args) => messages.push({ type: "log", args }), console.warn = (...args) => messages.push({ type: "warn", args }), console.error = (...args) => messages.push({ type: "error", args }), {
19
+ messages,
20
+ restore: () => {
21
+ console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
22
+ }
23
+ };
40
24
  }
41
25
  function assertLast(a, arr) {
42
26
  const aIdx = arr.indexOf(a);
@@ -46,85 +30,26 @@ function assertOrder(a, b, arr) {
46
30
  const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
47
31
  return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
48
32
  }
49
- const pkgSchema = z.object({
50
- type: z.optional(z.enum(["commonjs", "module"])),
51
- name: z.string(),
52
- version: z.string(),
53
- license: z.string(),
54
- bin: z.optional(z.record(z.string())),
55
- dependencies: z.optional(z.record(z.string())),
56
- devDependencies: z.optional(z.record(z.string())),
57
- peerDependencies: z.optional(z.record(z.string())),
58
- source: z.optional(z.string()),
59
- main: z.optional(z.string()),
60
- browser: z.optional(z.record(z.string())),
61
- module: z.optional(z.string()),
62
- types: z.optional(z.string()),
63
- exports: z.optional(
64
- z.record(
65
- z.union([
66
- z.custom(
67
- (val) => typeof val == "string" && /^\.\/.*\.json$/.test(val)
68
- ),
69
- z.custom((val) => typeof val == "string" && /^\.\/.*\.css$/.test(val)),
70
- z.object({
71
- types: z.optional(z.string()),
72
- source: z.optional(z.string()),
73
- browser: z.optional(
74
- z.object({
75
- source: z.string(),
76
- import: z.optional(z.string()),
77
- require: z.optional(z.string())
78
- })
79
- ),
80
- node: z.optional(
81
- z.object({
82
- source: z.optional(z.string()),
83
- import: z.optional(z.string()),
84
- require: z.optional(z.string())
85
- })
86
- ),
87
- import: z.optional(z.string()),
88
- require: z.optional(z.string()),
89
- default: z.string()
90
- }),
91
- z.object({
92
- types: z.optional(z.string()),
93
- svelte: z.string(),
94
- default: z.optional(z.string())
95
- })
96
- ])
97
- )
98
- ),
99
- browserslist: z.optional(z.union([z.string(), z.array(z.string())])),
100
- sideEffects: z.optional(z.union([z.boolean(), z.array(z.string())])),
101
- // @TODO type this properly
102
- typesVersions: z.optional(z.any())
103
- }), typoMap = /* @__PURE__ */ new Map();
104
- for (const key of pkgSchema.keyof()._def.values)
105
- typoMap.set(key.toUpperCase(), key);
106
33
  function validatePkg(input) {
107
- const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
34
+ const pkg = parsePackage(input), invalidKey = Object.keys(input).find((key) => {
108
35
  const needle = key.toUpperCase();
109
- return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
36
+ return _typoMap.has(needle) ? _typoMap.get(needle) !== key : !1;
110
37
  });
111
38
  if (invalidKey)
112
39
  throw new TypeError(
113
40
  `
114
- - package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
41
+ - package.json: "${invalidKey}" is not a valid key. Did you mean "${_typoMap.get(invalidKey.toUpperCase())}"?`
115
42
  );
116
43
  return pkg;
117
44
  }
118
45
  async function loadPkg(options) {
119
- const { cwd } = options, pkgPath = await packageUp({ cwd });
120
- if (!pkgPath) throw new Error("no package.json found");
121
- const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
46
+ const { pkgPath } = options, raw = JSON.parse(await fs.readFile(pkgPath, "utf-8"));
122
47
  return validatePkg(raw), raw;
123
48
  }
124
49
  async function loadPkgWithReporting(options) {
125
- const { cwd, logger, strict: strict2, strictOptions: strictOptions2 } = options;
50
+ const { pkgPath, logger, strict: strict2, strictOptions: strictOptions2 } = options;
126
51
  try {
127
- const pkg = await loadPkg({ cwd });
52
+ const pkg = await loadPkg({ pkgPath });
128
53
  let shouldError = !1;
129
54
  if (strict2) {
130
55
  if (strictOptions2.preferModuleType !== "off")
@@ -137,14 +62,6 @@ async function loadPkgWithReporting(options) {
137
62
  const msg = 'package.json: `type` field is missing. Future versions of pkg-utils will require `"type": "module"`. Consider adding `"type": "module"` to prepare for this change.';
138
63
  strictOptions2.preferModuleType === "error" ? (shouldError = !0, logger.error(msg)) : logger.warn(msg);
139
64
  }
140
- if (strictOptions2.noPackageJsonMain !== "off" && pkg.main) {
141
- const msg = "package.json: the `main` field is no longer needed. All modern versions of Node.js and bundlers support the `exports` field. Remove the `main` field and use `exports` instead.";
142
- strictOptions2.noPackageJsonMain === "error" ? (shouldError = !0, logger.error(msg)) : logger.warn(msg);
143
- }
144
- if (strictOptions2.noPackageJsonModule !== "off" && pkg.module) {
145
- const msg = "package.json: the `module` field is no longer needed. All modern versions of Node.js and bundlers support the `exports` field. Remove the `module` field and use `exports` instead.";
146
- strictOptions2.noPackageJsonModule === "error" ? (shouldError = !0, logger.error(msg)) : logger.warn(msg);
147
- }
148
65
  if (strictOptions2.noPackageJsonBrowser !== "off" && pkg.browser) {
149
66
  const msg = "package.json: the `browser` field is no longer needed. Use the `browser` condition in `exports` instead for better support across modern bundlers.";
150
67
  strictOptions2.noPackageJsonBrowser === "error" ? (shouldError = !0, logger.error(msg)) : logger.warn(msg);
@@ -235,7 +152,6 @@ function isPkgConfigPropertyResolver(prop) {
235
152
  function resolveConfigProperty(prop, initialValue) {
236
153
  return prop ? isPkgConfigPropertyResolver(prop) ? prop(initialValue) : prop : initialValue;
237
154
  }
238
- const DEFAULT_BROWSERSLIST_QUERY = config;
239
155
  function pathContains(containerPath, itemPath) {
240
156
  return !path.relative(containerPath, itemPath).startsWith("..");
241
157
  }
@@ -291,7 +207,11 @@ const pkgExtMap = {
291
207
  function validateExports(_exports, options) {
292
208
  const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
293
209
  for (const exp of _exports)
294
- exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
210
+ exp._path === "." && (exp.require && pkg.main && exp.require !== pkg.main && errors.push(
211
+ 'package.json: mismatch between "main" and "exports.require". These must be equal.'
212
+ ), exp.import && pkg.module && exp.import !== pkg.module && errors.push(
213
+ 'package.json: mismatch between "module" and "exports.import". These must be equal.'
214
+ )), exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
295
215
  `package.json with \`type: "${type}"\` - \`exports["${exp._path}"].require\` must end with "${ext.commonjs}"`
296
216
  ), exp.import && !exp.import.endsWith(ext.esm) && errors.push(
297
217
  `package.json with \`type: "${type}"\` - \`exports["${exp._path}"].import\` must end with "${ext.esm}"`
@@ -301,7 +221,7 @@ function validateExports(_exports, options) {
301
221
  function isTruthy$1(value) {
302
222
  return !!value;
303
223
  }
304
- function parseExports(options) {
224
+ function parseAndValidateExports(options) {
305
225
  const { cwd, pkg, strict: strict2, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
306
226
  kind === "warn" ? logger.warn(message) : errors.push(message);
307
227
  };
@@ -367,37 +287,21 @@ function parseExports(options) {
367
287
  ].join(`
368
288
  - `)
369
289
  );
370
- const _exports = [];
290
+ const _exports = parseExports({ pkg });
371
291
  strict2 && strictOptions2.noPackageJsonTypings !== "off" && "typings" in pkg && report(strictOptions2.noPackageJsonTypings, "package.json: `typings` should be `types`"), strict2 && strictOptions2.alwaysPackageJsonTypes !== "off" && !pkg.types && typeof pkg.exports?.["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source?.endsWith(".ts") && report(
372
292
  strictOptions2.alwaysPackageJsonTypes,
373
293
  "package.json: `types` must be declared for the npm listing to show as a TypeScript module."
374
294
  ), strict2 && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
375
295
  for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
376
- if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
377
- exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
378
- else if (exportPath.endsWith(".css"))
379
- typeof exportEntry == "string" && !existsSync(resolve(cwd, exportEntry)) ? errors.push(
380
- `package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
381
- ) : typeof exportEntry != "string" && errors.push(
382
- `package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
383
- );
384
- else if (!(isRecord(exportEntry) && "svelte" in exportEntry))
385
- if (isPkgExport(exportEntry)) {
386
- const exp = {
387
- _exported: !0,
388
- _path: exportPath,
389
- ...exportEntry
390
- };
391
- if (!exp.default) {
392
- const fallback = type === "module" ? exp.import : exp.require;
393
- fallback && (exp.default = fallback);
394
- }
395
- !exp.require && type === "commonjs" && exp.default && (exp.require = exp.default), !exp.import && type === "module" && exp.default && (exp.import = exp.default), exportPath === "." && (exportEntry.require && pkg.main && exportEntry.require !== pkg.main && errors.push(
396
- 'package.json: mismatch between "main" and "exports.require". These must be equal.'
397
- ), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
398
- 'package.json: mismatch between "module" and "exports.import" These must be equal.'
399
- )), _exports.push(exp);
400
- } else isRecord(exportEntry) || errors.push("package.json: exports must be an object");
296
+ exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json") ? exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".') : exportPath.endsWith(".css") ? typeof exportEntry == "string" && !existsSync(resolve(cwd, exportEntry)) ? errors.push(
297
+ `package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
298
+ ) : typeof exportEntry != "string" && errors.push(
299
+ `package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
300
+ ) : isRecord(exportEntry) && "svelte" in exportEntry || (isPkgExport(exportEntry) ? exportPath === "." && (exportEntry.require && pkg.main && exportEntry.require !== pkg.main && errors.push(
301
+ 'package.json: mismatch between "main" and "exports.require". These must be equal.'
302
+ ), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
303
+ 'package.json: mismatch between "module" and "exports.import" These must be equal.'
304
+ )) : isRecord(exportEntry) || errors.push("package.json: exports must be an object"));
401
305
  if (errors.push(...validateExports(_exports, { pkg })), errors.length)
402
306
  throw new Error(`
403
307
  - ` + errors.join(`
@@ -433,8 +337,6 @@ const toggle = z.union([z.literal("error"), z.literal("warn"), z.literal("off")]
433
337
  alwaysPackageJsonTypes: toggle.default("error"),
434
338
  alwaysPackageJsonFiles: toggle.default("error"),
435
339
  noCheckTypes: toggle.default("warn"),
436
- noPackageJsonMain: toggle.default("warn"),
437
- noPackageJsonModule: toggle.default("warn"),
438
340
  noPackageJsonBrowser: toggle.default("warn"),
439
341
  noPackageJsonTypesVersions: toggle.default("warn"),
440
342
  preferModuleType: toggle.default("warn")
@@ -453,15 +355,15 @@ function isTruthy(value) {
453
355
  }
454
356
  async function resolveBuildContext(options) {
455
357
  const {
456
- config: config2,
358
+ config,
457
359
  cwd,
458
360
  emitDeclarationOnly = !1,
459
361
  logger,
460
362
  pkg,
461
363
  strict: strict2,
462
364
  tsconfig: tsconfigPath
463
- } = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
464
- if (strictOptions2.noCheckTypes !== "off" && tsconfig?.options && config2?.dts !== "rolldown" && tsconfig.options.noCheck !== !1 && !tsconfig.options.noCheck) {
365
+ } = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config?.strictOptions ?? {});
366
+ if (strictOptions2.noCheckTypes !== "off" && tsconfig?.options && config?.dts !== "rolldown" && tsconfig.options.noCheck !== !1 && !tsconfig.options.noCheck) {
465
367
  if (strictOptions2.noCheckTypes === "error")
466
368
  throw new Error(
467
369
  "`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it."
@@ -499,7 +401,7 @@ async function resolveBuildContext(options) {
499
401
  "*": webTarget.concat(nodeTarget),
500
402
  browser: webTarget,
501
403
  node: nodeTarget
502
- }, parsedExports = parseExports({
404
+ }, parsedExports = parseAndValidateExports({
503
405
  cwd,
504
406
  pkg,
505
407
  strict: strict2,
@@ -508,13 +410,13 @@ async function resolveBuildContext(options) {
508
410
  }).reduce(
509
411
  (acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
510
412
  {}
511
- ), exports$1 = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
413
+ ), exports$1 = resolveConfigProperty(config?.exports, parsedExports), parsedExternal = [
512
414
  ...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
513
415
  ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
514
- ], external = config2 && Array.isArray(config2.external) ? [...parsedExternal, ...config2.external] : resolveConfigProperty(config2?.external, parsedExternal), externalWithTypes = /* @__PURE__ */ new Set([pkg.name, ...external, ...external.map(transformPackageName)]), bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(
416
+ ], external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : resolveConfigProperty(config?.external, parsedExternal), externalWithTypes = /* @__PURE__ */ new Set([pkg.name, ...external, ...external.map(transformPackageName)]), bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(
515
417
  // Do not bundle anything that is marked as external
516
418
  (_) => !externalWithTypes.has(_)
517
- ), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports$1).flatMap((exportEntry) => [
419
+ ), bundledPackages = config && Array.isArray(config.extract?.bundledPackages) ? [...bundledDependencies, ...config.extract.bundledPackages] : resolveConfigProperty(config?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports$1).flatMap((exportEntry) => [
518
420
  exportEntry.import,
519
421
  exportEntry.require,
520
422
  exportEntry.browser?.import,
@@ -528,14 +430,14 @@ async function resolveBuildContext(options) {
528
430
  );
529
431
  if (commonDistPath && !pathContains(cwd, commonDistPath))
530
432
  throw new Error("all output files must be located within the package");
531
- const configDistPath = config2?.dist ? path.resolve(cwd, config2.dist) : void 0;
433
+ const configDistPath = config?.dist ? path.resolve(cwd, config.dist) : void 0;
532
434
  if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
533
435
  throw logger.log(`did you mean to configure \`dist: './${path.relative(cwd, commonDistPath)}'\`?`), new Error("all output files must be located with the configured `dist` path");
534
436
  const distPath = configDistPath || commonDistPath;
535
437
  if (!distPath)
536
438
  throw new Error("could not detect `dist` path");
537
439
  return {
538
- config: config2,
440
+ config,
539
441
  cwd,
540
442
  distPath,
541
443
  emitDeclarationOnly,
@@ -545,14 +447,14 @@ async function resolveBuildContext(options) {
545
447
  files: [],
546
448
  logger,
547
449
  pkg,
548
- runtime: config2?.runtime ?? "*",
450
+ runtime: config?.runtime ?? "*",
549
451
  strict: strict2,
550
452
  target,
551
453
  ts: {
552
454
  config: tsconfig,
553
455
  configPath: tsconfigPath
554
456
  },
555
- dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
457
+ dts: config?.dts === "rolldown" ? "rolldown" : "api-extractor"
556
458
  };
557
459
  }
558
460
  function transformPackageName(packageName) {
@@ -564,31 +466,13 @@ function transformPackageName(packageName) {
564
466
  } else
565
467
  return `@types/${packageName}`;
566
468
  }
567
- function createConsoleSpy(options) {
568
- const { onRestored } = options || {}, original = {
569
- log: console.log,
570
- warn: console.warn,
571
- error: console.error
572
- }, messages = [];
573
- return console.log = (...args) => messages.push({ type: "log", args }), console.warn = (...args) => messages.push({ type: "warn", args }), console.error = (...args) => messages.push({ type: "error", args }), {
574
- messages,
575
- restore: () => {
576
- console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
577
- }
578
- };
579
- }
580
469
  export {
581
- DEFAULT_BROWSERSLIST_QUERY,
582
470
  createConsoleSpy,
583
471
  getTargetPaths,
584
- loadConfig,
585
- loadPkg,
586
472
  loadPkgWithReporting,
587
- parseExports,
588
- parseStrictOptions,
589
473
  pkgExtMap,
590
474
  resolveBuildContext,
591
475
  resolveConfigProperty,
592
476
  strict
593
477
  };
594
- //# sourceMappingURL=consoleSpy.js.map
478
+ //# sourceMappingURL=resolveBuildContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveBuildContext.js","sources":["../../src/node/consoleSpy.ts","../../src/node/core/pkg/helpers.ts","../../src/node/core/pkg/validatePkg.ts","../../src/node/core/pkg/loadPkg.ts","../../src/node/core/pkg/loadPkgWithReporting.ts","../../../../../node_modules/.pnpm/browserslist-to-esbuild@2.1.1_browserslist@4.28.0/node_modules/browserslist-to-esbuild/src/index.js","../../src/node/core/config/resolveConfigProperty.ts","../../src/node/core/findCommonPath.ts","../../src/node/tasks/dts/getTargetPaths.ts","../../src/node/core/pkg/pkgExt.ts","../../src/node/core/pkg/validateExports.ts","../../src/node/core/pkg/parseAndValidateExports.ts","../../src/node/core/ts/loadTSConfig.ts","../../src/node/resolveBrowserTarget.ts","../../src/node/resolveNodeTarget.ts","../../src/node/strict.ts","../../src/node/resolveBuildContext.ts"],"sourcesContent":["// oxlint-disable no-console\nexport interface ConsoleSpyMsg {\n type: 'log' | 'warn' | 'error'\n code?: string\n args: unknown[]\n}\n\nexport interface ConsoleSpy {\n messages: ConsoleSpyMsg[]\n restore: () => void\n}\n\nexport function createConsoleSpy(options?: {\n onRestored?: (messages: ConsoleSpyMsg[]) => void\n}): ConsoleSpy {\n const {onRestored} = options || {}\n\n const original = {\n log: console.log,\n warn: console.warn,\n error: console.error,\n }\n\n const messages: ConsoleSpyMsg[] = []\n\n console.log = (...args: unknown[]) => messages.push({type: 'log', args})\n console.warn = (...args: unknown[]) => messages.push({type: 'warn', args})\n console.error = (...args: unknown[]) => messages.push({type: 'error', args})\n\n return {\n messages,\n restore: () => {\n console.log = original.log\n console.warn = original.warn\n console.error = original.error\n\n onRestored?.(messages)\n },\n }\n}\n","/** @internal */\nexport function assertFirst<T>(a: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n\n // if not found, then we don't care\n if (aIdx === -1) {\n return true\n }\n\n return aIdx === 0\n}\n\n/** @internal */\nexport function assertLast<T>(a: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n\n // if not found, then we don't care\n if (aIdx === -1) {\n return true\n }\n\n return aIdx === arr.length - 1\n}\n\n/** @internal */\nexport function assertOrder<T>(a: T, b: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n const bIdx = arr.indexOf(b)\n\n // if either is not found, then we don't care\n if (aIdx === -1 || bIdx === -1) {\n return true\n }\n\n return aIdx < bIdx\n}\n","import {parsePackage, _typoMap as typoMap, type PackageJSON} from '@sanity/parse-package-json'\n\nexport function validatePkg(input: unknown): PackageJSON {\n const pkg = parsePackage(input)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- Need to check raw input for typos\n const invalidKey = Object.keys(input as PackageJSON).find((key) => {\n const needle = key.toUpperCase()\n\n return typoMap.has(needle) ? typoMap.get(needle) !== key : false\n })\n\n if (invalidKey) {\n throw new TypeError(\n `\n- package.json: \"${invalidKey}\" is not a valid key. Did you mean \"${typoMap.get(invalidKey.toUpperCase())}\"?`,\n )\n }\n\n return pkg\n}\n","import fs from 'node:fs/promises'\nimport type {PackageJSON} from '@sanity/parse-package-json'\nimport {validatePkg} from './validatePkg.ts'\n\n/** @internal */\nexport async function loadPkg(options: {pkgPath: string}): Promise<PackageJSON> {\n const {pkgPath} = options\n\n const raw = JSON.parse(await fs.readFile(pkgPath, 'utf-8'))\n\n validatePkg(raw)\n\n return raw\n}\n","import {ZodError, type PackageJSON} from '@sanity/parse-package-json'\nimport chalk from 'chalk'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport {assertLast, assertOrder} from './helpers.ts'\nimport {loadPkg} from './loadPkg.ts'\n\n/** @alpha */\nexport async function loadPkgWithReporting(options: {\n pkgPath: string\n logger: Logger\n strict: boolean\n strictOptions: StrictOptions\n}): Promise<PackageJSON> {\n const {pkgPath, logger, strict, strictOptions} = options\n\n try {\n const pkg = await loadPkg({pkgPath})\n let shouldError = false\n\n if (strict) {\n // Check for missing or commonjs type field\n if (strictOptions.preferModuleType !== 'off') {\n if (!pkg.type) {\n const msg =\n 'package.json: `type` field is missing. Future versions of pkg-utils will require `\"type\": \"module\"`. Consider adding `\"type\": \"module\"` to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n } else if (pkg.type === 'commonjs') {\n const msg =\n 'package.json: `type` is set to \"commonjs\". Future versions of pkg-utils will require `\"type\": \"module\"`. Consider migrating to ES modules to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n }\n\n // Check for banned root-level fields\n if (strictOptions.noPackageJsonBrowser !== 'off' && pkg.browser) {\n const msg =\n 'package.json: the `browser` field is no longer needed. Use the `browser` condition in `exports` instead for better support across modern bundlers.'\n if (strictOptions.noPackageJsonBrowser === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n if (strictOptions.noPackageJsonTypesVersions !== 'off' && pkg.typesVersions) {\n const msg =\n 'package.json: the `typesVersions` field is no longer needed. TypeScript has long supported conditional exports and the `types` condition. Remove the `typesVersions` field and use the `types` condition in `exports` instead.'\n if (strictOptions.noPackageJsonTypesVersions === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n }\n\n // validate exports\n if (pkg.exports) {\n const _exports = Object.entries(pkg.exports)\n\n for (const [expPath, exp] of _exports) {\n if (typeof exp === 'string' || 'svelte' in exp) {\n continue\n }\n\n const keys = Object.keys(exp)\n\n if (exp.types) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`types\\` condition shouldn't be used as dts files are generated in such a way that both CJS and ESM is supported`,\n )\n }\n\n if (exp.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`module\\` condition shouldn't be used as it's not well supported in all bundlers.`,\n )\n }\n\n if (exp.node) {\n if (exp.import && exp.node.import && !assertOrder('node', 'import', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`import\\` property`,\n )\n }\n\n if (exp.node.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.module\\` condition shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (\n !exp.node.source &&\n exp.node.import &&\n (exp.node.require || exp.require) &&\n (exp.node.import.endsWith('.cjs.js') || exp.node.import.endsWith('.cjs.mjs'))\n ) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.import\\` re-export pattern shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (exp.require && exp.node.require && exp.require === exp.node.require) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.require\\` property isn't necessary as it's identical to \\`require\\``,\n )\n } else if (exp.require && exp.node.require && !assertOrder('node', 'require', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`require\\` property`,\n )\n }\n } else {\n if (!assertOrder('import', 'require', keys)) {\n logger.warn(\n `exports[\"${expPath}\"]: the \\`import\\` property should come before the \\`require\\` property`,\n )\n }\n }\n\n if (!assertLast('default', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`default\\` property should be the last property`,\n )\n }\n }\n }\n\n if (shouldError) {\n process.exit(1)\n }\n\n return pkg\n } catch (err) {\n if (err instanceof ZodError) {\n for (const issue of err.issues) {\n if (issue.code === 'invalid_type') {\n logger.error(\n [\n `\\`${formatPath(issue.path)}\\` `,\n `in \\`./package.json\\` must be of type ${chalk.magenta(issue.expected)} `,\n `(received ${chalk.magenta(issue.received)})`,\n ].join(''),\n )\n continue\n }\n\n logger.error(issue)\n }\n } else {\n logger.error(err)\n }\n\n process.exit(1)\n }\n}\n\nfunction formatPath(segments: Array<string | number>) {\n return segments\n .map((s, idx) => {\n if (idx === 0) return s\n\n if (typeof s === 'number') {\n return `[${s}]`\n }\n\n if (s.startsWith('.')) {\n return `[\"${s}\"]`\n }\n\n return `.${s}`\n })\n .join('')\n}\n","import browserslist from 'browserslist'\n\n// convert the browserslist field in package.json to\n// esbuild compatible array of browsers\nexport default function browserslistToEsbuild(browserslistConfig, options = {}) {\n if (!browserslistConfig) {\n // the path from where the script is run\n const path = process.cwd()\n\n // read config if none is passed\n browserslistConfig = browserslist.loadConfig({ path, ...options })\n }\n\n const SUPPORTED_ESBUILD_TARGETS = [\n 'es',\n 'chrome',\n 'edge',\n 'firefox',\n 'ios',\n 'node',\n 'safari',\n 'opera',\n 'ie',\n ]\n\n // https://github.com/eBay/browserslist-config/issues/16#issuecomment-863870093\n const UNSUPPORTED = ['android 4']\n\n const replaces = {\n ios_saf: 'ios',\n android: 'chrome',\n }\n\n const separator = ' '\n\n return (\n browserslist(browserslistConfig, options)\n // filter out the unsupported ones\n .filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u)))\n // replaces safari TP with latest safari version\n .map((b) => {\n if (b === 'safari TP') {\n return browserslist('last 1 safari version')[0]\n }\n\n return b\n })\n // transform into ['chrome', '88']\n .map((b) => b.split(separator))\n // replace the similar browser\n .map((b) => {\n if (replaces[b[0]]) {\n b[0] = replaces[b[0]]\n }\n\n return b\n })\n // 11.0-12.0 --> 11.0\n .map((b) => {\n if (b[1].includes('-')) {\n b[1] = b[1].slice(0, b[1].indexOf('-'))\n }\n\n return b\n })\n // 11.0 --> 11\n .map((b) => {\n if (b[1].endsWith('.0')) {\n b[1] = b[1].slice(0, -2)\n }\n\n return b\n })\n // removes invalid versions that will break esbuild\n // https://github.com/evanw/esbuild/blob/35c0d65b9d4f29a26176404d2890d1b499634e9f/compat-table/src/caniuse.ts#L119-L122\n .filter((b) => /^\\d+(\\.\\d+)*$/.test(b[1]))\n // only get the targets supported by esbuild\n .filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0]))\n // only get the oldest version, assuming that the older version\n // is last in the array\n .reduce((acc, b) => {\n const existingIndex = acc.findIndex((br) => br[0] === b[0])\n\n if (existingIndex !== -1) {\n acc[existingIndex][1] = b[1]\n } else {\n acc.push(b)\n }\n return acc\n }, [])\n // remove separator\n .map((b) => b.join(''))\n )\n}\n","import type {PkgConfigProperty, PkgConfigPropertyResolver} from './types.ts'\n\nfunction isPkgConfigPropertyResolver<T>(\n prop: PkgConfigProperty<T>,\n): prop is PkgConfigPropertyResolver<T> {\n return typeof prop === 'function'\n}\n\n/** @internal */\nexport function resolveConfigProperty<T>(\n prop: PkgConfigProperty<T> | undefined,\n initialValue: T,\n): T {\n if (!prop) return initialValue\n\n if (isPkgConfigPropertyResolver(prop)) {\n return prop(initialValue)\n }\n\n return prop\n}\n","import path from 'node:path'\n\nexport function pathContains(containerPath: string, itemPath: string): boolean {\n return !path.relative(containerPath, itemPath).startsWith('..')\n}\n\nexport function findCommonDirPath(filePaths: string[]): string | undefined {\n let ret: string | undefined = undefined\n\n for (const filePath of filePaths) {\n let dirPath = path.dirname(filePath)\n\n if (!ret) {\n ret = dirPath\n continue\n }\n\n while (dirPath !== ret) {\n dirPath = path.dirname(dirPath)\n\n if (dirPath === ret) {\n break\n }\n\n if (pathContains(dirPath, ret)) {\n ret = dirPath\n break\n }\n\n if (dirPath === '.') return undefined\n }\n }\n\n return ret\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {PkgBundle, PkgExport} from '../../core/config/types.ts'\n\n/** @internal */\nexport const fileEnding: RegExp = /\\.[mc]?js$/\n/** @internal */\nexport const dtsEnding = '.d.ts'\n/** @internal */\nexport const defaultEnding = '.js'\n/** @internal */\nexport const mjsEnding = '.mjs'\n/** @internal */\nexport const cjsEnding = '.cjs'\nconst mtsEnding = '.d.mts'\nconst ctsEnding = '.d.cts'\n\n/** @internal */\nexport function getTargetPaths(\n _type: PackageJSON['type'],\n expOrBundle: PkgExport | PkgExport['browser'] | PkgExport['node'] | PkgBundle,\n): string[] {\n const type = (_type === 'module' ? 'module' : 'commonjs') satisfies PackageJSON['type']\n\n const set = new Set<string>()\n\n if (expOrBundle?.import) {\n set.add(expOrBundle.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding))\n }\n\n if (expOrBundle?.require) {\n set.add(expOrBundle.require.replace(fileEnding, type === 'commonjs' ? dtsEnding : ctsEnding))\n }\n\n if (isPkgExport(expOrBundle)) {\n if (!expOrBundle.browser?.source) {\n if (expOrBundle.browser?.import) {\n set.add(\n expOrBundle.browser.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding),\n )\n }\n\n if (expOrBundle.browser?.require) {\n set.add(\n expOrBundle.browser.require.replace(\n fileEnding,\n type === 'commonjs' ? dtsEnding : ctsEnding,\n ),\n )\n }\n }\n\n if (!expOrBundle.node?.source) {\n if (expOrBundle.node?.import) {\n set.add(\n expOrBundle.node.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding),\n )\n }\n\n if (expOrBundle.node?.require) {\n set.add(\n expOrBundle.node.require.replace(fileEnding, type === 'commonjs' ? dtsEnding : ctsEnding),\n )\n }\n }\n }\n\n return Array.from(set)\n}\n\nfunction isPkgExport(exp: any): exp is PkgExport {\n return exp?.browser || exp?.node || exp?.default\n}\n","import {cjsEnding, defaultEnding, mjsEnding} from '../../tasks/dts/getTargetPaths.ts'\n\n/** @internal */\nexport interface PkgExtMap {\n commonjs: {commonjs: string; esm: string}\n module: {commonjs: string; esm: string}\n}\n\n/** @internal */\nexport const pkgExtMap: PkgExtMap = {\n // pkg.type: \"commonjs\"\n commonjs: {\n commonjs: defaultEnding,\n esm: mjsEnding,\n },\n\n // pkg.type: \"module\"\n module: {\n commonjs: cjsEnding,\n esm: defaultEnding,\n },\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {PkgExport} from '../config/types.ts'\nimport {pkgExtMap as extMap} from './pkgExt.ts'\n\nexport function validateExports(\n _exports: (PkgExport & {_path: string})[],\n options: {pkg: PackageJSON},\n): string[] {\n const {pkg} = options\n const type = pkg.type || 'commonjs'\n const ext = extMap[type]\n\n const errors: string[] = []\n\n for (const exp of _exports) {\n if (exp._path === '.') {\n if (exp.require && pkg.main && exp.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exp.import && pkg.module && exp.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\". These must be equal.',\n )\n }\n }\n if (exp.require && !exp.require.endsWith(ext.commonjs)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].require\\` must end with \"${ext.commonjs}\"`,\n )\n }\n\n if (exp.import && !exp.import.endsWith(ext.esm)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].import\\` must end with \"${ext.esm}\"`,\n )\n }\n }\n\n return errors\n}\n","import {existsSync} from 'node:fs'\nimport {resolve as resolvePath} from 'node:path'\nimport {parseExports, type PackageJSON} from '@sanity/parse-package-json'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport {defaultEnding, fileEnding} from '../../tasks/dts/getTargetPaths.ts'\nimport type {PkgExport} from '../config/types.ts'\nimport {isRecord} from '../isRecord.ts'\nimport {pkgExtMap} from './pkgExt.ts'\nimport {validateExports} from './validateExports.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\n/** @alpha */\nexport function parseAndValidateExports(options: {\n cwd: string\n pkg: PackageJSON\n strict: boolean\n strictOptions: StrictOptions\n logger: Logger\n}): (PkgExport & {_path: string})[] {\n const {cwd, pkg, strict, strictOptions, logger} = options\n const type = pkg.type || 'commonjs'\n const errors: string[] = []\n\n const report = (kind: 'warn' | 'error', message: string) => {\n if (kind === 'warn') {\n logger.warn(message)\n } else {\n errors.push(message)\n }\n }\n\n if (!Array.isArray(pkg.files) && strict && strictOptions.alwaysPackageJsonFiles !== 'off') {\n report(\n strictOptions.alwaysPackageJsonFiles,\n 'package.json: `files` should be used over `.npmignore`',\n )\n }\n\n if (pkg.source) {\n if (\n strict &&\n pkg.exports?.['.'] &&\n typeof pkg.exports['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source === pkg.source\n ) {\n errors.push(\n 'package.json: the \"source\" property can be removed, as it is equal to exports[\".\"].source.',\n )\n } else if (!pkg.exports && pkg.main) {\n const extMap = pkgExtMap[type]\n const importExport = pkg.main.replace(fileEnding, extMap.esm)\n const requireExport = pkg.main.replace(fileEnding, extMap.commonjs)\n const defaultExport = pkg.main.replace(fileEnding, defaultEnding)\n\n const maybeBrowserCondition = []\n\n if (pkg.browser) {\n const browserConditions = []\n\n if (pkg.module && pkg.browser?.[pkg.module]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.module]!.replace(fileEnding, extMap.esm))}`,\n )\n } else if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.esm))}`,\n )\n }\n\n if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"require\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.commonjs))}`,\n )\n }\n\n if (browserConditions.length) {\n maybeBrowserCondition.push(\n ` \"browser\": {`,\n ` \"source\": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,\n ...browserConditions,\n ` }`,\n )\n }\n }\n\n errors.push(\n ...[\n 'package.json: `exports` are missing, it should be:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": ${JSON.stringify(pkg.source)},`,\n // If browser conditions are detected then add them to the suggestion\n ...(maybeBrowserCondition.length > 0 ? maybeBrowserCondition : []),\n type === 'commonjs' && ` \"import\": ${JSON.stringify(importExport)},`,\n type === 'module' && ` \"require\": ${JSON.stringify(requireExport)},`,\n ` \"default\": ${JSON.stringify(defaultExport)}`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].filter(isTruthy),\n )\n }\n }\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n if (!pkg.exports) {\n throw new Error(\n '\\n- ' +\n [\n 'package.json: `exports` are missing, please set a minimal configuration, for example:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": \"./src/index.js\",`,\n ` \"default\": \"./dist/index.js\"`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].join('\\n- '),\n )\n }\n\n const _exports = parseExports({pkg})\n\n if (strict && strictOptions.noPackageJsonTypings !== 'off' && 'typings' in pkg) {\n report(strictOptions.noPackageJsonTypings, 'package.json: `typings` should be `types`')\n }\n\n if (\n strict &&\n strictOptions.alwaysPackageJsonTypes !== 'off' &&\n !pkg.types &&\n typeof pkg.exports?.['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source?.endsWith('.ts')\n ) {\n report(\n strictOptions.alwaysPackageJsonTypes,\n 'package.json: `types` must be declared for the npm listing to show as a TypeScript module.',\n )\n }\n\n if (strict && !pkg.exports['./package.json']) {\n errors.push('package.json: `exports[\"./package.json\"] must be declared.')\n }\n\n for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {\n if (\n exportPath.endsWith('.json') ||\n (typeof exportEntry === 'string' && exportEntry.endsWith('.json'))\n ) {\n if (exportPath === './package.json') {\n if (exportEntry !== './package.json') {\n errors.push('package.json: `exports[\"./package.json\"]` must be \"./package.json\".')\n }\n }\n } else if (exportPath.endsWith('.css')) {\n if (typeof exportEntry === 'string' && !existsSync(resolvePath(cwd, exportEntry))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: file does not exist.`,\n )\n } else if (typeof exportEntry !== 'string') {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: export conditions not supported for CSS files.`,\n )\n }\n } else if (isRecord(exportEntry) && 'svelte' in exportEntry) {\n // @TODO should we report a warning or a debug message here about a detected svelte export that is ignored?\n } else if (isPkgExport(exportEntry)) {\n const exp = {\n _exported: true,\n _path: exportPath,\n ...exportEntry,\n } satisfies PkgExport & {_path: string}\n\n // Infer the `default` condition based on the `type` and other conditions\n if (!exp.default) {\n const fallback = type === 'module' ? exp.import : exp.require\n\n if (fallback) {\n exp.default = fallback\n }\n }\n\n // Infer the `require` condition based on the `type` and other conditions\n if (!exp.require && type === 'commonjs' && exp.default) {\n exp.require = exp.default\n }\n\n // Infer the `import` condition based on the `type` and other conditions\n if (!exp.import && type === 'module' && exp.default) {\n exp.import = exp.default\n }\n\n if (exportPath === '.') {\n if (exportEntry.require && pkg.main && exportEntry.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exportEntry.import && pkg.module && exportEntry.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\" These must be equal.',\n )\n }\n }\n } else if (!isRecord(exportEntry)) {\n errors.push('package.json: exports must be an object')\n }\n }\n\n errors.push(...validateExports(_exports, {pkg}))\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n return _exports\n}\n\nfunction isPkgExport(value: unknown): value is PkgExport {\n return isRecord(value) && 'source' in value && typeof value['source'] === 'string'\n}\n","import ts from 'typescript'\n\n/** @internal */\nexport async function loadTSConfig(options: {\n cwd: string\n tsconfigPath: string\n}): Promise<ts.ParsedCommandLine | undefined> {\n const {cwd, tsconfigPath} = options\n\n // oxlint-disable-next-line unbound-method\n const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath)\n\n if (!configPath) {\n return undefined\n }\n\n // oxlint-disable-next-line unbound-method\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n\n return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd)\n}\n","export function resolveBrowserTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter(\n (version) =>\n version.startsWith('chrome') ||\n version.startsWith('edge') ||\n version.startsWith('firefox') ||\n version.startsWith('ios') ||\n version.startsWith('safari') ||\n version.startsWith('opera'),\n )\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","export function resolveNodeTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter((version) => version.startsWith('node'))\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","import {errorMap} from 'zod-validation-error/v3'\nimport {z} from 'zod/v3'\n\nconst toggle = z.union([z.literal('error'), z.literal('warn'), z.literal('off')])\n\ntype ToggleType = 'error' | 'warn' | 'off'\n\nconst strictOptions = z\n .object({\n noPackageJsonTypings: toggle.default('error'),\n noImplicitSideEffects: toggle.default('warn'),\n noImplicitBrowsersList: toggle.default('warn'),\n alwaysPackageJsonTypes: toggle.default('error'),\n alwaysPackageJsonFiles: toggle.default('error'),\n noCheckTypes: toggle.default('warn'),\n noPackageJsonBrowser: toggle.default('warn'),\n noPackageJsonTypesVersions: toggle.default('warn'),\n preferModuleType: toggle.default('warn'),\n })\n .strict()\n\n/**\n * To make error message paths line up with the paths in package.config.ts the schema is hoisted into a root schema\n * This way errors will say `Expected boolean, received string at \"strict.noPackageJsonTypings\"` instead of `Expected boolean, received string at \"noPackageJsonTypings\"`.\n */\nconst validationSchema = z.object({\n strictOptions: strictOptions.default({}),\n})\n\n/**\n * @public\n */\nexport interface StrictOptions {\n /**\n * Disallows a top level `typings` field in `package.json` if it is equal to `exports['.'].source`.\n * @defaultValue 'error'\n */\n noPackageJsonTypings: ToggleType\n /**\n * Requires specifying `sideEffects` in `package.json`.\n * @defaultValue 'warn'\n */\n noImplicitSideEffects: ToggleType\n /**\n * Requires specifying `browserslist` in `package.json`, instead of relying on it implicitly being:\n * @example\n * ```\n * \"browserslist\": \"extends @sanity/browserslist-config\"\n * ```\n * @defaultValue 'warn'\n */\n noImplicitBrowsersList: ToggleType\n /**\n * If typescript is used then `types` in `package.json` should be specified for npm listings to show the TS icon.\n * @defaultValue 'error'\n */\n alwaysPackageJsonTypes: ToggleType\n /**\n * Using `.npmignore` is error prone, it's best practice to always declare `files` instead\n * @defaultValue 'error'\n */\n alwaysPackageJsonFiles: ToggleType\n /**\n * It's slow to perform type checking while generating dts files, so it's best practice to disable it with a `\"noCheck\": true` in the tsconfig.json file used by `package.config.ts`\n * @defaultValue 'warn'\n */\n noCheckTypes: ToggleType\n /**\n * Disallows the `browser` field in `package.json` as the `browser` condition in `exports` is better supported.\n * @defaultValue 'warn'\n */\n noPackageJsonBrowser: ToggleType\n /**\n * Disallows the `typesVersions` field in `package.json` as TypeScript has long supported conditional exports and the `types` condition.\n * @defaultValue 'warn'\n */\n noPackageJsonTypesVersions: ToggleType\n /**\n * Warns if `type` field is missing or set to `commonjs`. Future versions will require `\"type\": \"module\"`.\n * @defaultValue 'warn'\n */\n preferModuleType: ToggleType\n}\n\n/** @alpha */\nexport function parseStrictOptions(input: unknown): StrictOptions {\n return validationSchema.parse({strictOptions: input}, {errorMap}).strictOptions\n}\n","import path from 'node:path'\nimport type {PackageJSON} from '@sanity/parse-package-json'\nimport browserslistToEsbuild from 'browserslist-to-esbuild'\nimport {resolveConfigProperty} from './core/config/resolveConfigProperty.ts'\nimport {type PkgConfigOptions, type PkgExports, type PkgRuntime} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {DEFAULT_BROWSERSLIST_QUERY} from './core/defaults.ts'\nimport {findCommonDirPath, pathContains} from './core/findCommonPath.ts'\nimport {parseAndValidateExports} from './core/pkg/parseAndValidateExports.ts'\nimport {loadTSConfig} from './core/ts/loadTSConfig.ts'\nimport type {Logger} from './logger.ts'\nimport {resolveBrowserTarget} from './resolveBrowserTarget.ts'\nimport {resolveNodeTarget} from './resolveNodeTarget.ts'\nimport {parseStrictOptions} from './strict.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\nexport async function resolveBuildContext(options: {\n config?: PkgConfigOptions | undefined\n cwd: string\n emitDeclarationOnly?: boolean\n logger: Logger\n pkg: PackageJSON\n strict: boolean\n tsconfig: string\n}): Promise<BuildContext> {\n const {\n config,\n cwd,\n emitDeclarationOnly = false,\n logger,\n pkg,\n strict,\n tsconfig: tsconfigPath,\n } = options\n const tsconfig = await loadTSConfig({cwd, tsconfigPath})\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n\n if (strictOptions.noCheckTypes !== 'off' && tsconfig?.options && config?.dts !== 'rolldown') {\n if (tsconfig.options.noCheck !== false && !tsconfig.options.noCheck) {\n if (strictOptions.noCheckTypes === 'error') {\n throw new Error(\n '`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it.',\n )\n } else {\n logger.warn(\n '`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it.',\n )\n }\n }\n }\n\n let browserslist = pkg.browserslist\n if (!browserslist) {\n if (strict && strictOptions.noImplicitBrowsersList !== 'off') {\n if (strictOptions.noImplicitBrowsersList === 'error') {\n throw new Error(\n '\\n- ' +\n `package.json: \"browserslist\" is missing, set it to \\`\"browserslist\": \"extends @sanity/browserslist-config\"\\``,\n )\n } else {\n logger.warn(\n 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `\"browserslist\": \"extends @sanity/browserslist-config\"` to silence this warning.',\n )\n }\n }\n browserslist = DEFAULT_BROWSERSLIST_QUERY\n }\n const targetVersions = browserslistToEsbuild(browserslist)\n\n if (\n strict &&\n strictOptions.noImplicitSideEffects !== 'off' &&\n typeof pkg.sideEffects === 'undefined'\n ) {\n const msg =\n 'package.json: `sideEffects` is missing, see https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects for how to define `sideEffects`'\n\n if (strictOptions.noImplicitSideEffects === 'error') {\n throw new Error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n const nodeTarget = resolveNodeTarget(targetVersions)\n const webTarget = resolveBrowserTarget(targetVersions)\n\n if (!nodeTarget) {\n throw new Error('no matching `node` target')\n }\n\n if (!webTarget) {\n throw new Error('no matching `web` target')\n }\n\n const target: Record<PkgRuntime, string[]> = {\n '*': webTarget.concat(nodeTarget),\n 'browser': webTarget,\n 'node': nodeTarget,\n }\n\n const parsedExports = parseAndValidateExports({\n cwd,\n pkg,\n strict,\n strictOptions,\n logger,\n }).reduce<PkgExports>(\n (acc, {_path: exportPath, ...exportEntry}) => Object.assign(acc, {[exportPath]: exportEntry}),\n {},\n )\n\n const exports = resolveConfigProperty(config?.exports, parsedExports)\n\n const parsedExternal = [\n ...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),\n ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []),\n ]\n\n // Merge externals if an array is provided, replace if it's a function\n const external =\n config && Array.isArray(config.external)\n ? [...parsedExternal, ...config.external]\n : resolveConfigProperty(config?.external, parsedExternal)\n // Merge bundledPackages with dev deps, replace if it's a function\n const externalWithTypes = new Set([pkg.name, ...external, ...external.map(transformPackageName)])\n const bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(\n // Do not bundle anything that is marked as external\n (_) => !externalWithTypes.has(_),\n )\n const bundledPackages =\n config && Array.isArray(config.extract?.bundledPackages)\n ? [...bundledDependencies, ...config.extract.bundledPackages]\n : resolveConfigProperty(config?.extract?.bundledPackages, bundledDependencies)\n\n const outputPaths = Object.values(exports)\n .flatMap((exportEntry) => {\n return [\n exportEntry.import,\n exportEntry.require,\n exportEntry.browser?.import,\n exportEntry.browser?.require,\n exportEntry.node?.source && exportEntry.node.import,\n exportEntry.node?.source && exportEntry.node.require,\n ].filter(isTruthy)\n })\n .map((p) => path.resolve(cwd, p))\n\n const commonDistPath = findCommonDirPath(outputPaths)\n\n if (commonDistPath === cwd) {\n throw new Error(\n 'all output files must share a common parent directory which is not the root package directory',\n )\n }\n\n if (commonDistPath && !pathContains(cwd, commonDistPath)) {\n throw new Error('all output files must be located within the package')\n }\n\n const configDistPath = config?.dist ? path.resolve(cwd, config.dist) : undefined\n\n if (\n configDistPath &&\n commonDistPath &&\n configDistPath !== commonDistPath &&\n !pathContains(configDistPath, commonDistPath)\n ) {\n logger.log(`did you mean to configure \\`dist: './${path.relative(cwd, commonDistPath)}'\\`?`)\n\n throw new Error('all output files must be located with the configured `dist` path')\n }\n\n const distPath = configDistPath || commonDistPath\n\n if (!distPath) {\n throw new Error('could not detect `dist` path')\n }\n\n const ctx: BuildContext = {\n config,\n cwd,\n distPath,\n emitDeclarationOnly,\n exports,\n external,\n bundledPackages,\n files: [],\n logger,\n pkg,\n runtime: config?.runtime ?? '*',\n strict,\n target,\n ts: {\n config: tsconfig,\n configPath: tsconfigPath,\n },\n dts: config?.dts === 'rolldown' ? 'rolldown' : 'api-extractor',\n }\n\n return ctx\n}\n\nfunction transformPackageName(packageName: string): string {\n if (packageName.startsWith('@types/')) {\n // If it already starts with @types, return it as is\n return packageName\n } else if (packageName.startsWith('@')) {\n // Handle scoped packages\n const [scope, name] = packageName.split('/')\n\n return `@types/${scope?.slice(1)}__${name}`\n } else {\n // Handle regular packages\n return `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OAAO,IAAI,wCAAwC,KAAK,SAAS,KAAK,cAAc,CAAC,MAAM,GAErF,IAAI,MAAM,kEAAkE;AAGpF,QAAM,WAAW,kBAAkB;AAEnC,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,8BAA8B;AAwBhD,SArB0B;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAAA,SACAA;AAAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,CAAA;AAAA,IACP;AAAA,IACA;AAAA,IACA,SAAS,QAAQ,WAAW;AAAA,IAC5B,QAAAR;AAAA,IACA;AAAA,IACA,IAAI;AAAA,MACF,QAAQ;AAAA,MACR,YAAY;AAAA,IAAA;AAAA,IAEd,KAAK,QAAQ,QAAQ,aAAa,aAAa;AAAA,EAAA;AAInD;AAEA,SAAS,qBAAqB,aAA6B;AACzD,MAAI,YAAY,WAAW,SAAS;AAElC,WAAO;AACF,MAAI,YAAY,WAAW,GAAG,GAAG;AAEtC,UAAM,CAAC,OAAO,IAAI,IAAI,YAAY,MAAM,GAAG;AAE3C,WAAO,UAAU,OAAO,MAAM,CAAC,CAAC,KAAK,IAAI;AAAA,EAC3C;AAEE,WAAO,UAAU,WAAW;AAEhC;","x_google_ignoreList":[5]}
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { dts } from "rolldown-plugin-dts";
3
- import { pkgExtMap } from "./consoleSpy.js";
3
+ import { pkgExtMap } from "./resolveBuildContext.js";
4
4
  function resolveRolldownConfig(ctx, buildTask) {
5
5
  const { format, runtime } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
6
6
  Object.entries(ts.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts.config?.options.baseUrl || ".", val[0])])
@@ -1,5 +1,111 @@
1
- import { watch } from "./watch.js";
2
- import { handleError } from "./handleError.js";
1
+ import path from "node:path";
2
+ import { up } from "empathic/package";
3
+ import { switchMap } from "rxjs";
4
+ import { loadConfig } from "./defaults.js";
5
+ import { getTargetPaths, loadPkgWithReporting, resolveBuildContext } from "./resolveBuildContext.js";
6
+ import { createLogger, handleError } from "./handleError.js";
7
+ import { watchTaskHandlers } from "./index.js";
8
+ function resolveWatchTasks(ctx) {
9
+ const { pkg, target } = ctx, tasks = [], exports$1 = Object.entries(ctx.exports || {}).map(
10
+ ([_path, exp]) => ({ _path, ...exp })
11
+ ), dtsTask = {
12
+ type: "watch:dts",
13
+ entries: []
14
+ }, rollupTasks = {};
15
+ function addRollupTaskEntry(format, runtime, entry) {
16
+ const buildId = `${format}:${runtime}`;
17
+ rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
18
+ type: "watch:js",
19
+ buildId,
20
+ entries: [entry],
21
+ runtime,
22
+ format,
23
+ target: target[runtime]
24
+ };
25
+ }
26
+ for (const exp of exports$1) {
27
+ const importId = path.join(pkg.name, exp._path);
28
+ exp.source?.endsWith(".ts") && dtsTask.entries.push({
29
+ importId,
30
+ exportPath: exp._path,
31
+ sourcePath: exp.source,
32
+ targetPaths: getTargetPaths(pkg.type, exp)
33
+ }), exp.browser?.source?.endsWith(".ts") && dtsTask.entries.push({
34
+ importId,
35
+ exportPath: exp._path,
36
+ sourcePath: exp.browser.source,
37
+ targetPaths: getTargetPaths(pkg.type, exp.browser)
38
+ }), exp.node?.source?.endsWith(".ts") && dtsTask.entries.push({
39
+ importId,
40
+ exportPath: exp._path,
41
+ sourcePath: exp.node.source,
42
+ targetPaths: getTargetPaths(pkg.type, exp.node)
43
+ });
44
+ }
45
+ for (const exp of exports$1) {
46
+ const output = exp.require;
47
+ output && addRollupTaskEntry("commonjs", ctx.runtime, {
48
+ path: exp._path,
49
+ source: exp.source,
50
+ output
51
+ });
52
+ }
53
+ for (const exp of exports$1) {
54
+ const output = exp.browser?.require;
55
+ output && addRollupTaskEntry("commonjs", "browser", {
56
+ path: exp._path,
57
+ source: exp.browser?.source || exp.source,
58
+ output
59
+ });
60
+ }
61
+ for (const exp of exports$1) {
62
+ const output = exp.import;
63
+ output && addRollupTaskEntry("esm", ctx.runtime, {
64
+ path: exp._path,
65
+ source: exp.source,
66
+ output
67
+ });
68
+ }
69
+ for (const exp of exports$1) {
70
+ const output = exp.browser?.import;
71
+ output && addRollupTaskEntry("esm", "browser", {
72
+ path: exp._path,
73
+ source: exp.browser?.source || exp.source,
74
+ output
75
+ });
76
+ }
77
+ return dtsTask.entries.length && tasks.push(dtsTask), tasks.push(...Object.values(rollupTasks)), tasks;
78
+ }
79
+ async function watch(options) {
80
+ const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger(), { watchConfigFiles } = await import("./watchConfigFiles.js");
81
+ (await watchConfigFiles({ cwd, logger })).pipe(
82
+ switchMap(async (configFiles) => {
83
+ const packageJsonPath = configFiles.map((f) => path.relative(cwd, f)).find((f) => f === "package.json"), pkgPath = up({ cwd });
84
+ if (!packageJsonPath || !pkgPath)
85
+ throw new Error("missing package.json", { cause: { cwd } });
86
+ const config = await loadConfig({ cwd, pkgPath }), { parseStrictOptions } = await import("./resolveBuildContext.js").then(function(n) {
87
+ return n.strict;
88
+ }), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({ pkgPath, logger, strict, strictOptions }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json";
89
+ return resolveBuildContext({ config, cwd, logger, pkg, strict, tsconfig });
90
+ })
91
+ ).subscribe(async (ctx) => {
92
+ const watchTasks = resolveWatchTasks(ctx);
93
+ for (const task of watchTasks) {
94
+ const handler = watchTaskHandlers[task.type];
95
+ handler.exec(ctx, task).subscribe({
96
+ error: (err) => {
97
+ ctx.logger.error(err), ctx.logger.log(), process.exit(1);
98
+ },
99
+ next: (result) => {
100
+ handler.complete(ctx, task, result);
101
+ },
102
+ complete: () => {
103
+ ctx.logger.success(handler.name(ctx, task)), ctx.logger.log();
104
+ }
105
+ });
106
+ }
107
+ });
108
+ }
3
109
  async function watchAction(options) {
4
110
  try {
5
111
  await watch({