@sanity/pkg-utils 7.4.1-canary.0 → 7.5.1-canary.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 (75) hide show
  1. package/dist/_chunks-cjs/index.cjs +2022 -260
  2. package/dist/_chunks-cjs/index.cjs.map +1 -1
  3. package/dist/_chunks-es/build.js +106 -17
  4. package/dist/_chunks-es/build.js.map +1 -1
  5. package/dist/_chunks-es/check.js +125 -37
  6. package/dist/_chunks-es/check.js.map +1 -1
  7. package/dist/_chunks-es/consoleSpy.js +541 -0
  8. package/dist/_chunks-es/consoleSpy.js.map +1 -0
  9. package/dist/_chunks-es/index.js +774 -180
  10. package/dist/_chunks-es/index.js.map +1 -1
  11. package/dist/_chunks-es/init.js +493 -9
  12. package/dist/_chunks-es/init.js.map +1 -1
  13. package/dist/_chunks-es/{logger.js → isRecord.js} +15 -2
  14. package/dist/_chunks-es/isRecord.js.map +1 -0
  15. package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
  16. package/dist/_chunks-es/spinner.js +16 -0
  17. package/dist/_chunks-es/spinner.js.map +1 -0
  18. package/dist/_chunks-es/watch.js +115 -9
  19. package/dist/_chunks-es/watch.js.map +1 -1
  20. package/dist/cli.d.ts +1 -1
  21. package/dist/cli.js +1 -1
  22. package/dist/index.d.cts +421 -487
  23. package/dist/index.d.ts +421 -487
  24. package/dist/index.js +7 -4
  25. package/dist/index.js.map +1 -1
  26. package/package.json +3 -2
  27. package/dist/_chunks-cjs/findConfigFile.cjs +0 -24
  28. package/dist/_chunks-cjs/findConfigFile.cjs.map +0 -1
  29. package/dist/_chunks-cjs/index2.cjs +0 -781
  30. package/dist/_chunks-cjs/index2.cjs.map +0 -1
  31. package/dist/_chunks-cjs/index3.cjs +0 -50
  32. package/dist/_chunks-cjs/index3.cjs.map +0 -1
  33. package/dist/_chunks-cjs/printPackageTree.cjs +0 -42
  34. package/dist/_chunks-cjs/printPackageTree.cjs.map +0 -1
  35. package/dist/_chunks-cjs/resolveBuildContext.cjs +0 -176
  36. package/dist/_chunks-cjs/resolveBuildContext.cjs.map +0 -1
  37. package/dist/_chunks-cjs/resolveBuildTasks.cjs +0 -111
  38. package/dist/_chunks-cjs/resolveBuildTasks.cjs.map +0 -1
  39. package/dist/_chunks-cjs/resolveConfigProperty.cjs +0 -6
  40. package/dist/_chunks-cjs/resolveConfigProperty.cjs.map +0 -1
  41. package/dist/_chunks-cjs/resolveWatchTasks.cjs +0 -79
  42. package/dist/_chunks-cjs/resolveWatchTasks.cjs.map +0 -1
  43. package/dist/_chunks-cjs/template.cjs +0 -446
  44. package/dist/_chunks-cjs/template.cjs.map +0 -1
  45. package/dist/_chunks-cjs/validatePkg.cjs +0 -71
  46. package/dist/_chunks-cjs/validatePkg.cjs.map +0 -1
  47. package/dist/_chunks-cjs/watchConfigFiles.cjs +0 -59
  48. package/dist/_chunks-cjs/watchConfigFiles.cjs.map +0 -1
  49. package/dist/_chunks-es/fileExists.js +0 -12
  50. package/dist/_chunks-es/fileExists.js.map +0 -1
  51. package/dist/_chunks-es/findConfigFile.js +0 -23
  52. package/dist/_chunks-es/findConfigFile.js.map +0 -1
  53. package/dist/_chunks-es/index2.js +0 -769
  54. package/dist/_chunks-es/index2.js.map +0 -1
  55. package/dist/_chunks-es/index3.js +0 -51
  56. package/dist/_chunks-es/index3.js.map +0 -1
  57. package/dist/_chunks-es/loadPkgWithReporting.js +0 -100
  58. package/dist/_chunks-es/loadPkgWithReporting.js.map +0 -1
  59. package/dist/_chunks-es/logger.js.map +0 -1
  60. package/dist/_chunks-es/printPackageTree.js +0 -44
  61. package/dist/_chunks-es/printPackageTree.js.map +0 -1
  62. package/dist/_chunks-es/resolveBuildContext.js +0 -177
  63. package/dist/_chunks-es/resolveBuildContext.js.map +0 -1
  64. package/dist/_chunks-es/resolveBuildTasks.js +0 -109
  65. package/dist/_chunks-es/resolveBuildTasks.js.map +0 -1
  66. package/dist/_chunks-es/resolveConfigProperty.js +0 -7
  67. package/dist/_chunks-es/resolveConfigProperty.js.map +0 -1
  68. package/dist/_chunks-es/resolveWatchTasks.js +0 -77
  69. package/dist/_chunks-es/resolveWatchTasks.js.map +0 -1
  70. package/dist/_chunks-es/template.js +0 -449
  71. package/dist/_chunks-es/template.js.map +0 -1
  72. package/dist/_chunks-es/validatePkg.js +0 -72
  73. package/dist/_chunks-es/validatePkg.js.map +0 -1
  74. package/dist/_chunks-es/watchConfigFiles.js +0 -45
  75. package/dist/_chunks-es/watchConfigFiles.js.map +0 -1
