@sanity/pkg-utils 5.1.0 → 5.1.1

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.js CHANGED
@@ -142,10 +142,6 @@ async function loadPkg(options2) {
142
142
  const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
143
143
  return validatePkg(raw), raw;
144
144
  }
145
- function assertFirst(a, arr) {
146
- const aIdx = arr.indexOf(a);
147
- return aIdx === -1 ? !0 : aIdx === 0;
148
- }
149
145
  function assertLast(a, arr) {
150
146
  const aIdx = arr.indexOf(a);
151
147
  return aIdx === -1 ? !0 : aIdx === arr.length - 1;
@@ -165,7 +161,9 @@ async function loadPkgWithReporting(options2) {
165
161
  if (typeof exp == "string" || "svelte" in exp)
166
162
  continue;
167
163
  const keys = Object.keys(exp);
168
- assertFirst("types", keys) || (shouldError = !0, logger.error(`exports["${expPath}"]: the \`types\` property should be the first property`)), exp.module && (shouldError = !0, logger.error(
164
+ exp.types && (shouldError = !0, logger.error(
165
+ `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`
166
+ )), exp.module && (shouldError = !0, logger.error(
169
167
  `exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
170
168
  )), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
171
169
  `exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
@@ -222,7 +220,6 @@ function parseExports(options2) {
222
220
  const { extMap, pkg, strict } = options2, rootExport = {
223
221
  _exported: !0,
224
222
  _path: ".",
225
- types: pkg.types,
226
223
  source: pkg.source || "",
227
224
  browser: pkg.browser && {
228
225
  source: pkg.source || "",
@@ -233,7 +230,9 @@ function parseExports(options2) {
233
230
  import: pkg.module,
234
231
  default: pkg.module || pkg.main || ""
235
232
  }, extraExports = [], errors = [];
236
- if (pkg.exports) {
233
+ if (strict && !pkg.types && pkg.source?.endsWith(".ts") && errors.push(
234
+ "package.json: `types` must be declared for the npm listing to show as a TypeScript module."
235
+ ), strict && "typings" in pkg && errors.push("package.json: `typings` should be `types`"), pkg.exports) {
237
236
  strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
238
237
  for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
239
238
  if (exportPath.endsWith(".json"))
@@ -245,8 +244,6 @@ function parseExports(options2) {
245
244
  'package.json: mismatch between "main" and "exports.require". These must be equal.'
246
245
  ), exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import && errors.push(
247
246
  'package.json: mismatch between "module" and "exports.import" These must be equal.'
248
- ), exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types && errors.push(
249
- 'package.json: mismatch between "types" and "exports.types". These must be equal.'
250
247
  ), exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source && errors.push(
251
248
  'package.json: mismatch between "source" and "exports.source". These must be equal.'
252
249
  ), Object.assign(rootExport, exportEntry);
@@ -491,6 +488,25 @@ async function resolveBuildContext(options2) {
491
488
  }
492
489
  };
493
490
  }
491
+ const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
492
+ function getTargetPaths(_type, expOrBundle) {
493
+ const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
494
+ return expOrBundle?.import && set.add(expOrBundle.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)), expOrBundle?.require && set.add(expOrBundle.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)), isPkgExport(expOrBundle) && (expOrBundle.browser?.source || (expOrBundle.browser?.import && set.add(
495
+ expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
496
+ ), expOrBundle.browser?.require && set.add(
497
+ expOrBundle.browser.require.replace(
498
+ fileEnding,
499
+ type === "commonjs" ? dtsEnding : ctsEnding
500
+ )
501
+ )), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
502
+ expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
503
+ ), expOrBundle.node?.require && set.add(
504
+ expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
505
+ ))), Array.from(set);
506
+ }
507
+ function isPkgExport(exp) {
508
+ return exp?.browser || exp?.node || exp?.default;
509
+ }
494
510
  function resolveBuildTasks(ctx) {
495
511
  const { config: config2, cwd, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports = Object.entries(ctx.exports || {}).map(
496
512
  ([_path, exp]) => ({ _path, ...exp })
@@ -511,13 +527,33 @@ function resolveBuildTasks(ctx) {
511
527
  }
512
528
  for (const exp of exports) {
513
529
  const importId = path$1.join(pkg.name, exp._path);
514
- exp.types && dtsTask2.entries.push({
530
+ exp.source?.endsWith(".ts") && dtsTask2.entries.push({
515
531
  importId,
516
532
  exportPath: exp._path,
517
533
  sourcePath: exp.source,
518
- targetPath: exp.types
534
+ targetPaths: getTargetPaths(pkg.type, exp)
535
+ }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
536
+ importId,
537
+ exportPath: exp._path,
538
+ sourcePath: exp.browser.source,
539
+ targetPaths: getTargetPaths(pkg.type, exp.browser)
540
+ }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
541
+ importId,
542
+ exportPath: exp._path,
543
+ sourcePath: exp.node.source,
544
+ targetPaths: getTargetPaths(pkg.type, exp.node)
519
545
  });
520
546
  }
547
+ for (const bundle of bundles)
548
+ if (bundle.source?.endsWith(".ts")) {
549
+ const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path$1.join(pkg.name, exportPath);
550
+ dtsTask2.entries.push({
551
+ importId,
552
+ exportPath,
553
+ sourcePath: bundle.source,
554
+ targetPaths: getTargetPaths(pkg.type, bundle)
555
+ });
556
+ }
521
557
  if (dtsTask2.entries.length && tasks.push(dtsTask2), !ctx.emitDeclarationOnly) {
522
558
  for (const exp of exports) {
523
559
  const output = exp.require;
@@ -20180,7 +20216,7 @@ async function extractTypes(options2) {
20180
20216
  distPath,
20181
20217
  exportPath,
20182
20218
  files,
20183
- filePath,
20219
+ filePaths,
20184
20220
  projectPath,
20185
20221
  rules,
20186
20222
  sourceTypesPath,
@@ -20189,7 +20225,7 @@ async function extractTypes(options2) {
20189
20225
  tsconfigPath
20190
20226
  } = options2, tsdocConfigFile = await createTSDocConfig({
20191
20227
  customTags: customTags || []
20192
- }), extractorConfig = ExtractorConfig.prepare({
20228
+ }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = ExtractorConfig.prepare({
20193
20229
  configObject: createApiExtractorConfig({
20194
20230
  bundledPackages,
20195
20231
  distPath,
@@ -20220,17 +20256,18 @@ async function extractTypes(options2) {
20220
20256
  tsOutDir: tmpPath
20221
20257
  }), code = [typesBuf.toString(), ...moduleBlocks].join(`
20222
20258
 
20223
- `);
20224
- return await fs.writeFile(
20225
- typesPath,
20226
- await prettier.format(code, {
20227
- ...prettierConfig,
20228
- filepath: typesPath
20229
- })
20230
- ), files.push({
20231
- type: "types",
20232
- path: typesPath
20233
- }), { extractorResult, messages };
20259
+ `), prettyCode = await prettier.format(code, {
20260
+ ...prettierConfig,
20261
+ filepath: typesPath
20262
+ });
20263
+ for (const expFilePath of filePaths) {
20264
+ const expTypesPath = path$1.resolve(distPath, expFilePath);
20265
+ await fs.writeFile(expTypesPath, prettyCode), files.push({
20266
+ type: "types",
20267
+ path: expTypesPath
20268
+ });
20269
+ }
20270
+ return shouldCleanUpDts && await fs.unlink(typesPath), { extractorResult, messages };
20234
20271
  }
20235
20272
  async function doExtract(ctx, task) {
20236
20273
  const { config: config2, cwd, files, logger, strict, ts: ts2 } = ctx;
@@ -20246,14 +20283,14 @@ async function doExtract(ctx, task) {
20246
20283
  const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path$1.resolve(
20247
20284
  tmpPath,
20248
20285
  path$1.relative(rootDir, path$1.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
20249
- ), targetPath = path$1.resolve(cwd, entry.targetPath), filePath = path$1.relative(outDir, targetPath), result = await extractTypes({
20286
+ ), targetPaths = entry.targetPaths.map((targetPath) => path$1.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path$1.relative(outDir, targetPath)), result = await extractTypes({
20250
20287
  bundledPackages: config2?.extract?.bundledPackages || [],
20251
20288
  customTags: config2?.extract?.customTags,
20252
20289
  cwd,
20253
20290
  distPath: outDir,
20254
20291
  exportPath,
20255
20292
  files,
20256
- filePath,
20293
+ filePaths,
20257
20294
  projectPath: cwd,
20258
20295
  rules: config2?.extract?.rules,
20259
20296
  sourceTypesPath,
@@ -20265,7 +20302,7 @@ async function doExtract(ctx, task) {
20265
20302
  const errors = result.messages.filter((msg) => msg.logLevel === "error");
20266
20303
  if (errors.length > 0)
20267
20304
  throw await rimraf(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
20268
- results.push({ sourcePath: path$1.resolve(cwd, entry.sourcePath), filePath: targetPath });
20305
+ results.push({ sourcePath: path$1.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
20269
20306
  }
20270
20307
  return await rimraf(tmpPath), { type: "dts", messages, results };
20271
20308
  }
@@ -20273,12 +20310,11 @@ const dtsTask = {
20273
20310
  name: (_ctx, task) => [
20274
20311
  "Build type definitions...",
20275
20312
  " entries:",
20276
- ...task.entries.map(
20277
- (entry) => [
20278
- ` - ${chalk.cyan(entry.importId)}: `,
20279
- `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(entry.targetPath)}`
20280
- ].join("")
20281
- )
20313
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
20314
+ ` - ${chalk.cyan(entry.importId)}: `,
20315
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
20316
+ ].join("")).join(`
20317
+ `))
20282
20318
  ].join(`
20283
20319
  `),
20284
20320
  exec: (ctx, task) => new Observable((observer) => {
@@ -20298,9 +20334,10 @@ const dtsTask = {
20298
20334
  }, dtsWatchTask = {
20299
20335
  name: (_ctx, task) => [
20300
20336
  "build type definitions",
20301
- ...task.entries.map(
20302
- (entry) => ` ${chalk.blue(entry.importId)}: ${entry.sourcePath} -> ${entry.targetPath}`
20303
- )
20337
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
20338
+ ` - ${chalk.cyan(entry.importId)}: `,
20339
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
20340
+ ].join("")))
20304
20341
  ].join(`
20305
20342
  `),
20306
20343
  exec: (ctx, task) => new Observable((observer) => {
@@ -20615,7 +20652,6 @@ function printPackageTree(ctx) {
20615
20652
  tree.exports = Object.fromEntries(
20616
20653
  Object.entries(exports).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
20617
20654
  const exp = {
20618
- types: void 0,
20619
20655
  source: fileInfo(entry.source),
20620
20656
  browser: void 0,
20621
20657
  require: void 0,
@@ -20623,7 +20659,7 @@ function printPackageTree(ctx) {
20623
20659
  import: void 0,
20624
20660
  default: fileInfo(entry.default)
20625
20661
  };
20626
- return entry.types ? exp.types = fileInfo(entry.types) : delete exp.types, entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path$1.join(pkg.name, exportPath)), exp];
20662
+ return entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path$1.join(pkg.name, exportPath)), exp];
20627
20663
  })
20628
20664
  ), logger.log(treeify.asTree(tree, !0, !0));
20629
20665
  }
@@ -20632,8 +20668,8 @@ async function check(options2) {
20632
20668
  if (printPackageTree(ctx), strict) {
20633
20669
  const missingFiles = [];
20634
20670
  for (const [, exp] of Object.entries(ctx.exports || {}))
20635
- exp.source && !fileExists(path$1.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path$1.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path$1.resolve(cwd, exp.import)) && missingFiles.push(exp.import), exp.types && !fileExists(path$1.resolve(cwd, exp.types)) && missingFiles.push(exp.types);
20636
- missingFiles.length && (logger.error("missing files"), process.exit(1));
20671
+ exp.source && !fileExists(path$1.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path$1.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path$1.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
20672
+ ctx.pkg.types && !fileExists(path$1.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
20637
20673
  const exportPaths = {
20638
20674
  require: [],
20639
20675
  import: []
@@ -20899,9 +20935,7 @@ const RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/
20899
20935
  }, pkgJson.bugs = {
20900
20936
  url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
20901
20937
  }, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
20902
- pkgJson.types = "./dist/index.d.ts";
20903
- const mainExport = pkgJson.exports?.["."];
20904
- isRecord(mainExport) && (mainExport.types = "./dist/index.d.ts"), pkgJson.scripts = {
20938
+ pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
20905
20939
  ...pkgJson.scripts,
20906
20940
  "ts:check": "tsc --build"
20907
20941
  };
@@ -21213,11 +21247,21 @@ function resolveWatchTasks(ctx) {
21213
21247
  }
21214
21248
  for (const exp of exports) {
21215
21249
  const importId = path$1.join(pkg.name, exp._path);
21216
- exp.types && dtsTask2.entries.push({
21250
+ exp.source?.endsWith(".ts") && dtsTask2.entries.push({
21217
21251
  importId,
21218
21252
  exportPath: exp._path,
21219
21253
  sourcePath: exp.source,
21220
- targetPath: exp.types
21254
+ targetPaths: getTargetPaths(pkg.type, exp)
21255
+ }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
21256
+ importId,
21257
+ exportPath: exp._path,
21258
+ sourcePath: exp.browser.source,
21259
+ targetPaths: getTargetPaths(pkg.type, exp.browser)
21260
+ }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
21261
+ importId,
21262
+ exportPath: exp._path,
21263
+ sourcePath: exp.node.source,
21264
+ targetPaths: getTargetPaths(pkg.type, exp.node)
21221
21265
  });
21222
21266
  }
21223
21267
  for (const exp of exports) {