@@ -1,781 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __copyProps = (to, from, except, desc) => {
8
- if (from && typeof from == "object" || typeof from == "function")
9
- for (let key of __getOwnPropNames(from))
10
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- return to;
12
- };
13
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
14
- // If the importer is in node compatibility mode or this is not an ESM
15
- // file that has been converted to a CommonJS file using a Babel-
16
- // compatible transform (i.e. "__esModule" has not been set), then set
17
- // "default" to the CommonJS "module.exports" for node compatibility.
18
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
- mod
20
- ));
21
- var chalk = require("chalk"), rxjs = require("rxjs"), path = require("node:path"), rimraf = require("rimraf"), ts = require("typescript"), fs = require("node:fs/promises"), apiExtractor = require("@microsoft/api-extractor"), mkdirp = require("mkdirp"), prettier = require("prettier"), node_module = require("node:module"), tsdocConfig = require("@microsoft/tsdoc-config"), jsoncParser = require("jsonc-parser"), recast = require("recast"), typeScriptParser = require("recast/parsers/typescript.js"), index = require("./index.cjs"), rollup = require("rollup"), rollupPlugin = require("@optimize-lodash/rollup-plugin"), alias = require("@rollup/plugin-alias"), pluginBabel = require("@rollup/plugin-babel"), commonjs = require("@rollup/plugin-commonjs"), json = require("@rollup/plugin-json"), pluginNodeResolve = require("@rollup/plugin-node-resolve"), replace = require("@rollup/plugin-replace"), terser = require("@rollup/plugin-terser"), esbuild = require("rollup-plugin-esbuild"), resolveConfigProperty = require("./resolveConfigProperty.cjs"), _documentCurrentScript = typeof document < "u" ? document.currentScript : null;
22
- function _interopDefaultCompat(e) {
23
- return e && typeof e == "object" && "default" in e ? e : { default: e };
24
- }
25
- function _interopNamespaceCompat(e) {
26
- if (e && typeof e == "object" && "default" in e) return e;
27
- var n = /* @__PURE__ */ Object.create(null);
28
- return e && Object.keys(e).forEach(function(k) {
29
- if (k !== "default") {
30
- var d = Object.getOwnPropertyDescriptor(e, k);
31
- Object.defineProperty(n, k, d.get ? d : {
32
- enumerable: !0,
33
- get: function() {
34
- return e[k];
35
- }
36
- });
37
- }
38
- }), n.default = e, Object.freeze(n);
39
- }
40
- var chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), path__default = /* @__PURE__ */ _interopDefaultCompat(path), rimraf__namespace = /* @__PURE__ */ _interopNamespaceCompat(rimraf), ts__default = /* @__PURE__ */ _interopDefaultCompat(ts), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs), prettier__namespace = /* @__PURE__ */ _interopNamespaceCompat(prettier), typeScriptParser__default = /* @__PURE__ */ _interopDefaultCompat(typeScriptParser), alias__default = /* @__PURE__ */ _interopDefaultCompat(alias), commonjs__default = /* @__PURE__ */ _interopDefaultCompat(commonjs), json__default = /* @__PURE__ */ _interopDefaultCompat(json), replace__default = /* @__PURE__ */ _interopDefaultCompat(replace), terser__default = /* @__PURE__ */ _interopDefaultCompat(terser), esbuild__default = /* @__PURE__ */ _interopDefaultCompat(esbuild);
41
- function printExtractMessages(ctx, messages) {
42
- const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
43
- warnings.length && logger.log();
44
- for (const msg of warnings) {
45
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
46
- msg.messageId !== "TS6307" && logger.log(
47
- [
48
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
49
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
50
- ` - ${chalk__default.default.yellow("warning")} ${chalk__default.default.gray(msg.messageId)}
51
- `,
52
- msg.text,
53
- `
54
- `
55
- ].join("")
56
- );
57
- }
58
- const errors = messages.filter((msg) => msg.logLevel === "error");
59
- !warnings.length && errors.length && logger.log("");
60
- for (const msg of errors) {
61
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
62
- logger.log(
63
- [
64
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
65
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
66
- ` - ${chalk__default.default.red("error")} ${chalk__default.default.gray(msg.messageId)}
67
- `,
68
- msg.text,
69
- `
70
- `
71
- ].join("")
72
- );
73
- }
74
- errors.length && process.exit(1);
75
- }
76
- function printDiagnostic(options) {
77
- const { cwd, logger, diagnostic } = options;
78
- if (diagnostic.file && diagnostic.start) {
79
- const { line, character } = ts__default.default.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
80
- `), file = path__default.default.relative(cwd, diagnostic.file.fileName), output = [
81
- `${chalk__default.default.yellow(file)}:${chalk__default.default.blue(line + 1)}:${chalk__default.default.blue(character + 1)} - `,
82
- `${chalk__default.default.gray(`TS${diagnostic.code}:`)} ${message}`
83
- ].join("");
84
- diagnostic.category === ts__default.default.DiagnosticCategory.Error && logger.error(output), diagnostic.category === ts__default.default.DiagnosticCategory.Warning && logger.warn(output), diagnostic.category === ts__default.default.DiagnosticCategory.Message && logger.log(output), diagnostic.category === ts__default.default.DiagnosticCategory.Suggestion && logger.log(output);
85
- } else
86
- logger.log(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
87
- `));
88
- }
89
- async function buildTypes(options) {
90
- const { cwd, logger, outDir, tsconfig, strict = !1 } = options, compilerOptions = {
91
- ...tsconfig.options,
92
- declaration: !0,
93
- declarationDir: outDir,
94
- emitDeclarationOnly: !0,
95
- noEmit: !1,
96
- noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
97
- outDir
98
- }, program = ts__default.default.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts__default.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
99
- for (const diagnostic of allDiagnostics)
100
- printDiagnostic({ cwd, logger, diagnostic });
101
- if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts__default.default.DiagnosticCategory.Error).length)
102
- throw new Error("failed to compile TypeScript definitions");
103
- }
104
- class DtsError extends Error {
105
- messages;
106
- constructor(message, messages) {
107
- super(message), this.messages = messages;
108
- }
109
- }
110
- function createApiExtractorConfig(options) {
111
- const {
112
- bundledPackages,
113
- distPath,
114
- exportPath,
115
- filePath,
116
- messages,
117
- projectFolder,
118
- mainEntryPointFilePath,
119
- tsconfig,
120
- tsconfigPath,
121
- dtsRollupEnabled
122
- } = options;
123
- return {
124
- apiReport: {
125
- enabled: !1,
126
- reportFileName: "<unscopedPackageName>.api.md"
127
- },
128
- bundledPackages,
129
- // If `paths` are used for self-referencing imports (e.g. the module is named `sanity`, and the `sanity/structure` export is also importing from `sanity/router`),
130
- compiler: tsconfig.options.paths ? {
131
- overrideTsconfig: {
132
- extends: tsconfigPath,
133
- compilerOptions: {
134
- // An empty object replaces whatever is in the original tsconfig file
135
- paths: {}
136
- }
137
- }
138
- } : { tsconfigFilePath: tsconfigPath },
139
- docModel: {
140
- enabled: !1,
141
- apiJsonFilePath: path__default.default.resolve(distPath, `${exportPath}.api.json`)
142
- },
143
- dtsRollup: {
144
- enabled: dtsRollupEnabled,
145
- untrimmedFilePath: path__default.default.resolve(distPath, filePath)
146
- // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
147
- // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
148
- },
149
- tsdocMetadata: {
150
- enabled: !1
151
- },
152
- messages,
153
- mainEntryPointFilePath,
154
- projectFolder
155
- };
156
- }
157
- const require$1 = node_module.createRequire(typeof document > "u" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("_chunks-cjs/index2.cjs", document.baseURI).href);
158
- async function createTSDocConfig(opts) {
159
- const { customTags } = opts;
160
- if (customTags.length === 0)
161
- return;
162
- const tsDocBaseBuf = await fs.readFile(
163
- require$1.resolve("@microsoft/api-extractor/extends/tsdoc-base.json")
164
- ), tsDocBaseConfig = jsoncParser.parse(tsDocBaseBuf.toString()), tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(
165
- customTags.map((t) => ({
166
- tagName: `@${t.name}`,
167
- syntaxKind: t.syntaxKind,
168
- allowMultiple: t.allowMultiple
169
- }))
170
- ), supportForTags = { ...tsDocBaseConfig.supportForTags };
171
- for (const customTag of customTags)
172
- supportForTags[`@${customTag.name}`] = !0;
173
- return tsdocConfig.TSDocConfigFile.loadFromObject({
174
- ...tsDocBaseConfig,
175
- noStandardTags: !1,
176
- tagDefinitions,
177
- supportForTags
178
- });
179
- }
180
- async function extractModuleBlocksFromTypes({
181
- tsOutDir,
182
- extractResult
183
- }) {
184
- const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
185
- for (const sourceFile of sourceFiles)
186
- sourceFile.text.includes("declare module") && moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
187
- return moduleBlocks;
188
- }
189
- function extractModuleBlocks(fileContent) {
190
- return recast.parse(fileContent, {
191
- parser: typeScriptParser__default.default
192
- }).program.body.filter((node) => node.type === "TSModuleDeclaration").map((node) => recast.print(node).code);
193
- }
194
- async function extractTypes(options) {
195
- const {
196
- bundledPackages,
197
- customTags,
198
- distPath,
199
- exportPath,
200
- files,
201
- filePaths,
202
- projectPath,
203
- rules,
204
- sourceTypesPath,
205
- tmpPath,
206
- tsconfig,
207
- tsconfigPath,
208
- extractorDisabled
209
- } = options, tsdocConfigFile = await createTSDocConfig({
210
- customTags: customTags || []
211
- }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = apiExtractor.ExtractorConfig.prepare({
212
- configObject: createApiExtractorConfig({
213
- bundledPackages,
214
- distPath,
215
- exportPath,
216
- filePath,
217
- messages: index.getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
218
- projectFolder: projectPath,
219
- mainEntryPointFilePath: sourceTypesPath,
220
- tsconfig,
221
- tsconfigPath,
222
- dtsRollupEnabled: !0
223
- }),
224
- configObjectFullPath: void 0,
225
- tsdocConfigFile,
226
- packageJsonFullPath: path__default.default.resolve(projectPath, "package.json")
227
- }), messages = [], extractorResult = apiExtractor.Extractor.invoke(extractorConfig, {
228
- // Equivalent to the "--local" command-line parameter
229
- localBuild: !0,
230
- // Equivalent to the "--verbose" command-line parameter
231
- showVerboseMessages: !0,
232
- // handle messages
233
- messageCallback(message) {
234
- messages.push(message), message.handled = !0;
235
- }
236
- }), typesPath = path__default.default.resolve(distPath, filePath), typesBuf = await fs__default.default.readFile(typesPath), prettierConfig = await prettier__namespace.resolveConfig(typesPath);
237
- await mkdirp.mkdirp(path__default.default.dirname(typesPath));
238
- const moduleBlocks = await extractModuleBlocksFromTypes({
239
- extractResult: extractorResult,
240
- tsOutDir: tmpPath
241
- }), code = [typesBuf.toString(), ...moduleBlocks].join(`
242
-
243
- `), prettyCode = await prettier__namespace.format(code, {
244
- ...prettierConfig,
245
- filepath: typesPath
246
- });
247
- for (const expFilePath of filePaths) {
248
- const expTypesPath = path__default.default.resolve(distPath, expFilePath);
249
- await fs__default.default.writeFile(expTypesPath, prettyCode), files.push({
250
- type: "types",
251
- path: expTypesPath
252
- });
253
- }
254
- return shouldCleanUpDts && await fs__default.default.unlink(typesPath), { extractorResult, messages };
255
- }
256
- async function doExtract(ctx, task) {
257
- const { config, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
258
- if (!ts2.config || !ts2.configPath)
259
- return { type: "dts", messages: [], results: [] };
260
- const { outDir, rootDir = cwd } = ts2.config.options;
261
- if (!outDir)
262
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
263
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
264
- await buildTypes({ cwd, logger, outDir: tmpPath, strict, tsconfig: ts2.config });
265
- const messages = [], results = [];
266
- for (const entry of task.entries) {
267
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
268
- tmpPath,
269
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
270
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath)), result = await extractTypes({
271
- bundledPackages: bundledPackages || [],
272
- customTags: config?.extract?.customTags,
273
- distPath: outDir,
274
- exportPath,
275
- files,
276
- filePaths,
277
- projectPath: cwd,
278
- rules: config?.extract?.rules,
279
- sourceTypesPath,
280
- tsconfig: ts2.config,
281
- tmpPath,
282
- tsconfigPath: path__default.default.resolve(cwd, ts2.configPath || "tsconfig.json"),
283
- extractorDisabled: config?.extract?.enabled === !1
284
- });
285
- messages.push(...result.messages);
286
- const errors = result.messages.filter((msg) => msg.logLevel === "error");
287
- if (errors.length > 0)
288
- throw await rimraf.rimraf(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
289
- results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
290
- }
291
- return await rimraf.rimraf(tmpPath), { type: "dts", messages, results };
292
- }
293
- const dtsTask = {
294
- name: (ctx, task) => [
295
- `Build type definitions with ${chalk__default.default.bold(ctx.dts)}...`,
296
- " entries:",
297
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
298
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
299
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
300
- ].join("")).join(`
301
- `))
302
- ].join(`
303
- `),
304
- exec: (ctx, task) => new rxjs.Observable((observer) => {
305
- doExtract(ctx, task).then((result) => {
306
- observer.next(result), observer.complete();
307
- }).catch((err) => {
308
- observer.error(err);
309
- });
310
- }),
311
- complete: (ctx, _task, result) => {
312
- printExtractMessages(ctx, result.messages);
313
- },
314
- error: (ctx, _task, err) => {
315
- const { logger } = ctx;
316
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
317
- }
318
- }, dtsWatchTask = {
319
- name: (_ctx, task) => [
320
- "build type definitions",
321
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
322
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
323
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
324
- ].join("")))
325
- ].join(`
326
- `),
327
- exec: (ctx, task) => {
328
- const { config, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
329
- return new rxjs.Observable((observer) => {
330
- if (!tsContext.config || !tsContext.configPath) {
331
- observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
332
- return;
333
- }
334
- const { outDir, rootDir = cwd } = tsContext.config.options;
335
- if (!outDir) {
336
- observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`"));
337
- return;
338
- }
339
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
340
- buildTypes({
341
- cwd,
342
- logger,
343
- outDir: tmpPath,
344
- tsconfig: tsContext.config,
345
- strict
346
- }).catch((err) => {
347
- observer.error(err);
348
- });
349
- const host = ts__default.default.createWatchCompilerHost(
350
- tsContext.configPath,
351
- {
352
- ...tsContext.config.options,
353
- declaration: !0,
354
- declarationDir: tmpPath,
355
- emitDeclarationOnly: !0,
356
- noEmit: !1,
357
- noEmitOnError: strict ? !0 : tsContext.config.options.noEmitOnError ?? !0,
358
- outDir: tmpPath
359
- },
360
- ts__default.default.sys,
361
- ts__default.default.createEmitAndSemanticDiagnosticsBuilderProgram,
362
- (diagnostic) => {
363
- logger.error(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
364
- `));
365
- },
366
- (diagnostic) => {
367
- logger.info(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
368
- `));
369
- }
370
- ), origPostProgramCreate = host.afterProgramCreate;
371
- host.afterProgramCreate = async (program) => {
372
- origPostProgramCreate?.(program);
373
- const messages = [], results = [];
374
- for (const entry of task.entries) {
375
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
376
- tmpPath,
377
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
378
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath));
379
- try {
380
- const result = await extractTypes({
381
- bundledPackages: bundledPackages || [],
382
- customTags: config?.extract?.customTags,
383
- cwd,
384
- distPath: outDir,
385
- exportPath,
386
- files,
387
- filePaths,
388
- projectPath: cwd,
389
- rules: config?.extract?.rules,
390
- sourceTypesPath,
391
- tsconfig: tsContext.config,
392
- tmpPath,
393
- tsconfigPath: path__default.default.resolve(cwd, tsContext.configPath || "tsconfig.json"),
394
- extractorDisabled: config?.extract?.enabled === !1
395
- });
396
- messages.push(...result.messages), results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
397
- } catch (err) {
398
- if (err instanceof DtsError)
399
- messages.push(...err.messages);
400
- else {
401
- observer.error(err);
402
- return;
403
- }
404
- }
405
- }
406
- observer.next({ type: "dts", messages, results });
407
- };
408
- const watchProgram = ts__default.default.createWatchProgram(host);
409
- return () => {
410
- watchProgram.close(), rimraf__namespace.sync(tmpPath);
411
- };
412
- });
413
- },
414
- complete: (ctx, task, result) => {
415
- const { logger } = ctx;
416
- printExtractMessages(ctx, result.messages), logger.success(
417
- `build type definitions
418
- ${task.entries.map(
419
- (entry) => ` - ${chalk__default.default.cyan(entry.importId)}: ${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(entry.targetPaths.join(", "))}`
420
- ).join(`
421
- `)}`
422
- ), logger.log("");
423
- },
424
- error: (ctx, _task, err) => {
425
- const { logger } = ctx;
426
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
427
- }
428
- }, rolldownDtsTask = {
429
- name: (ctx, task) => {
430
- const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk__default.default.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
431
- " bundles:",
432
- ...bundleEntries.map(
433
- (e) => [
434
- " - ",
435
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
436
- ].join("")
437
- )
438
- ] : [], entriesLines = entries.length ? [
439
- " entries:",
440
- ...entries.map(
441
- (e) => [
442
- " - ",
443
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
444
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
445
- ].join("")
446
- )
447
- ] : [];
448
- return [
449
- `Build type definitions with ${chalk__default.default.bold("rolldown")}...`,
450
- ` format: ${chalk__default.default.yellow(task.format)}`,
451
- ...targetLines,
452
- ...bundlesLines,
453
- ...entriesLines
454
- ].join(`
455
- `);
456
- },
457
- exec: (ctx, task) => rxjs.from(execPromise$1(ctx, task)),
458
- complete: () => {
459
- },
460
- error: (_ctx, _task, err) => {
461
- console.error(err);
462
- }
463
- };
464
- async function execPromise$1(ctx, task) {
465
- const [{ rolldown }, { resolveRolldownConfig }] = await Promise.all([
466
- import("rolldown"),
467
- Promise.resolve().then(function() {
468
- return require("./resolveRolldownConfig.cjs");
469
- })
470
- ]), { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = index.createConsoleSpy({
471
- onRestored: (messages) => {
472
- for (const msg of messages) {
473
- const text = String(msg.args[0]);
474
- msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
475
- }
476
- }
477
- });
478
- try {
479
- const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
480
- ...inputOptions,
481
- onwarn(warning) {
482
- consoleSpy.messages.push({
483
- type: "warn",
484
- code: warning.code,
485
- args: [warning.message]
486
- });
487
- }
488
- }), { output } = await bundle.generate(outputOptions);
489
- for (const chunkOrAsset of output)
490
- chunkOrAsset.type === "asset" ? files.push({
491
- type: "asset",
492
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
493
- }) : files.push({
494
- type: "chunk",
495
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
496
- });
497
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
498
- } catch (err) {
499
- throw consoleSpy.restore(), err;
500
- }
501
- }
502
- function replaceFileEnding(path2) {
503
- switch (!0) {
504
- case path2.endsWith(".mjs"):
505
- return path2.replace(/\.mjs$/, ".d.mts");
506
- case path2.endsWith(".cjs"):
507
- return path2.replace(/\.cjs$/, ".d.cts");
508
- default:
509
- return path2.replace(/\.js$/, ".d.ts");
510
- }
511
- }
512
- function resolveRollupConfig(ctx, buildTask) {
513
- const { format, runtime, target } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = index.pkgExtMap[pkg.type || "commonjs"][format], minify = config?.minify ?? !1, outDir = path__default.default.relative(cwd, distPath), pathAliases = Object.fromEntries(
514
- Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path__default.default.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
515
- ), entries = buildTask.entries.map((entry) => ({
516
- ...entry,
517
- name: path__default.default.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
518
- }), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path__default.default.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path__default.default.resolve(cwd, e.source)), replacements = Object.fromEntries(
519
- Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
520
- ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, defaultPlugins = [
521
- replace__default.default({
522
- preventAssignment: !0,
523
- values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
524
- "process.env.PKG_FILE_PATH": (arg) => {
525
- const sourcePath = `./${path__default.default.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
526
- return entry ? JSON.stringify(
527
- path__default.default.relative(cwd, path__default.default.resolve(outDir, entry.name + outputExt))
528
- ) : (console.error(`could not find source entry: ${sourcePath}`), "null");
529
- },
530
- "process.env.PKG_FORMAT": JSON.stringify(format),
531
- "process.env.PKG_RUNTIME": JSON.stringify(runtime),
532
- "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
533
- ...replacements
534
- }
535
- }),
536
- alias__default.default({
537
- entries: { ...pathAliases }
538
- }),
539
- pluginNodeResolve.nodeResolve({
540
- browser: runtime === "browser",
541
- extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
542
- preferBuiltins: !0
543
- }),
544
- commonjs__default.default(),
545
- json__default.default(),
546
- (config?.babel?.reactCompiler || config?.babel?.styledComponents) && pluginBabel.babel({
547
- babelrc: !1,
548
- presets: ["@babel/preset-typescript"],
549
- babelHelpers: "bundled",
550
- extensions: [".ts", ".tsx", ".js", ".jsx"],
551
- plugins: [
552
- // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
553
- config?.babel?.styledComponents && [
554
- "babel-plugin-styled-components",
555
- {
556
- // Unnecessary, as the way we use styled-components in Sanity is usually by wrapping `@sanity/ui` primitives, not declaring new ones like "const Button = styled.button``"
557
- fileName: !1,
558
- // Native template literals take less space than this transpilation
559
- transpileTemplateLiterals: !1,
560
- // Massively helps dead code elimination and tree-shaking
561
- pure: !0,
562
- // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
563
- cssProp: !1,
564
- ...typeof config.babel.styledComponents == "object" ? config.babel.styledComponents : {}
565
- }
566
- ],
567
- config?.babel?.reactCompiler && [
568
- "babel-plugin-react-compiler",
569
- config?.reactCompilerOptions || {}
570
- ]
571
- ].filter(Boolean)
572
- }),
573
- esbuild__default.default({
574
- jsx: config?.jsx ?? "automatic",
575
- jsxFactory: config?.jsxFactory ?? "createElement",
576
- jsxFragment: config?.jsxFragment ?? "Fragment",
577
- jsxImportSource: config?.jsxImportSource ?? "react",
578
- target,
579
- tsconfig: ctx.ts.configPath || "tsconfig.json",
580
- treeShaking: !0,
581
- minifySyntax: config?.minify !== !1,
582
- supported: {
583
- "template-literal": !0
584
- }
585
- }),
586
- Array.isArray(config?.babel?.plugins) && pluginBabel.getBabelOutputPlugin({
587
- babelrc: !1,
588
- plugins: config.babel.plugins
589
- }),
590
- enableOptimizeLodash && rollupPlugin.optimizeLodashImports({
591
- useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
592
- ...typeof config?.rollup?.optimizeLodash == "boolean" ? {} : config?.rollup?.optimizeLodash
593
- }),
594
- minify && terser__default.default({
595
- compress: { directives: !1, passes: 10 },
596
- ecma: 2020,
597
- output: {
598
- comments: (_node, comment) => {
599
- const text = comment.value;
600
- return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
601
- },
602
- preserve_annotations: !0
603
- }
604
- })
605
- ].filter(Boolean), userPlugins = config?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty.resolveConfigProperty(config?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
606
- return {
607
- inputOptions: {
608
- context: cwd,
609
- external: (id, importer) => {
610
- if (exportIds?.includes(id))
611
- return !0;
612
- if (importer && (id.startsWith(".") || id.startsWith("/"))) {
613
- const idPath = path__default.default.resolve(path__default.default.dirname(importer), id);
614
- if (sourcePaths?.includes(idPath))
615
- return logger.warn(
616
- `detected self-referencing import \u2013 treating as external: ${path__default.default.relative(
617
- cwd,
618
- idPath
619
- )}`
620
- ), !0;
621
- }
622
- const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
623
- return !!(name && external.includes(name));
624
- },
625
- input: entries.reduce(
626
- (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
627
- {}
628
- ),
629
- watch: {
630
- chokidar: {
631
- usePolling: !0
632
- }
633
- },
634
- plugins,
635
- treeshake: {
636
- preset: "recommended",
637
- propertyReadSideEffects: !1,
638
- moduleSideEffects: "no-external",
639
- ...config?.rollup?.treeshake
640
- },
641
- experimentalLogSideEffects: config?.rollup?.experimentalLogSideEffects
642
- },
643
- outputOptions: {
644
- chunkFileNames,
645
- compact: minify,
646
- dir: outDir,
647
- entryFileNames,
648
- esModule: !0,
649
- format,
650
- interop: "compat",
651
- sourcemap: config?.sourcemap ?? !0,
652
- hoistTransitiveImports: !1,
653
- minifyInternalExports: minify,
654
- ...config?.rollup?.output
655
- }
656
- };
657
- }
658
- function hasDependency(pkg, packageName) {
659
- return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
660
- }
661
- const rollupTask = {
662
- name: (ctx, task) => {
663
- const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk__default.default.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
664
- " bundles:",
665
- ...bundleEntries.map(
666
- (e) => [
667
- " - ",
668
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
669
- ].join("")
670
- )
671
- ] : [], entriesLines = entries.length ? [
672
- " entries:",
673
- ...entries.map(
674
- (e) => [
675
- " - ",
676
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
677
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
678
- ].join("")
679
- )
680
- ] : [];
681
- return [
682
- "Build javascript files...",
683
- ` format: ${chalk__default.default.yellow(task.format)}`,
684
- ...targetLines,
685
- ...bundlesLines,
686
- ...entriesLines
687
- ].join(`
688
- `);
689
- },
690
- exec: (ctx, task) => new rxjs.Observable((observer) => {
691
- execPromise(ctx, task).then((result) => {
692
- observer.next(result), observer.complete();
693
- }).catch((err) => observer.error(err));
694
- }),
695
- complete: () => {
696
- },
697
- error: (_ctx, _task, err) => {
698
- console.error(err);
699
- }
700
- };
701
- async function execPromise(ctx, task) {
702
- const { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = index.createConsoleSpy({
703
- onRestored: (messages) => {
704
- for (const msg of messages) {
705
- const text = String(msg.args[0]);
706
- msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
707
- }
708
- }
709
- });
710
- try {
711
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup.rollup({
712
- ...inputOptions,
713
- onwarn(warning) {
714
- consoleSpy.messages.push({
715
- type: "warn",
716
- code: warning.code,
717
- args: [warning.message]
718
- });
719
- }
720
- }), { output } = await bundle.generate(outputOptions);
721
- for (const chunkOrAsset of output)
722
- chunkOrAsset.type === "asset" ? files.push({
723
- type: "asset",
724
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
725
- }) : files.push({
726
- type: "chunk",
727
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
728
- });
729
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
730
- } catch (err) {
731
- throw consoleSpy.restore(), err;
732
- }
733
- }
734
- const rollupWatchTask = {
735
- name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
736
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
737
- `)}`,
738
- exec: (ctx, task) => {
739
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
740
- return new rxjs.Observable((observer) => {
741
- const watchOptions = {
742
- ...inputOptions,
743
- output: outputOptions
744
- }, watcher = rollup.watch(watchOptions);
745
- return watcher.on("event", (event) => {
746
- observer.next(event);
747
- }), () => {
748
- watcher.close();
749
- };
750
- });
751
- },
752
- complete: (ctx, task, event) => {
753
- const { logger } = ctx;
754
- if (event.code === "BUNDLE_END") {
755
- logger.success(
756
- `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
757
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
758
- `)}`
759
- ), logger.log("");
760
- return;
761
- }
762
- if (event.code !== "BUNDLE_START" && event.code !== "END" && event.code === "ERROR") {
763
- logger.error(event.code, event);
764
- return;
765
- }
766
- },
767
- error: (ctx, _task, err) => {
768
- const { logger } = ctx;
769
- err instanceof Error && logger.log(err);
770
- }
771
- }, buildTaskHandlers = {
772
- "build:dts": dtsTask,
773
- "build:js": rollupTask,
774
- "rolldown:dts": rolldownDtsTask
775
- }, watchTaskHandlers = {
776
- "watch:dts": dtsWatchTask,
777
- "watch:js": rollupWatchTask
778
- };
779
- exports.buildTaskHandlers = buildTaskHandlers;
780
- exports.watchTaskHandlers = watchTaskHandlers;
781
- //# sourceMappingURL=index2.cjs.map