@sanity/pkg-utils 7.4.0-canary.2 → 7.4.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 (70) hide show
  1. package/dist/_chunks-cjs/findConfigFile.cjs +24 -0
  2. package/dist/_chunks-cjs/findConfigFile.cjs.map +1 -0
  3. package/dist/_chunks-cjs/index.cjs +231 -1910
  4. package/dist/_chunks-cjs/index.cjs.map +1 -1
  5. package/dist/_chunks-cjs/index2.cjs +781 -0
  6. package/dist/_chunks-cjs/index2.cjs.map +1 -0
  7. package/dist/_chunks-cjs/index3.cjs +50 -0
  8. package/dist/_chunks-cjs/index3.cjs.map +1 -0
  9. package/dist/_chunks-cjs/printPackageTree.cjs +42 -0
  10. package/dist/_chunks-cjs/printPackageTree.cjs.map +1 -0
  11. package/dist/_chunks-cjs/resolveBuildContext.cjs +176 -0
  12. package/dist/_chunks-cjs/resolveBuildContext.cjs.map +1 -0
  13. package/dist/_chunks-cjs/resolveBuildTasks.cjs +111 -0
  14. package/dist/_chunks-cjs/resolveBuildTasks.cjs.map +1 -0
  15. package/dist/_chunks-cjs/resolveConfigProperty.cjs +6 -0
  16. package/dist/_chunks-cjs/resolveConfigProperty.cjs.map +1 -0
  17. package/dist/_chunks-cjs/resolveWatchTasks.cjs +79 -0
  18. package/dist/_chunks-cjs/resolveWatchTasks.cjs.map +1 -0
  19. package/dist/_chunks-cjs/template.cjs +446 -0
  20. package/dist/_chunks-cjs/template.cjs.map +1 -0
  21. package/dist/_chunks-cjs/validatePkg.cjs +71 -0
  22. package/dist/_chunks-cjs/validatePkg.cjs.map +1 -0
  23. package/dist/_chunks-cjs/watchConfigFiles.cjs +59 -0
  24. package/dist/_chunks-cjs/watchConfigFiles.cjs.map +1 -0
  25. package/dist/_chunks-es/build.js +7 -107
  26. package/dist/_chunks-es/build.js.map +1 -1
  27. package/dist/_chunks-es/check.js +23 -44
  28. package/dist/_chunks-es/check.js.map +1 -1
  29. package/dist/_chunks-es/fileExists.js +12 -0
  30. package/dist/_chunks-es/fileExists.js.map +1 -0
  31. package/dist/_chunks-es/findConfigFile.js +23 -0
  32. package/dist/_chunks-es/findConfigFile.js.map +1 -0
  33. package/dist/_chunks-es/index.js +180 -754
  34. package/dist/_chunks-es/index.js.map +1 -1
  35. package/dist/_chunks-es/index2.js +769 -0
  36. package/dist/_chunks-es/index2.js.map +1 -0
  37. package/dist/_chunks-es/index3.js +51 -0
  38. package/dist/_chunks-es/index3.js.map +1 -0
  39. package/dist/_chunks-es/init.js +9 -493
  40. package/dist/_chunks-es/init.js.map +1 -1
  41. package/dist/_chunks-es/loadPkgWithReporting.js +100 -0
  42. package/dist/_chunks-es/loadPkgWithReporting.js.map +1 -0
  43. package/dist/_chunks-es/{isRecord.js → logger.js} +2 -15
  44. package/dist/_chunks-es/logger.js.map +1 -0
  45. package/dist/_chunks-es/printPackageTree.js +44 -0
  46. package/dist/_chunks-es/printPackageTree.js.map +1 -0
  47. package/dist/_chunks-es/resolveBuildContext.js +177 -0
  48. package/dist/_chunks-es/resolveBuildContext.js.map +1 -0
  49. package/dist/_chunks-es/resolveBuildTasks.js +109 -0
  50. package/dist/_chunks-es/resolveBuildTasks.js.map +1 -0
  51. package/dist/_chunks-es/resolveConfigProperty.js +7 -0
  52. package/dist/_chunks-es/resolveConfigProperty.js.map +1 -0
  53. package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
  54. package/dist/_chunks-es/resolveWatchTasks.js +77 -0
  55. package/dist/_chunks-es/resolveWatchTasks.js.map +1 -0
  56. package/dist/_chunks-es/template.js +449 -0
  57. package/dist/_chunks-es/template.js.map +1 -0
  58. package/dist/_chunks-es/validatePkg.js +72 -0
  59. package/dist/_chunks-es/validatePkg.js.map +1 -0
  60. package/dist/_chunks-es/watch.js +9 -115
  61. package/dist/_chunks-es/watch.js.map +1 -1
  62. package/dist/_chunks-es/watchConfigFiles.js +45 -0
  63. package/dist/_chunks-es/watchConfigFiles.js.map +1 -0
  64. package/dist/cli.js +1 -1
  65. package/dist/index.js +4 -7
  66. package/dist/index.js.map +1 -1
  67. package/package.json +2 -2
  68. package/dist/_chunks-es/consoleSpy.js +0 -541
  69. package/dist/_chunks-es/consoleSpy.js.map +0 -1
  70. package/dist/_chunks-es/isRecord.js.map +0 -1
@@ -18,58 +18,25 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
18
18
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
19
  mod
20
20
  ));
21
- var path = require("node:path"), rimraf = require("rimraf"), node_module = require("node:module"), node = require("esbuild-register/dist/node"), pkgUp = require("pkg-up"), findConfig = require("find-config"), node_fs = require("node:fs"), chalk = require("chalk"), zod = require("zod"), fs = require("node:fs/promises"), browserslist = require("browserslist"), config$1 = require("@sanity/browserslist-config"), ts = require("typescript"), zodValidationError = require("zod-validation-error"), rxjs = require("rxjs"), apiExtractor = require("@microsoft/api-extractor"), mkdirp = require("mkdirp"), prettier = require("prettier"), tsdocConfig = require("@microsoft/tsdoc-config"), jsoncParser = require("jsonc-parser"), recast = require("recast"), typeScriptParser = require("recast/parsers/typescript.js"), 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"), esbuild$1 = require("esbuild"), treeify = require("treeify"), prettyBytes = require("pretty-bytes"), prompts = require("prompts"), node_child_process = require("node:child_process"), getLatestVersion = require("get-latest-version"), gitUrlParse = require("git-url-parse"), outdent = require("outdent"), operators = require("rxjs/operators"), globby = require("globby"), chokidar = require("chokidar"), _documentCurrentScript = typeof document < "u" ? document.currentScript : null;
21
+ var path = require("node:path"), rimraf = require("rimraf"), node_module = require("node:module"), chalk = require("chalk"), zod = require("zod"), fs = require("node:fs/promises"), node_fs = require("node:fs"), config = require("@sanity/browserslist-config"), zodValidationError = require("zod-validation-error"), rxjs = require("rxjs"), _documentCurrentScript = typeof document < "u" ? document.currentScript : null;
22
22
  function _interopDefaultCompat(e) {
23
23
  return e && typeof e == "object" && "default" in e ? e : { default: e };
24
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 path__default = /* @__PURE__ */ _interopDefaultCompat(path), rimraf__namespace = /* @__PURE__ */ _interopNamespaceCompat(rimraf), pkgUp__default = /* @__PURE__ */ _interopDefaultCompat(pkgUp), findConfig__default = /* @__PURE__ */ _interopDefaultCompat(findConfig), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs), browserslist__default = /* @__PURE__ */ _interopDefaultCompat(browserslist), config__default = /* @__PURE__ */ _interopDefaultCompat(config$1), ts__default = /* @__PURE__ */ _interopDefaultCompat(ts), 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), esbuild__default$1 = /* @__PURE__ */ _interopDefaultCompat(esbuild$1), treeify__default = /* @__PURE__ */ _interopDefaultCompat(treeify), prettyBytes__default = /* @__PURE__ */ _interopDefaultCompat(prettyBytes), prompts__default = /* @__PURE__ */ _interopDefaultCompat(prompts), getLatestVersion__default = /* @__PURE__ */ _interopDefaultCompat(getLatestVersion), gitUrlParse__default = /* @__PURE__ */ _interopDefaultCompat(gitUrlParse), globby__default = /* @__PURE__ */ _interopDefaultCompat(globby), chokidar__namespace = /* @__PURE__ */ _interopNamespaceCompat(chokidar);
41
- function fileExists(filePath) {
42
- try {
43
- return node_fs.statSync(filePath), !0;
44
- } catch {
45
- return !1;
46
- }
47
- }
48
- const CONFIG_FILE_NAMES = [
49
- "package.config.ts",
50
- "package.config.js",
51
- "package.config.cjs",
52
- "package.config.mjs"
53
- ];
54
- function findConfigFile(cwd) {
55
- const pkgJsonPath = findConfig__default.default("package.json", { cwd });
56
- if (!pkgJsonPath) return;
57
- const pkgPath = path__default.default.dirname(pkgJsonPath);
58
- for (const fileName of CONFIG_FILE_NAMES) {
59
- const configPath = path__default.default.resolve(pkgPath, fileName);
60
- if (fileExists(configPath))
61
- return configPath;
62
- }
63
- }
64
- const require$2 = node_module.createRequire(typeof document > "u" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("_chunks-cjs/index.cjs", document.baseURI).href);
25
+ var path__default = /* @__PURE__ */ _interopDefaultCompat(path), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs), config__default = /* @__PURE__ */ _interopDefaultCompat(config);
65
26
  async function loadConfig(options) {
66
- const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
27
+ const [{ register }, { default: pkgUp }, { findConfigFile }] = await Promise.all([
28
+ import("esbuild-register/dist/node"),
29
+ import("pkg-up"),
30
+ Promise.resolve().then(function() {
31
+ return require("./findConfigFile.cjs");
32
+ })
33
+ ]), { cwd } = options, pkgPath = await pkgUp({ cwd });
67
34
  if (!pkgPath) return;
68
35
  const root = path__default.default.dirname(pkgPath), configFile = await findConfigFile(root);
69
36
  if (!configFile || !configFile.startsWith(cwd))
70
37
  return;
71
38
  const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] }, { unregister } = globalThis.__DEV__ ? { unregister: () => {
72
- } } : node.register(esbuildOptions), mod = require$2(configFile);
39
+ } } : register(esbuildOptions), mod = node_module.createRequire(typeof document > "u" ? require("url").pathToFileURL(__filename).href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("_chunks-cjs/index.cjs", document.baseURI).href)(configFile);
73
40
  return unregister(), mod?.default || mod || void 0;
74
41
  }
75
42
  function assertLast(a, arr) {
@@ -80,75 +47,13 @@ function assertOrder(a, b, arr) {
80
47
  const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
81
48
  return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
82
49
  }
83
- const pkgSchema = zod.z.object({
84
- type: zod.z.optional(zod.z.enum(["commonjs", "module"])),
85
- name: zod.z.string(),
86
- version: zod.z.string(),
87
- license: zod.z.string(),
88
- bin: zod.z.optional(zod.z.record(zod.z.string())),
89
- dependencies: zod.z.optional(zod.z.record(zod.z.string())),
90
- devDependencies: zod.z.optional(zod.z.record(zod.z.string())),
91
- peerDependencies: zod.z.optional(zod.z.record(zod.z.string())),
92
- source: zod.z.optional(zod.z.string()),
93
- main: zod.z.optional(zod.z.string()),
94
- browser: zod.z.optional(zod.z.record(zod.z.string())),
95
- module: zod.z.optional(zod.z.string()),
96
- types: zod.z.optional(zod.z.string()),
97
- exports: zod.z.optional(
98
- zod.z.record(
99
- zod.z.union([
100
- zod.z.custom((val) => /^\.\/.*\.json$/.test(val)),
101
- zod.z.custom((val) => /^\.\/.*\.css$/.test(val)),
102
- zod.z.object({
103
- types: zod.z.optional(zod.z.string()),
104
- source: zod.z.optional(zod.z.string()),
105
- browser: zod.z.optional(
106
- zod.z.object({
107
- source: zod.z.string(),
108
- import: zod.z.optional(zod.z.string()),
109
- require: zod.z.optional(zod.z.string())
110
- })
111
- ),
112
- node: zod.z.optional(
113
- zod.z.object({
114
- source: zod.z.optional(zod.z.string()),
115
- import: zod.z.optional(zod.z.string()),
116
- require: zod.z.optional(zod.z.string())
117
- })
118
- ),
119
- import: zod.z.optional(zod.z.string()),
120
- require: zod.z.optional(zod.z.string()),
121
- default: zod.z.string()
122
- }),
123
- zod.z.object({
124
- types: zod.z.optional(zod.z.string()),
125
- svelte: zod.z.string(),
126
- default: zod.z.optional(zod.z.string())
127
- })
128
- ])
129
- )
130
- ),
131
- browserslist: zod.z.optional(zod.z.union([zod.z.string(), zod.z.array(zod.z.string())])),
132
- sideEffects: zod.z.optional(zod.z.union([zod.z.boolean(), zod.z.array(zod.z.string())])),
133
- // @TODO type this properly
134
- typesVersions: zod.z.optional(zod.z.any())
135
- }), typoMap = /* @__PURE__ */ new Map();
136
- for (const key of pkgSchema.keyof()._def.values)
137
- typoMap.set(key.toUpperCase(), key);
138
- function validatePkg(input) {
139
- const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
140
- const needle = key.toUpperCase();
141
- return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
142
- });
143
- if (invalidKey)
144
- throw new TypeError(
145
- `
146
- - package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
147
- );
148
- return pkg;
149
- }
150
50
  async function loadPkg(options) {
151
- const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
51
+ const [{ default: pkgUp }, { validatePkg }] = await Promise.all([
52
+ import("pkg-up"),
53
+ Promise.resolve().then(function() {
54
+ return require("./validatePkg.cjs");
55
+ })
56
+ ]), { cwd } = options, pkgPath = await pkgUp({ cwd });
152
57
  if (!pkgPath) throw new Error("no package.json found");
153
58
  const buf = await fs__default.default.readFile(pkgPath), raw = JSON.parse(buf.toString());
154
59
  return validatePkg(raw), raw;
@@ -230,56 +135,166 @@ function createLogger() {
230
135
  }
231
136
  };
232
137
  }
233
- function browserslistToEsbuild(browserslistConfig, options = {}) {
234
- if (!browserslistConfig) {
235
- const path2 = process.cwd();
236
- browserslistConfig = browserslist__default.default.loadConfig({ path: path2, ...options });
138
+ function createSpinner(msg) {
139
+ const startTime = Date.now();
140
+ return console.log(msg), {
141
+ complete: () => {
142
+ console.log(`${chalk__default.default.green("[success]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
143
+ },
144
+ error: () => {
145
+ console.log(`${chalk__default.default.red("[error]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
146
+ }
147
+ };
148
+ }
149
+ async function build(options) {
150
+ const [{ resolveBuildContext }, { resolveBuildTasks }, { buildTaskHandlers }] = await Promise.all([
151
+ Promise.resolve().then(function() {
152
+ return require("./resolveBuildContext.cjs");
153
+ }),
154
+ Promise.resolve().then(function() {
155
+ return require("./resolveBuildTasks.cjs");
156
+ }),
157
+ Promise.resolve().then(function() {
158
+ return require("./index2.cjs");
159
+ })
160
+ ]), {
161
+ cwd,
162
+ emitDeclarationOnly,
163
+ strict = !1,
164
+ tsconfig: tsconfigOption,
165
+ clean = !1
166
+ } = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
167
+ config: config2,
168
+ cwd,
169
+ emitDeclarationOnly,
170
+ logger,
171
+ pkg,
172
+ strict,
173
+ tsconfig
174
+ });
175
+ clean && (logger.log(
176
+ `Deleting the \`dist\` folder: './${path__default.default.relative(cwd, ctx.distPath)}' before building...`
177
+ ), await rimraf.rimraf(ctx.distPath));
178
+ const buildTasks = resolveBuildTasks(ctx);
179
+ for (const task of buildTasks) {
180
+ const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName);
181
+ try {
182
+ const result = await handler.exec(ctx, task).toPromise();
183
+ spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
184
+ } catch (err) {
185
+ if (spinner.error(), err instanceof Error) {
186
+ const RE_CWD = new RegExp(`${cwd}`, "g");
187
+ ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
188
+ }
189
+ handler.error(ctx, task, err), process.exit(1);
190
+ }
237
191
  }
238
- const SUPPORTED_ESBUILD_TARGETS = [
239
- "es",
240
- "chrome",
241
- "edge",
242
- "firefox",
243
- "ios",
244
- "node",
245
- "safari",
246
- "opera",
247
- "ie"
248
- ], UNSUPPORTED = ["android 4"], replaces = {
249
- ios_saf: "ios",
250
- android: "chrome"
251
- }, separator = " ";
252
- return browserslist__default.default(browserslistConfig, options).filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u))).map((b) => b === "safari TP" ? browserslist__default.default("last 1 safari version")[0] : b).map((b) => b.split(separator)).map((b) => (replaces[b[0]] && (b[0] = replaces[b[0]]), b)).map((b) => (b[1].includes("-") && (b[1] = b[1].slice(0, b[1].indexOf("-"))), b)).map((b) => (b[1].endsWith(".0") && (b[1] = b[1].slice(0, -2)), b)).filter((b) => /^\d+(\.\d+)*$/.test(b[1])).filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0])).reduce((acc, b) => {
253
- const existingIndex = acc.findIndex((br) => br[0] === b[0]);
254
- return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
255
- }, []).map((b) => b.join(""));
256
192
  }
257
- function resolveConfigProperty(prop, initialValue) {
258
- return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
193
+ function createConsoleSpy(options) {
194
+ const { onRestored } = options || {}, original = {
195
+ log: console.log,
196
+ warn: console.warn,
197
+ error: console.error
198
+ }, messages = [];
199
+ 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 }), {
200
+ messages,
201
+ restore: () => {
202
+ console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
203
+ }
204
+ };
259
205
  }
260
- const DEFAULT_BROWSERSLIST_QUERY = config__default.default;
261
- function pathContains(containerPath, itemPath) {
262
- return !path__default.default.relative(containerPath, itemPath).startsWith("..");
206
+ function fileExists(filePath) {
207
+ try {
208
+ return node_fs.statSync(filePath), !0;
209
+ } catch {
210
+ return !1;
211
+ }
263
212
  }
264
- function findCommonDirPath(filePaths) {
265
- let ret;
266
- for (const filePath of filePaths) {
267
- let dirPath = path__default.default.dirname(filePath);
268
- if (!ret) {
269
- ret = dirPath;
270
- continue;
271
- }
272
- for (; dirPath !== ret && (dirPath = path__default.default.dirname(dirPath), dirPath !== ret); ) {
273
- if (pathContains(dirPath, ret)) {
274
- ret = dirPath;
275
- break;
213
+ async function check(options) {
214
+ const [{ resolveBuildContext }, { printPackageTree }] = await Promise.all([
215
+ Promise.resolve().then(function() {
216
+ return require("./resolveBuildContext.cjs");
217
+ }),
218
+ Promise.resolve().then(function() {
219
+ return require("./printPackageTree.cjs");
220
+ })
221
+ ]), { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
222
+ if (printPackageTree(ctx), strict) {
223
+ const missingFiles = [];
224
+ for (const [, exp] of Object.entries(ctx.exports || {}))
225
+ exp.source && !fileExists(path__default.default.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path__default.default.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path__default.default.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
226
+ ctx.pkg.types && !fileExists(path__default.default.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
227
+ const exportPaths = {
228
+ require: [],
229
+ import: []
230
+ };
231
+ for (const exp of Object.values(ctx.exports || {}))
232
+ exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
233
+ const external = [
234
+ ...Object.keys(pkg.dependencies || {}),
235
+ ...Object.keys(pkg.devDependencies || {})
236
+ ], consoleSpy = createConsoleSpy();
237
+ exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
238
+ }
239
+ }
240
+ async function checkExports(exportPaths, options) {
241
+ const { build: build2 } = await import("esbuild"), { cwd, external, format, logger } = options, code = exportPaths.map((id) => format ? `import('${id}');` : `require('${id}');`).join(`
242
+ `);
243
+ try {
244
+ const esbuildResult = await build2({
245
+ bundle: !0,
246
+ external,
247
+ format,
248
+ logLevel: "silent",
249
+ // otherwise output maps to stdout as we're using stdin
250
+ outfile: "/dev/null",
251
+ platform: "node",
252
+ stdin: {
253
+ contents: code,
254
+ loader: "js",
255
+ resolveDir: cwd
276
256
  }
277
- if (dirPath === ".") return;
257
+ });
258
+ if (esbuildResult.errors.length > 0) {
259
+ for (const msg of esbuildResult.errors)
260
+ printEsbuildMessage(logger.warn, msg), logger.log();
261
+ process.exit(1);
278
262
  }
263
+ const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
264
+ (msg.detail || msg.text).includes("does not affect esbuild's own target setting");
265
+ });
266
+ for (const msg of esbuildWarnings)
267
+ printEsbuildMessage(logger.warn, msg), logger.log();
268
+ } catch (err) {
269
+ if (isEsbuildFailure(err)) {
270
+ const { errors } = err;
271
+ for (const msg of errors)
272
+ printEsbuildMessage(logger.error, msg), logger.log();
273
+ } else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
274
+ process.exit(1);
279
275
  }
280
- return ret;
281
276
  }
282
- const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
277
+ function printEsbuildMessage(log, msg) {
278
+ msg.location ? log(
279
+ [
280
+ `${msg.detail || msg.text}
281
+ `,
282
+ `${msg.location.line} | ${msg.location.lineText}
283
+ `,
284
+ `in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
285
+ ].join("")
286
+ ) : log(msg.detail || msg.text);
287
+ }
288
+ function isEsbuildFailure(err) {
289
+ return err instanceof Error && "errors" in err && Array.isArray(err.errors) && err.errors.every(isEsbuildMessage) && "warnings" in err && Array.isArray(err.warnings) && err.warnings.every(isEsbuildMessage);
290
+ }
291
+ function isEsbuildMessage(msg) {
292
+ return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
293
+ }
294
+ function defineConfig(configOptions) {
295
+ return configOptions;
296
+ }
297
+ const DEFAULT_BROWSERSLIST_QUERY = config__default.default, fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
283
298
  function getTargetPaths(_type, expOrBundle) {
284
299
  const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
285
300
  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$1(expOrBundle) && (expOrBundle.browser?.source || (expOrBundle.browser?.import && set.add(
@@ -429,24 +444,43 @@ function parseExports(options) {
429
444
  function isPkgExport(value) {
430
445
  return isRecord(value) && "source" in value && typeof value.source == "string";
431
446
  }
432
- async function loadTSConfig(options) {
433
- const { cwd, tsconfigPath } = options, configPath = ts__default.default.findConfigFile(cwd, ts__default.default.sys.fileExists, tsconfigPath);
434
- if (!configPath)
435
- return;
436
- const configFile = ts__default.default.readConfigFile(configPath, ts__default.default.sys.readFile);
437
- return ts__default.default.parseJsonConfigFileContent(configFile.config, ts__default.default.sys, cwd);
447
+ function defineTemplateOption(option) {
448
+ return option;
449
+ }
450
+ async function isEmptyDirectory(dirPath) {
451
+ return (await fs.readdir(dirPath)).length === 0;
438
452
  }
439
- function resolveBrowserTarget(versions) {
440
- const target = versions.filter(
441
- (version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
442
- );
443
- if (target.length !== 0)
444
- return target;
453
+ async function init(options) {
454
+ const [{ createFromTemplate }, { defaultTemplate }] = await Promise.all([
455
+ Promise.resolve().then(function() {
456
+ return require("./index3.cjs");
457
+ }),
458
+ Promise.resolve().then(function() {
459
+ return require("./template.cjs");
460
+ })
461
+ ]);
462
+ if (!options.cwd)
463
+ throw new Error("Missing required option: cwd");
464
+ if (!options.path)
465
+ throw new Error("Missing required option: path");
466
+ const logger = createLogger(), packagePath = path.resolve(options.cwd, options.path);
467
+ await ensurePackagePath(packagePath), await createFromTemplate({
468
+ cwd: options.cwd,
469
+ logger,
470
+ template: defaultTemplate,
471
+ packagePath
472
+ });
445
473
  }
446
- function resolveNodeTarget(versions) {
447
- const target = versions.filter((version) => version.startsWith("node"));
448
- if (target.length !== 0)
449
- return target;
474
+ async function ensurePackagePath(packagePath) {
475
+ const { mkdirp } = await import("mkdirp");
476
+ if (!fileExists(packagePath)) {
477
+ await mkdirp(packagePath);
478
+ return;
479
+ }
480
+ if (!(await fs.lstat(packagePath)).isDirectory())
481
+ throw new Error("the package path is a file, not a directory");
482
+ if (!await isEmptyDirectory(packagePath))
483
+ throw new Error("the package directory is not empty");
450
484
  }
451
485
  const toggle = zod.z.union([zod.z.literal("error"), zod.z.literal("warn"), zod.z.literal("off")]), strictOptions = zod.z.object({
452
486
  noPackageJsonTypings: toggle.default("error"),
@@ -461,393 +495,22 @@ const toggle = zod.z.union([zod.z.literal("error"), zod.z.literal("warn"), zod.z
461
495
  function parseStrictOptions(input) {
462
496
  return validationSchema.parse({ strictOptions: input }, { errorMap: zodValidationError.errorMap }).strictOptions;
463
497
  }
464
- async function resolveBuildContext(options) {
465
- const {
466
- config: config2,
467
- cwd,
468
- emitDeclarationOnly = !1,
469
- logger,
470
- pkg,
471
- strict,
472
- tsconfig: tsconfigPath
473
- } = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
474
- let browserslist2 = pkg.browserslist;
475
- if (!browserslist2) {
476
- if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
477
- if (strictOptions2.noImplicitBrowsersList === "error")
478
- throw new Error(
479
- '\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
480
- );
481
- logger.warn(
482
- 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
483
- );
484
- }
485
- browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
486
- }
487
- const targetVersions = browserslistToEsbuild(browserslist2);
488
- if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
489
- const msg = "package.json: `sideEffects` is missing, see https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects for how to define `sideEffects`";
490
- if (strictOptions2.noImplicitSideEffects === "error")
491
- throw new Error(msg);
492
- logger.warn(msg);
498
+ const LOG_LEVELS = {
499
+ error: "error",
500
+ info: "info",
501
+ off: "none",
502
+ warn: "warning"
503
+ };
504
+ function getExtractMessagesConfig(options) {
505
+ const { rules, disabled = !1 } = options;
506
+ function ruleToLogLevel(key, defaultLevel) {
507
+ const r = rules?.[key];
508
+ return r ? LOG_LEVELS[r] : defaultLevel || "warning";
493
509
  }
494
- const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
495
- if (!nodeTarget)
496
- throw new Error("no matching `node` target");
497
- if (!webTarget)
498
- throw new Error("no matching `web` target");
499
- const target = {
500
- "*": webTarget.concat(nodeTarget),
501
- browser: webTarget,
502
- node: nodeTarget
503
- }, parsedExports = parseExports({
504
- cwd,
505
- pkg,
506
- strict,
507
- strictOptions: strictOptions2,
508
- logger
509
- }).reduce(
510
- (acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
511
- {}
512
- ), exports2 = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
513
- ...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
514
- ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
515
- ], 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(
516
- // Do not bundle anything that is marked as external
517
- (_) => !externalWithTypes.has(_)
518
- ), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports2).flatMap((exportEntry) => [
519
- exportEntry.import,
520
- exportEntry.require,
521
- exportEntry.browser?.import,
522
- exportEntry.browser?.require,
523
- exportEntry.node?.source && exportEntry.node.import,
524
- exportEntry.node?.source && exportEntry.node.require
525
- ].filter(Boolean)).map((p) => path__default.default.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
526
- if (commonDistPath === cwd)
527
- throw new Error(
528
- "all output files must share a common parent directory which is not the root package directory"
529
- );
530
- if (commonDistPath && !pathContains(cwd, commonDistPath))
531
- throw new Error("all output files must be located within the package");
532
- const configDistPath = config2?.dist ? path__default.default.resolve(cwd, config2.dist) : void 0;
533
- if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
534
- throw logger.log(`did you mean to configure \`dist: './${path__default.default.relative(cwd, commonDistPath)}'\`?`), new Error("all output files must be located with the configured `dist` path");
535
- const distPath = configDistPath || commonDistPath;
536
- if (!distPath)
537
- throw new Error("could not detect `dist` path");
538
510
  return {
539
- config: config2,
540
- cwd,
541
- distPath,
542
- emitDeclarationOnly,
543
- exports: exports2,
544
- external,
545
- bundledPackages,
546
- files: [],
547
- logger,
548
- pkg,
549
- runtime: config2?.runtime ?? "*",
550
- strict,
551
- target,
552
- ts: {
553
- config: tsconfig,
554
- configPath: tsconfigPath
555
- },
556
- dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
557
- };
558
- }
559
- function transformPackageName(packageName) {
560
- if (packageName.startsWith("@types/"))
561
- return packageName;
562
- if (packageName.startsWith("@")) {
563
- const [scope, name] = packageName.split("/");
564
- return `@types/${scope.slice(1)}__${name}`;
565
- } else
566
- return `@types/${packageName}`;
567
- }
568
- function resolveBuildTasks(ctx) {
569
- const { config: config2, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
570
- ([_path, exp]) => ({ _path, ...exp })
571
- ), dtsTask2 = {
572
- type: "build:dts",
573
- entries: []
574
- }, rolldownDtsTask2 = {}, rollupTasks = {};
575
- function addRollupTaskEntry(format, runtime, entry) {
576
- const buildId = `${format}:${runtime}`;
577
- ctx.dts === "rolldown" && (rolldownDtsTask2[buildId] ? rolldownDtsTask2[buildId].entries.push(entry) : rolldownDtsTask2[buildId] = {
578
- type: "rolldown:dts",
579
- buildId,
580
- entries: [entry],
581
- runtime,
582
- format,
583
- target: target[runtime]
584
- }), ctx.emitDeclarationOnly || (rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
585
- type: "build:js",
586
- buildId,
587
- entries: [entry],
588
- runtime,
589
- format,
590
- target: target[runtime]
591
- });
592
- }
593
- if (ctx.dts === "api-extractor") {
594
- for (const exp of exports2) {
595
- const importId = path__default.default.join(pkg.name, exp._path);
596
- exp.source?.endsWith(".ts") && dtsTask2.entries.push({
597
- importId,
598
- exportPath: exp._path,
599
- sourcePath: exp.source,
600
- targetPaths: getTargetPaths(pkg.type, exp)
601
- }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
602
- importId,
603
- exportPath: exp._path,
604
- sourcePath: exp.browser.source,
605
- targetPaths: getTargetPaths(pkg.type, exp.browser)
606
- }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
607
- importId,
608
- exportPath: exp._path,
609
- sourcePath: exp.node.source,
610
- targetPaths: getTargetPaths(pkg.type, exp.node)
611
- });
612
- }
613
- for (const bundle of bundles)
614
- if (bundle.source?.endsWith(".ts")) {
615
- const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path__default.default.join(pkg.name, exportPath);
616
- dtsTask2.entries.push({
617
- importId,
618
- exportPath,
619
- sourcePath: bundle.source,
620
- targetPaths: getTargetPaths(pkg.type, bundle)
621
- });
622
- }
623
- dtsTask2.entries.length && tasks.push(dtsTask2);
624
- }
625
- for (const exp of exports2) {
626
- const output = exp.require;
627
- output && addRollupTaskEntry("commonjs", ctx.runtime, {
628
- path: exp._path,
629
- source: exp.source,
630
- output
631
- });
632
- }
633
- for (const exp of exports2) {
634
- const output = exp.import;
635
- output && addRollupTaskEntry("esm", ctx.runtime, {
636
- path: exp._path,
637
- source: exp.source,
638
- output
639
- });
640
- }
641
- for (const exp of exports2) {
642
- const output = exp.browser?.require;
643
- output && addRollupTaskEntry("commonjs", "browser", {
644
- path: exp._path,
645
- source: exp.browser?.source || exp.source,
646
- output
647
- });
648
- }
649
- for (const exp of exports2) {
650
- const output = exp.browser?.import;
651
- output && addRollupTaskEntry("esm", "browser", {
652
- path: exp._path,
653
- source: exp.browser?.source || exp.source,
654
- output
655
- });
656
- }
657
- for (const bundle of bundles) {
658
- const idx = bundles.indexOf(bundle);
659
- bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
660
- path: `__$$bundle_cjs_${idx}$$__`,
661
- source: bundle.source,
662
- output: bundle.require
663
- }), bundle.import && addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
664
- path: `__$$bundle_esm_${idx}$$__`,
665
- source: bundle.source,
666
- output: bundle.import
667
- });
668
- }
669
- return tasks.push(...Object.values(rolldownDtsTask2)), tasks.push(...Object.values(rollupTasks)), tasks;
670
- }
671
- function createSpinner(msg) {
672
- const startTime = Date.now();
673
- return console.log(msg), {
674
- complete: () => {
675
- console.log(`${chalk__default.default.green("[success]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
676
- },
677
- error: () => {
678
- console.log(`${chalk__default.default.red("[error]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
679
- }
680
- };
681
- }
682
- function printExtractMessages(ctx, messages) {
683
- const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
684
- warnings.length && logger.log();
685
- for (const msg of warnings) {
686
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
687
- msg.messageId !== "TS6307" && logger.log(
688
- [
689
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
690
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
691
- ` - ${chalk__default.default.yellow("warning")} ${chalk__default.default.gray(msg.messageId)}
692
- `,
693
- msg.text,
694
- `
695
- `
696
- ].join("")
697
- );
698
- }
699
- const errors = messages.filter((msg) => msg.logLevel === "error");
700
- !warnings.length && errors.length && logger.log("");
701
- for (const msg of errors) {
702
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
703
- logger.log(
704
- [
705
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
706
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
707
- ` - ${chalk__default.default.red("error")} ${chalk__default.default.gray(msg.messageId)}
708
- `,
709
- msg.text,
710
- `
711
- `
712
- ].join("")
713
- );
714
- }
715
- errors.length && process.exit(1);
716
- }
717
- function printDiagnostic(options) {
718
- const { cwd, logger, diagnostic } = options;
719
- if (diagnostic.file && diagnostic.start) {
720
- const { line, character } = ts__default.default.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
721
- `), file = path__default.default.relative(cwd, diagnostic.file.fileName), output = [
722
- `${chalk__default.default.yellow(file)}:${chalk__default.default.blue(line + 1)}:${chalk__default.default.blue(character + 1)} - `,
723
- `${chalk__default.default.gray(`TS${diagnostic.code}:`)} ${message}`
724
- ].join("");
725
- 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);
726
- } else
727
- logger.log(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
728
- `));
729
- }
730
- async function buildTypes(options) {
731
- const { cwd, logger, outDir, tsconfig, strict = !1 } = options, compilerOptions = {
732
- ...tsconfig.options,
733
- declaration: !0,
734
- declarationDir: outDir,
735
- emitDeclarationOnly: !0,
736
- noEmit: !1,
737
- noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
738
- outDir
739
- }, program = ts__default.default.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts__default.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
740
- for (const diagnostic of allDiagnostics)
741
- printDiagnostic({ cwd, logger, diagnostic });
742
- if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts__default.default.DiagnosticCategory.Error).length)
743
- throw new Error("failed to compile TypeScript definitions");
744
- }
745
- class DtsError extends Error {
746
- messages;
747
- constructor(message, messages) {
748
- super(message), this.messages = messages;
749
- }
750
- }
751
- function createApiExtractorConfig(options) {
752
- const {
753
- bundledPackages,
754
- distPath,
755
- exportPath,
756
- filePath,
757
- messages,
758
- projectFolder,
759
- mainEntryPointFilePath,
760
- tsconfig,
761
- tsconfigPath,
762
- dtsRollupEnabled
763
- } = options;
764
- return {
765
- apiReport: {
766
- enabled: !1,
767
- reportFileName: "<unscopedPackageName>.api.md"
768
- },
769
- bundledPackages,
770
- // 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`),
771
- compiler: tsconfig.options.paths ? {
772
- overrideTsconfig: {
773
- extends: tsconfigPath,
774
- compilerOptions: {
775
- // An empty object replaces whatever is in the original tsconfig file
776
- paths: {}
777
- }
778
- }
779
- } : { tsconfigFilePath: tsconfigPath },
780
- docModel: {
781
- enabled: !1,
782
- apiJsonFilePath: path__default.default.resolve(distPath, `${exportPath}.api.json`)
783
- },
784
- dtsRollup: {
785
- enabled: dtsRollupEnabled,
786
- untrimmedFilePath: path__default.default.resolve(distPath, filePath)
787
- // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
788
- // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
789
- },
790
- tsdocMetadata: {
791
- enabled: !1
792
- },
793
- messages,
794
- mainEntryPointFilePath,
795
- projectFolder
796
- };
797
- }
798
- 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/index.cjs", document.baseURI).href);
799
- async function createTSDocConfig(opts) {
800
- const { customTags } = opts;
801
- if (customTags.length === 0)
802
- return;
803
- const tsDocBaseBuf = await fs.readFile(
804
- require$1.resolve("@microsoft/api-extractor/extends/tsdoc-base.json")
805
- ), tsDocBaseConfig = jsoncParser.parse(tsDocBaseBuf.toString()), tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(
806
- customTags.map((t) => ({
807
- tagName: `@${t.name}`,
808
- syntaxKind: t.syntaxKind,
809
- allowMultiple: t.allowMultiple
810
- }))
811
- ), supportForTags = { ...tsDocBaseConfig.supportForTags };
812
- for (const customTag of customTags)
813
- supportForTags[`@${customTag.name}`] = !0;
814
- return tsdocConfig.TSDocConfigFile.loadFromObject({
815
- ...tsDocBaseConfig,
816
- noStandardTags: !1,
817
- tagDefinitions,
818
- supportForTags
819
- });
820
- }
821
- async function extractModuleBlocksFromTypes({
822
- tsOutDir,
823
- extractResult
824
- }) {
825
- const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
826
- for (const sourceFile of sourceFiles)
827
- sourceFile.text.includes("declare module") && moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
828
- return moduleBlocks;
829
- }
830
- function extractModuleBlocks(fileContent) {
831
- return recast.parse(fileContent, {
832
- parser: typeScriptParser__default.default
833
- }).program.body.filter((node2) => node2.type === "TSModuleDeclaration").map((node2) => recast.print(node2).code);
834
- }
835
- const LOG_LEVELS = {
836
- error: "error",
837
- info: "info",
838
- off: "none",
839
- warn: "warning"
840
- };
841
- function getExtractMessagesConfig(options) {
842
- const { rules, disabled = !1 } = options;
843
- function ruleToLogLevel(key, defaultLevel) {
844
- const r = rules?.[key];
845
- return r ? LOG_LEVELS[r] : defaultLevel || "warning";
846
- }
847
- return {
848
- compilerMessageReporting: {
849
- default: {
850
- logLevel: disabled ? "none" : "warning"
511
+ compilerMessageReporting: {
512
+ default: {
513
+ logLevel: disabled ? "none" : "warning"
851
514
  }
852
515
  },
853
516
  extractorMessageReporting: disabled ? {
@@ -913,1367 +576,21 @@ function getExtractMessagesConfig(options) {
913
576
  }
914
577
  };
915
578
  }
916
- async function extractTypes(options) {
917
- const {
918
- bundledPackages,
919
- customTags,
920
- distPath,
921
- exportPath,
922
- files,
923
- filePaths,
924
- projectPath,
925
- rules,
926
- sourceTypesPath,
927
- tmpPath,
928
- tsconfig,
929
- tsconfigPath,
930
- extractorDisabled
931
- } = options, tsdocConfigFile = await createTSDocConfig({
932
- customTags: customTags || []
933
- }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = apiExtractor.ExtractorConfig.prepare({
934
- configObject: createApiExtractorConfig({
935
- bundledPackages,
936
- distPath,
937
- exportPath,
938
- filePath,
939
- messages: getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
940
- projectFolder: projectPath,
941
- mainEntryPointFilePath: sourceTypesPath,
942
- tsconfig,
943
- tsconfigPath,
944
- dtsRollupEnabled: !0
945
- }),
946
- configObjectFullPath: void 0,
947
- tsdocConfigFile,
948
- packageJsonFullPath: path__default.default.resolve(projectPath, "package.json")
949
- }), messages = [], extractorResult = apiExtractor.Extractor.invoke(extractorConfig, {
950
- // Equivalent to the "--local" command-line parameter
951
- localBuild: !0,
952
- // Equivalent to the "--verbose" command-line parameter
953
- showVerboseMessages: !0,
954
- // handle messages
955
- messageCallback(message) {
956
- messages.push(message), message.handled = !0;
957
- }
958
- }), typesPath = path__default.default.resolve(distPath, filePath), typesBuf = await fs__default.default.readFile(typesPath), prettierConfig = await prettier__namespace.resolveConfig(typesPath);
959
- await mkdirp.mkdirp(path__default.default.dirname(typesPath));
960
- const moduleBlocks = await extractModuleBlocksFromTypes({
961
- extractResult: extractorResult,
962
- tsOutDir: tmpPath
963
- }), code = [typesBuf.toString(), ...moduleBlocks].join(`
964
-
965
- `), prettyCode = await prettier__namespace.format(code, {
966
- ...prettierConfig,
967
- filepath: typesPath
968
- });
969
- for (const expFilePath of filePaths) {
970
- const expTypesPath = path__default.default.resolve(distPath, expFilePath);
971
- await fs__default.default.writeFile(expTypesPath, prettyCode), files.push({
972
- type: "types",
973
- path: expTypesPath
974
- });
975
- }
976
- return shouldCleanUpDts && await fs__default.default.unlink(typesPath), { extractorResult, messages };
977
- }
978
- async function doExtract(ctx, task) {
979
- const { config: config2, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
980
- if (!ts2.config || !ts2.configPath)
981
- return { type: "dts", messages: [], results: [] };
982
- const { outDir, rootDir = cwd } = ts2.config.options;
983
- if (!outDir)
984
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
985
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
986
- await buildTypes({ cwd, logger, outDir: tmpPath, strict, tsconfig: ts2.config });
987
- const messages = [], results = [];
988
- for (const entry of task.entries) {
989
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
990
- tmpPath,
991
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
992
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath)), result = await extractTypes({
993
- bundledPackages: bundledPackages || [],
994
- customTags: config2?.extract?.customTags,
995
- distPath: outDir,
996
- exportPath,
997
- files,
998
- filePaths,
999
- projectPath: cwd,
1000
- rules: config2?.extract?.rules,
1001
- sourceTypesPath,
1002
- tsconfig: ts2.config,
1003
- tmpPath,
1004
- tsconfigPath: path__default.default.resolve(cwd, ts2.configPath || "tsconfig.json"),
1005
- extractorDisabled: config2?.extract?.enabled === !1
1006
- });
1007
- messages.push(...result.messages);
1008
- const errors = result.messages.filter((msg) => msg.logLevel === "error");
1009
- if (errors.length > 0)
1010
- throw await rimraf.rimraf(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
1011
- results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
1012
- }
1013
- return await rimraf.rimraf(tmpPath), { type: "dts", messages, results };
1014
- }
1015
- const dtsTask = {
1016
- name: (ctx, task) => [
1017
- `Build type definitions with ${chalk__default.default.bold(ctx.dts)}...`,
1018
- " entries:",
1019
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
1020
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
1021
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
1022
- ].join("")).join(`
1023
- `))
1024
- ].join(`
1025
- `),
1026
- exec: (ctx, task) => new rxjs.Observable((observer) => {
1027
- doExtract(ctx, task).then((result) => {
1028
- observer.next(result), observer.complete();
1029
- }).catch((err) => {
1030
- observer.error(err);
1031
- });
1032
- }),
1033
- complete: (ctx, _task, result) => {
1034
- printExtractMessages(ctx, result.messages);
1035
- },
1036
- error: (ctx, _task, err) => {
1037
- const { logger } = ctx;
1038
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
1039
- }
1040
- }, dtsWatchTask = {
1041
- name: (_ctx, task) => [
1042
- "build type definitions",
1043
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
1044
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
1045
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
1046
- ].join("")))
1047
- ].join(`
1048
- `),
1049
- exec: (ctx, task) => {
1050
- const { config: config2, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
1051
- return new rxjs.Observable((observer) => {
1052
- if (!tsContext.config || !tsContext.configPath) {
1053
- observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
1054
- return;
1055
- }
1056
- const { outDir, rootDir = cwd } = tsContext.config.options;
1057
- if (!outDir) {
1058
- observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`"));
1059
- return;
1060
- }
1061
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
1062
- buildTypes({
1063
- cwd,
1064
- logger,
1065
- outDir: tmpPath,
1066
- tsconfig: tsContext.config,
1067
- strict
1068
- }).catch((err) => {
1069
- observer.error(err);
1070
- });
1071
- const host = ts__default.default.createWatchCompilerHost(
1072
- tsContext.configPath,
1073
- {
1074
- ...tsContext.config.options,
1075
- declaration: !0,
1076
- declarationDir: tmpPath,
1077
- emitDeclarationOnly: !0,
1078
- noEmit: !1,
1079
- noEmitOnError: strict ? !0 : tsContext.config.options.noEmitOnError ?? !0,
1080
- outDir: tmpPath
1081
- },
1082
- ts__default.default.sys,
1083
- ts__default.default.createEmitAndSemanticDiagnosticsBuilderProgram,
1084
- (diagnostic) => {
1085
- logger.error(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
1086
- `));
1087
- },
1088
- (diagnostic) => {
1089
- logger.info(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
1090
- `));
1091
- }
1092
- ), origPostProgramCreate = host.afterProgramCreate;
1093
- host.afterProgramCreate = async (program) => {
1094
- origPostProgramCreate?.(program);
1095
- const messages = [], results = [];
1096
- for (const entry of task.entries) {
1097
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
1098
- tmpPath,
1099
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
1100
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath));
1101
- try {
1102
- const result = await extractTypes({
1103
- bundledPackages: bundledPackages || [],
1104
- customTags: config2?.extract?.customTags,
1105
- cwd,
1106
- distPath: outDir,
1107
- exportPath,
1108
- files,
1109
- filePaths,
1110
- projectPath: cwd,
1111
- rules: config2?.extract?.rules,
1112
- sourceTypesPath,
1113
- tsconfig: tsContext.config,
1114
- tmpPath,
1115
- tsconfigPath: path__default.default.resolve(cwd, tsContext.configPath || "tsconfig.json"),
1116
- extractorDisabled: config2?.extract?.enabled === !1
1117
- });
1118
- messages.push(...result.messages), results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
1119
- } catch (err) {
1120
- if (err instanceof DtsError)
1121
- messages.push(...err.messages);
1122
- else {
1123
- observer.error(err);
1124
- return;
1125
- }
1126
- }
1127
- }
1128
- observer.next({ type: "dts", messages, results });
1129
- };
1130
- const watchProgram = ts__default.default.createWatchProgram(host);
1131
- return () => {
1132
- watchProgram.close(), rimraf__namespace.sync(tmpPath);
1133
- };
1134
- });
1135
- },
1136
- complete: (ctx, task, result) => {
1137
- const { logger } = ctx;
1138
- printExtractMessages(ctx, result.messages), logger.success(
1139
- `build type definitions
1140
- ${task.entries.map(
1141
- (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(", "))}`
1142
- ).join(`
1143
- `)}`
1144
- ), logger.log("");
1145
- },
1146
- error: (ctx, _task, err) => {
1147
- const { logger } = ctx;
1148
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
1149
- }
1150
- };
1151
- function createConsoleSpy(options) {
1152
- const { onRestored } = options || {}, original = {
1153
- log: console.log,
1154
- warn: console.warn,
1155
- error: console.error
1156
- }, messages = [];
1157
- 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 }), {
1158
- messages,
1159
- restore: () => {
1160
- console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
1161
- }
1162
- };
1163
- }
1164
- const rolldownDtsTask = {
1165
- name: (ctx, task) => {
1166
- 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 ? [
1167
- " bundles:",
1168
- ...bundleEntries.map(
1169
- (e) => [
1170
- " - ",
1171
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
1172
- ].join("")
1173
- )
1174
- ] : [], entriesLines = entries.length ? [
1175
- " entries:",
1176
- ...entries.map(
1177
- (e) => [
1178
- " - ",
1179
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
1180
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
1181
- ].join("")
1182
- )
1183
- ] : [];
1184
- return [
1185
- `Build type definitions with ${chalk__default.default.bold("rolldown")}...`,
1186
- ` format: ${chalk__default.default.yellow(task.format)}`,
1187
- ...targetLines,
1188
- ...bundlesLines,
1189
- ...entriesLines
1190
- ].join(`
1191
- `);
1192
- },
1193
- exec: (ctx, task) => rxjs.from(execPromise$1(ctx, task)),
1194
- complete: () => {
1195
- },
1196
- error: (_ctx, _task, err) => {
1197
- console.error(err);
1198
- }
1199
- };
1200
- async function execPromise$1(ctx, task) {
1201
- const [{ rolldown }, { resolveRolldownConfig }] = await Promise.all([
1202
- import("rolldown"),
579
+ async function watch(options) {
580
+ const [{ resolveBuildContext }, { resolveWatchTasks }, { watchTaskHandlers }, { watchConfigFiles }] = await Promise.all([
1203
581
  Promise.resolve().then(function() {
1204
- return require("./resolveRolldownConfig.cjs");
1205
- })
1206
- ]), { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
1207
- onRestored: (messages) => {
1208
- for (const msg of messages) {
1209
- const text = String(msg.args[0]);
1210
- 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)));
1211
- }
1212
- }
1213
- });
1214
- try {
1215
- const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
1216
- ...inputOptions,
1217
- onwarn(warning) {
1218
- consoleSpy.messages.push({
1219
- type: "warn",
1220
- code: warning.code,
1221
- args: [warning.message]
1222
- });
1223
- }
1224
- }), { output } = await bundle.generate(outputOptions);
1225
- for (const chunkOrAsset of output)
1226
- chunkOrAsset.type === "asset" ? files.push({
1227
- type: "asset",
1228
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1229
- }) : files.push({
1230
- type: "chunk",
1231
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1232
- });
1233
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
1234
- } catch (err) {
1235
- throw consoleSpy.restore(), err;
1236
- }
1237
- }
1238
- function replaceFileEnding(path2) {
1239
- switch (!0) {
1240
- case path2.endsWith(".mjs"):
1241
- return path2.replace(/\.mjs$/, ".d.mts");
1242
- case path2.endsWith(".cjs"):
1243
- return path2.replace(/\.cjs$/, ".d.cts");
1244
- default:
1245
- return path2.replace(/\.js$/, ".d.ts");
1246
- }
1247
- }
1248
- function resolveRollupConfig(ctx, buildTask) {
1249
- const { format, runtime, target } = buildTask, { config: config2, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], minify = config2?.minify ?? !1, outDir = path__default.default.relative(cwd, distPath), pathAliases = Object.fromEntries(
1250
- Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path__default.default.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
1251
- ), entries = buildTask.entries.map((entry) => ({
1252
- ...entry,
1253
- name: path__default.default.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
1254
- }), {}), 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(
1255
- Object.entries(config2?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
1256
- ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config2?.rollup || {}, defaultPlugins = [
1257
- replace__default.default({
1258
- preventAssignment: !0,
1259
- values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
1260
- "process.env.PKG_FILE_PATH": (arg) => {
1261
- const sourcePath = `./${path__default.default.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
1262
- return entry ? JSON.stringify(
1263
- path__default.default.relative(cwd, path__default.default.resolve(outDir, entry.name + outputExt))
1264
- ) : (console.error(`could not find source entry: ${sourcePath}`), "null");
1265
- },
1266
- "process.env.PKG_FORMAT": JSON.stringify(format),
1267
- "process.env.PKG_RUNTIME": JSON.stringify(runtime),
1268
- "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
1269
- ...replacements
1270
- }
1271
- }),
1272
- alias__default.default({
1273
- entries: { ...pathAliases }
1274
- }),
1275
- pluginNodeResolve.nodeResolve({
1276
- browser: runtime === "browser",
1277
- extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
1278
- preferBuiltins: !0
582
+ return require("./resolveBuildContext.cjs");
1279
583
  }),
1280
- commonjs__default.default(),
1281
- json__default.default(),
1282
- (config2?.babel?.reactCompiler || config2?.babel?.styledComponents) && pluginBabel.babel({
1283
- babelrc: !1,
1284
- presets: ["@babel/preset-typescript"],
1285
- babelHelpers: "bundled",
1286
- extensions: [".ts", ".tsx", ".js", ".jsx"],
1287
- plugins: [
1288
- // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
1289
- config2?.babel?.styledComponents && [
1290
- "babel-plugin-styled-components",
1291
- {
1292
- // 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``"
1293
- fileName: !1,
1294
- // Native template literals take less space than this transpilation
1295
- transpileTemplateLiterals: !1,
1296
- // Massively helps dead code elimination and tree-shaking
1297
- pure: !0,
1298
- // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
1299
- cssProp: !1,
1300
- ...typeof config2.babel.styledComponents == "object" ? config2.babel.styledComponents : {}
1301
- }
1302
- ],
1303
- config2?.babel?.reactCompiler && [
1304
- "babel-plugin-react-compiler",
1305
- config2?.reactCompilerOptions || {}
1306
- ]
1307
- ].filter(Boolean)
1308
- }),
1309
- esbuild__default.default({
1310
- jsx: config2?.jsx ?? "automatic",
1311
- jsxFactory: config2?.jsxFactory ?? "createElement",
1312
- jsxFragment: config2?.jsxFragment ?? "Fragment",
1313
- jsxImportSource: config2?.jsxImportSource ?? "react",
1314
- target,
1315
- tsconfig: ctx.ts.configPath || "tsconfig.json",
1316
- treeShaking: !0,
1317
- minifySyntax: config2?.minify !== !1,
1318
- supported: {
1319
- "template-literal": !0
1320
- }
1321
- }),
1322
- Array.isArray(config2?.babel?.plugins) && pluginBabel.getBabelOutputPlugin({
1323
- babelrc: !1,
1324
- plugins: config2.babel.plugins
584
+ Promise.resolve().then(function() {
585
+ return require("./resolveWatchTasks.cjs");
1325
586
  }),
1326
- enableOptimizeLodash && rollupPlugin.optimizeLodashImports({
1327
- useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
1328
- ...typeof config2?.rollup?.optimizeLodash == "boolean" ? {} : config2?.rollup?.optimizeLodash
587
+ Promise.resolve().then(function() {
588
+ return require("./index2.cjs");
1329
589
  }),
1330
- minify && terser__default.default({
1331
- compress: { directives: !1, passes: 10 },
1332
- ecma: 2020,
1333
- output: {
1334
- comments: (_node, comment) => {
1335
- const text = comment.value;
1336
- return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
1337
- },
1338
- preserve_annotations: !0
1339
- }
1340
- })
1341
- ].filter(Boolean), userPlugins = config2?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty(config2?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config2?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
1342
- return {
1343
- inputOptions: {
1344
- context: cwd,
1345
- external: (id, importer) => {
1346
- if (exportIds?.includes(id))
1347
- return !0;
1348
- if (importer && (id.startsWith(".") || id.startsWith("/"))) {
1349
- const idPath = path__default.default.resolve(path__default.default.dirname(importer), id);
1350
- if (sourcePaths?.includes(idPath))
1351
- return logger.warn(
1352
- `detected self-referencing import \u2013 treating as external: ${path__default.default.relative(
1353
- cwd,
1354
- idPath
1355
- )}`
1356
- ), !0;
1357
- }
1358
- const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
1359
- return !!(name && external.includes(name));
1360
- },
1361
- input: entries.reduce(
1362
- (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
1363
- {}
1364
- ),
1365
- watch: {
1366
- chokidar: {
1367
- usePolling: !0
1368
- }
1369
- },
1370
- plugins,
1371
- treeshake: {
1372
- preset: "recommended",
1373
- propertyReadSideEffects: !1,
1374
- moduleSideEffects: "no-external",
1375
- ...config2?.rollup?.treeshake
1376
- },
1377
- experimentalLogSideEffects: config2?.rollup?.experimentalLogSideEffects
1378
- },
1379
- outputOptions: {
1380
- chunkFileNames,
1381
- compact: minify,
1382
- dir: outDir,
1383
- entryFileNames,
1384
- esModule: !0,
1385
- format,
1386
- interop: "compat",
1387
- sourcemap: config2?.sourcemap ?? !0,
1388
- hoistTransitiveImports: !1,
1389
- minifyInternalExports: minify,
1390
- ...config2?.rollup?.output
1391
- }
1392
- };
1393
- }
1394
- function hasDependency(pkg, packageName) {
1395
- return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
1396
- }
1397
- const rollupTask = {
1398
- name: (ctx, task) => {
1399
- 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 ? [
1400
- " bundles:",
1401
- ...bundleEntries.map(
1402
- (e) => [
1403
- " - ",
1404
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
1405
- ].join("")
1406
- )
1407
- ] : [], entriesLines = entries.length ? [
1408
- " entries:",
1409
- ...entries.map(
1410
- (e) => [
1411
- " - ",
1412
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
1413
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
1414
- ].join("")
1415
- )
1416
- ] : [];
1417
- return [
1418
- "Build javascript files...",
1419
- ` format: ${chalk__default.default.yellow(task.format)}`,
1420
- ...targetLines,
1421
- ...bundlesLines,
1422
- ...entriesLines
1423
- ].join(`
1424
- `);
1425
- },
1426
- exec: (ctx, task) => new rxjs.Observable((observer) => {
1427
- execPromise(ctx, task).then((result) => {
1428
- observer.next(result), observer.complete();
1429
- }).catch((err) => observer.error(err));
1430
- }),
1431
- complete: () => {
1432
- },
1433
- error: (_ctx, _task, err) => {
1434
- console.error(err);
1435
- }
1436
- };
1437
- async function execPromise(ctx, task) {
1438
- const { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
1439
- onRestored: (messages) => {
1440
- for (const msg of messages) {
1441
- const text = String(msg.args[0]);
1442
- 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)));
1443
- }
1444
- }
1445
- });
1446
- try {
1447
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup.rollup({
1448
- ...inputOptions,
1449
- onwarn(warning) {
1450
- consoleSpy.messages.push({
1451
- type: "warn",
1452
- code: warning.code,
1453
- args: [warning.message]
1454
- });
1455
- }
1456
- }), { output } = await bundle.generate(outputOptions);
1457
- for (const chunkOrAsset of output)
1458
- chunkOrAsset.type === "asset" ? files.push({
1459
- type: "asset",
1460
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1461
- }) : files.push({
1462
- type: "chunk",
1463
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1464
- });
1465
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
1466
- } catch (err) {
1467
- throw consoleSpy.restore(), err;
1468
- }
1469
- }
1470
- const rollupWatchTask = {
1471
- name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
1472
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
1473
- `)}`,
1474
- exec: (ctx, task) => {
1475
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
1476
- return new rxjs.Observable((observer) => {
1477
- const watchOptions = {
1478
- ...inputOptions,
1479
- output: outputOptions
1480
- }, watcher = rollup.watch(watchOptions);
1481
- return watcher.on("event", (event) => {
1482
- observer.next(event);
1483
- }), () => {
1484
- watcher.close();
1485
- };
1486
- });
1487
- },
1488
- complete: (ctx, task, event) => {
1489
- const { logger } = ctx;
1490
- if (event.code === "BUNDLE_END") {
1491
- logger.success(
1492
- `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
1493
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
1494
- `)}`
1495
- ), logger.log("");
1496
- return;
1497
- }
1498
- if (event.code !== "BUNDLE_START" && event.code !== "END" && event.code === "ERROR") {
1499
- logger.error(event.code, event);
1500
- return;
1501
- }
1502
- },
1503
- error: (ctx, _task, err) => {
1504
- const { logger } = ctx;
1505
- err instanceof Error && logger.log(err);
1506
- }
1507
- }, buildTaskHandlers = {
1508
- "build:dts": dtsTask,
1509
- "build:js": rollupTask,
1510
- "rolldown:dts": rolldownDtsTask
1511
- }, watchTaskHandlers = {
1512
- "watch:dts": dtsWatchTask,
1513
- "watch:js": rollupWatchTask
1514
- };
1515
- async function build(options) {
1516
- const {
1517
- cwd,
1518
- emitDeclarationOnly,
1519
- strict = !1,
1520
- tsconfig: tsconfigOption,
1521
- clean = !1
1522
- } = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
1523
- config: config2,
1524
- cwd,
1525
- emitDeclarationOnly,
1526
- logger,
1527
- pkg,
1528
- strict,
1529
- tsconfig
1530
- });
1531
- clean && (logger.log(
1532
- `Deleting the \`dist\` folder: './${path__default.default.relative(cwd, ctx.distPath)}' before building...`
1533
- ), await rimraf.rimraf(ctx.distPath));
1534
- const buildTasks = resolveBuildTasks(ctx);
1535
- for (const task of buildTasks) {
1536
- const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName);
1537
- try {
1538
- const result = await handler.exec(ctx, task).toPromise();
1539
- spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
1540
- } catch (err) {
1541
- if (spinner.error(), err instanceof Error) {
1542
- const RE_CWD = new RegExp(`${cwd}`, "g");
1543
- ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
1544
- }
1545
- handler.error(ctx, task, err), process.exit(1);
1546
- }
1547
- }
1548
- }
1549
- function getFilesize(file) {
1550
- const stats = node_fs.statSync(file);
1551
- return prettyBytes__default.default(stats.size);
1552
- }
1553
- function getFileInfo(cwd, filePath) {
1554
- const p = path__default.default.resolve(cwd, filePath), exists = fileExists(p), size = exists ? getFilesize(p) : void 0;
1555
- return { exists, size };
1556
- }
1557
- function printPackageTree(ctx) {
1558
- const { cwd, exports: exports2, logger, pkg } = ctx;
1559
- if (!exports2) return;
1560
- logger.log(`${chalk__default.default.blue(pkg.name)}@${chalk__default.default.green(pkg.version)}`);
1561
- const tree = {};
1562
- pkg.type && (tree.type = chalk__default.default.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
1563
- Object.entries(pkg.bin).map(([name, file]) => [chalk__default.default.cyan(name), fileInfo(file)])
1564
- ));
1565
- function fileInfo(file) {
1566
- const info = getFileInfo(cwd, file);
1567
- return info.size ? `${chalk__default.default.yellow(file)} ${chalk__default.default.gray(info.size)}` : `${chalk__default.default.gray(file)} ${chalk__default.default.red("does not exist")}`;
1568
- }
1569
- tree.exports = Object.fromEntries(
1570
- Object.entries(exports2).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
1571
- const exp = {
1572
- source: fileInfo(entry.source),
1573
- browser: void 0,
1574
- require: void 0,
1575
- node: void 0,
1576
- import: void 0,
1577
- default: fileInfo(entry.default)
1578
- };
1579
- 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__default.default.cyan(path__default.default.join(pkg.name, exportPath)), exp];
590
+ Promise.resolve().then(function() {
591
+ return require("./watchConfigFiles.cjs");
1580
592
  })
1581
- ), logger.log(treeify__default.default.asTree(tree, !0, !0));
1582
- }
1583
- async function check(options) {
1584
- const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
1585
- if (printPackageTree(ctx), strict) {
1586
- const missingFiles = [];
1587
- for (const [, exp] of Object.entries(ctx.exports || {}))
1588
- exp.source && !fileExists(path__default.default.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path__default.default.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path__default.default.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
1589
- ctx.pkg.types && !fileExists(path__default.default.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
1590
- const exportPaths = {
1591
- require: [],
1592
- import: []
1593
- };
1594
- for (const exp of Object.values(ctx.exports || {}))
1595
- exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
1596
- const external = [
1597
- ...Object.keys(pkg.dependencies || {}),
1598
- ...Object.keys(pkg.devDependencies || {})
1599
- ], consoleSpy = createConsoleSpy();
1600
- exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
1601
- }
1602
- }
1603
- async function checkExports(exportPaths, options) {
1604
- const { cwd, external, format, logger } = options, code = exportPaths.map((id) => format ? `import('${id}');` : `require('${id}');`).join(`
1605
- `);
1606
- try {
1607
- const esbuildResult = await esbuild__default$1.default.build({
1608
- bundle: !0,
1609
- external,
1610
- format,
1611
- logLevel: "silent",
1612
- // otherwise output maps to stdout as we're using stdin
1613
- outfile: "/dev/null",
1614
- platform: "node",
1615
- stdin: {
1616
- contents: code,
1617
- loader: "js",
1618
- resolveDir: cwd
1619
- }
1620
- });
1621
- if (esbuildResult.errors.length > 0) {
1622
- for (const msg of esbuildResult.errors)
1623
- printEsbuildMessage(logger.warn, msg), logger.log();
1624
- process.exit(1);
1625
- }
1626
- const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
1627
- (msg.detail || msg.text).includes("does not affect esbuild's own target setting");
1628
- });
1629
- for (const msg of esbuildWarnings)
1630
- printEsbuildMessage(logger.warn, msg), logger.log();
1631
- } catch (err) {
1632
- if (isEsbuildFailure(err)) {
1633
- const { errors } = err;
1634
- for (const msg of errors)
1635
- printEsbuildMessage(logger.error, msg), logger.log();
1636
- } else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
1637
- process.exit(1);
1638
- }
1639
- }
1640
- function printEsbuildMessage(log, msg) {
1641
- msg.location ? log(
1642
- [
1643
- `${msg.detail || msg.text}
1644
- `,
1645
- `${msg.location.line} | ${msg.location.lineText}
1646
- `,
1647
- `in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
1648
- ].join("")
1649
- ) : log(msg.detail || msg.text);
1650
- }
1651
- function isEsbuildFailure(err) {
1652
- return err instanceof Error && "errors" in err && Array.isArray(err.errors) && err.errors.every(isEsbuildMessage) && "warnings" in err && Array.isArray(err.warnings) && err.warnings.every(isEsbuildMessage);
1653
- }
1654
- function isEsbuildMessage(msg) {
1655
- return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
1656
- }
1657
- function defineConfig(configOptions) {
1658
- return configOptions;
1659
- }
1660
- function defineTemplateOption(option) {
1661
- return option;
1662
- }
1663
- const promptsTypes = {
1664
- string: "text"
1665
- };
1666
- async function createFromTemplate(options) {
1667
- const { cwd, logger, packagePath, template: templateOrResolver } = options, template = typeof templateOrResolver == "function" ? await templateOrResolver({ cwd, logger, packagePath }) : templateOrResolver;
1668
- logger.log("create new package at", path.relative(cwd, packagePath));
1669
- const templateOptions = {};
1670
- for (const templateOption of template.options) {
1671
- const templateValidate = templateOption.validate, res = await prompts__default.default(
1672
- {
1673
- type: promptsTypes[templateOption.type],
1674
- name: templateOption.name,
1675
- message: templateOption.description,
1676
- validate: templateValidate ? (prev) => templateValidate(prev) : void 0,
1677
- initial: typeof templateOption.initial == "function" ? templateOption.initial(templateOptions) : templateOption.initial
1678
- },
1679
- { onCancel: () => process.exit(0) }
1680
- );
1681
- templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
1682
- }
1683
- const features = {};
1684
- for (const templateFeature of template.features) {
1685
- const res = templateFeature.optional ? await prompts__default.default(
1686
- {
1687
- type: "confirm",
1688
- name: "confirm",
1689
- message: `use ${templateFeature.name}?`,
1690
- initial: templateFeature.initial
1691
- },
1692
- { onCancel: () => process.exit(0) }
1693
- ) : void 0;
1694
- features[templateFeature.name] = res?.confirm || !templateFeature.optional;
1695
- }
1696
- const files = await template.getFiles(templateOptions, features);
1697
- files.sort((a, b) => a.name.localeCompare(b.name));
1698
- for (const file of files) {
1699
- const filePath = path.resolve(packagePath, file.name);
1700
- await mkdirp.mkdirp(path.dirname(filePath)), await fs.writeFile(filePath, file.contents.trim() + `
1701
- `), logger.success(`wrote ${path.relative(cwd, filePath)}`);
1702
- }
1703
- }
1704
- async function isEmptyDirectory(dirPath) {
1705
- return (await fs.readdir(dirPath)).length === 0;
1706
- }
1707
- const overridableDefaults = {
1708
- endOfLine: "lf",
1709
- tabWidth: 2,
1710
- useTabs: !1
1711
- }, config = {
1712
- ...overridableDefaults,
1713
- printWidth: 100,
1714
- semi: !1,
1715
- singleQuote: !0,
1716
- quoteProps: "consistent",
1717
- bracketSpacing: !1,
1718
- plugins: ["prettier-plugin-packagejson"],
1719
- overrides: [
1720
- {
1721
- files: ["*.json5"],
1722
- options: {
1723
- quoteProps: "preserve",
1724
- singleQuote: !1
1725
- }
1726
- },
1727
- {
1728
- files: ["*.yml"],
1729
- options: {
1730
- singleQuote: !1
1731
- }
1732
- }
1733
- ]
1734
- }, RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i, defaultTemplate = async ({ cwd, logger, packagePath }) => {
1735
- const gitConfig = getGitUserConfig(cwd);
1736
- return {
1737
- options: [
1738
- {
1739
- name: "repo",
1740
- type: "string",
1741
- description: "git url",
1742
- validate: (v) => {
1743
- if (!v) return !0;
1744
- try {
1745
- return gitUrlParse__default.default(v), !0;
1746
- } catch {
1747
- return "invalid git url";
1748
- }
1749
- },
1750
- parse: (v) => {
1751
- if (!v) return null;
1752
- const result = gitUrlParse__default.default(v);
1753
- return { source: result.source, owner: result.owner, name: result.name };
1754
- }
1755
- },
1756
- {
1757
- name: "pkgName",
1758
- type: "string",
1759
- description: "package name",
1760
- initial: (options) => options.repo?.name || void 0,
1761
- validate: (v) => v ? RE_NAME.exec(v) ? !0 : "invalid package name" : "package name is required",
1762
- parse: (v) => {
1763
- if (!v)
1764
- throw new Error("package name is required");
1765
- if (!RE_NAME.exec(v))
1766
- throw new Error("invalid package name");
1767
- const [scope, name] = v.split("/");
1768
- return { scope, name, fullName: v };
1769
- }
1770
- },
1771
- {
1772
- name: "description",
1773
- type: "string",
1774
- description: "package description"
1775
- },
1776
- {
1777
- name: "authorName",
1778
- type: "string",
1779
- description: "package author name",
1780
- initial: gitConfig.user
1781
- },
1782
- {
1783
- name: "authorEmail",
1784
- type: "string",
1785
- description: "package author email",
1786
- initial: gitConfig.email
1787
- },
1788
- {
1789
- name: "license",
1790
- type: "string",
1791
- description: "package license",
1792
- initial: "MIT",
1793
- validate: (v) => v ? !0 : "license is required"
1794
- }
1795
- ],
1796
- features: [
1797
- {
1798
- name: "eslint",
1799
- optional: !0,
1800
- initial: !0
1801
- },
1802
- {
1803
- name: "prettier",
1804
- optional: !0,
1805
- initial: !0
1806
- },
1807
- {
1808
- name: "typescript",
1809
- optional: !0,
1810
- initial: !0
1811
- }
1812
- ],
1813
- async getFiles(options, features) {
1814
- const { pkgName, repo } = options, { fullName: name } = pkgName, author = [options.authorName, options.authorEmail && `<${options.authorEmail}>`].filter(Boolean).join(" ") ?? void 0, pkgJson = {
1815
- name,
1816
- version: "0.0.0",
1817
- description: options.description ?? void 0,
1818
- keywords: [],
1819
- homepage: void 0,
1820
- bugs: void 0,
1821
- repository: void 0,
1822
- license: options.license,
1823
- author,
1824
- sideEffects: !1,
1825
- type: "module",
1826
- exports: {
1827
- ".": {
1828
- source: features.typescript ? "./src/index.ts" : "./src/index.js",
1829
- require: "./dist/index.cjs",
1830
- default: "./dist/index.js"
1831
- },
1832
- "./package.json": "./package.json"
1833
- },
1834
- main: "./dist/index.cjs",
1835
- module: "./dist/index.js",
1836
- types: void 0,
1837
- files: ["dist", "src"],
1838
- scripts: {
1839
- build: "pkg build --strict --clean --check",
1840
- format: features.prettier ? "prettier --write --cache --ignore-unknown ." : void 0
1841
- },
1842
- "lint-staged": features.prettier ? {
1843
- "*": ["prettier --write --cache --ignore-unknown"]
1844
- } : void 0,
1845
- browserslist: "extends @sanity/browserslist-config",
1846
- prettier: features.prettier ? "@sanity/prettier-config" : void 0,
1847
- dependencies: {},
1848
- devDependencies: {
1849
- "@sanity/pkg-utils": "^6",
1850
- "@sanity/prettier-config": features.prettier ? "^1" : void 0,
1851
- "@typescript-eslint/eslint-plugin": void 0,
1852
- "@typescript-eslint/parser": void 0,
1853
- eslint: void 0,
1854
- "eslint-config-prettier": void 0,
1855
- "eslint-plugin-import": void 0,
1856
- "eslint-plugin-prettier": void 0,
1857
- "eslint-plugin-simple-import-sort": void 0,
1858
- "lint-staged": "^15",
1859
- prettier: features.prettier ? "^3" : void 0,
1860
- typescript: void 0
1861
- },
1862
- engines: {
1863
- node: ">=18.0.0"
1864
- }
1865
- }, files = [];
1866
- if (files.push({
1867
- name: ".editorconfig",
1868
- contents: outdent.outdent`
1869
- root = true
1870
-
1871
- [*]
1872
- charset = utf-8
1873
- indent_style = space
1874
- indent_size = 2
1875
- end_of_line = lf
1876
- insert_final_newline = true
1877
- trim_trailing_whitespace = true
1878
- `
1879
- }), files.push({
1880
- name: ".gitignore",
1881
- contents: outdent.outdent`
1882
- *.local
1883
- *.log
1884
- *.tgz
1885
-
1886
- .DS_Store
1887
- dist
1888
- etc
1889
- node_modules
1890
- `
1891
- }), features.prettier && files.push({
1892
- name: ".prettierignore",
1893
- contents: outdent.outdent`
1894
- dist
1895
- pnpm-lock.yaml
1896
- `
1897
- }), repo && (pkgJson.repository = {
1898
- type: "git",
1899
- url: `git+ssh://git@${repo.source}/${repo.owner}/${repo.name}.git`
1900
- }, pkgJson.bugs = {
1901
- url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
1902
- }, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
1903
- pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
1904
- ...pkgJson.scripts,
1905
- "ts:check": "tsc --noEmit"
1906
- };
1907
- const devDependencies = pkgJson.devDependencies;
1908
- isRecord(devDependencies) && (devDependencies.typescript = "^5.4");
1909
- }
1910
- if (features.eslint) {
1911
- const eslintConfig = {
1912
- root: !0,
1913
- env: {
1914
- browser: !0,
1915
- es6: !0,
1916
- node: !0
1917
- },
1918
- extends: [
1919
- "eslint:recommended",
1920
- features.prettier ? "plugin:prettier/recommended" : void 0
1921
- ].filter(Boolean),
1922
- parserOptions: {
1923
- ecmaVersion: 2020,
1924
- sourceType: "module"
1925
- },
1926
- plugins: [
1927
- "import",
1928
- "simple-import-sort",
1929
- features.prettier ? "prettier" : void 0
1930
- ].filter(Boolean),
1931
- rules: {
1932
- "no-console": "error",
1933
- "no-shadow": "error",
1934
- "no-warning-comments": ["warn", { location: "start", terms: ["todo", "fixme"] }],
1935
- "quote-props": ["warn", "consistent-as-needed"],
1936
- "simple-import-sort/exports": "warn",
1937
- "simple-import-sort/imports": "warn",
1938
- strict: ["warn", "global"]
1939
- }
1940
- };
1941
- if (files.push({
1942
- name: ".eslintignore",
1943
- contents: outdent.outdent`
1944
- dist
1945
- `
1946
- }), pkgJson.scripts = {
1947
- ...pkgJson.scripts,
1948
- lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
1949
- }, pkgJson.devDependencies = {
1950
- ...pkgJson.devDependencies,
1951
- eslint: "^8",
1952
- "eslint-config-prettier": features.prettier ? "^9" : void 0,
1953
- "eslint-plugin-import": "^2",
1954
- "eslint-plugin-prettier": features.prettier ? "^5" : void 0,
1955
- "eslint-plugin-simple-import-sort": "^12"
1956
- }, features.typescript) {
1957
- pkgJson.devDependencies = {
1958
- ...pkgJson.devDependencies,
1959
- "@typescript-eslint/eslint-plugin": "^7",
1960
- "@typescript-eslint/parser": "^7"
1961
- };
1962
- const eslintConfigOverride = {
1963
- files: ["**/*.ts", "**/*.tsx"],
1964
- parser: "@typescript-eslint/parser",
1965
- parserOptions: {
1966
- project: ["./tsconfig.json"]
1967
- },
1968
- extends: [
1969
- "eslint:recommended",
1970
- features.prettier ? "plugin:prettier/recommended" : void 0,
1971
- "plugin:@typescript-eslint/eslint-recommended",
1972
- "plugin:@typescript-eslint/recommended"
1973
- ].filter(Boolean),
1974
- plugins: [
1975
- "import",
1976
- "@typescript-eslint",
1977
- "simple-import-sort",
1978
- features.prettier ? "prettier" : void 0
1979
- ].filter(Boolean),
1980
- rules: {
1981
- "@typescript-eslint/explicit-module-boundary-types": "error",
1982
- "@typescript-eslint/interface-name-prefix": "off",
1983
- "@typescript-eslint/member-delimiter-style": "off",
1984
- "@typescript-eslint/no-empty-interface": "off"
1985
- }
1986
- };
1987
- eslintConfig.overrides = [eslintConfigOverride];
1988
- }
1989
- files.push({
1990
- name: ".eslintrc.cjs",
1991
- contents: await prettierFormat(
1992
- path.resolve(packagePath, ".eslintrc.cjs"),
1993
- outdent.outdent`
1994
- 'use strict'
1995
-
1996
- /** @type import('eslint').Linter.Config */
1997
- module.exports = ${JSON.stringify(eslintConfig, null, 2)}
1998
- `,
1999
- config
2000
- )
2001
- });
2002
- }
2003
- features.typescript && (files.push({
2004
- name: "tsconfig.settings.json",
2005
- contents: await prettierFormat(
2006
- path.resolve(packagePath, "tsconfig.settings.json"),
2007
- outdent.outdent`
2008
- {
2009
- "extends": "@sanity/pkg-utils/tsconfig/strictest.json",
2010
- "compilerOptions": {
2011
- "rootDir": ".",
2012
- "outDir": "./dist"
2013
- }
2014
- }
2015
- `,
2016
- config
2017
- )
2018
- }), files.push({
2019
- name: "tsconfig.dist.json",
2020
- contents: await prettierFormat(
2021
- path.resolve(packagePath, "tsconfig.dist.json"),
2022
- outdent.outdent`
2023
- {
2024
- "extends": "./tsconfig.settings",
2025
- "include": ["./src"],
2026
- "exclude": ["./src/**/*.test.ts"]
2027
- }
2028
- `,
2029
- config
2030
- )
2031
- }), files.push({
2032
- name: "tsconfig.json",
2033
- contents: await prettierFormat(
2034
- path.resolve(packagePath, "tsconfig.json"),
2035
- outdent.outdent`
2036
- {
2037
- "extends": "./tsconfig.settings",
2038
- "include": ["./**/*.cjs", "./**/*.ts", "./**/*.tsx"],
2039
- "exclude": ["./node_modules"]
2040
- }
2041
- `,
2042
- config
2043
- )
2044
- })), features.typescript ? (files.push({
2045
- name: "package.config.ts",
2046
- contents: await prettierFormat(
2047
- path.resolve(packagePath, "package.config.ts"),
2048
- outdent.outdent`
2049
- import {defineConfig} from '@sanity/pkg-utils'
2050
-
2051
- // https://github.com/sanity-io/pkg-utils#configuration
2052
- export default defineConfig({
2053
- // the path to the tsconfig file for distributed builds
2054
- tsconfig: 'tsconfig.dist.json',
2055
- })
2056
- `,
2057
- config
2058
- )
2059
- }), files.push({
2060
- name: "src/index.ts",
2061
- contents: await prettierFormat(
2062
- path.resolve(packagePath, "src/index.ts"),
2063
- outdent.outdent`
2064
- /** @public */
2065
- export function main(): void {
2066
- //
2067
- }
2068
- `,
2069
- config
2070
- )
2071
- })) : (files.push({
2072
- name: "package.config.js",
2073
- contents: await prettierFormat(
2074
- path.resolve(packagePath, "package.config.js"),
2075
- outdent.outdent`
2076
- import {defineConfig} from '@sanity/pkg-utils'
2077
-
2078
- export default defineConfig({
2079
- extract: {
2080
- rules: {
2081
- // do not require internal members to be prefixed with \`_\`
2082
- 'ae-internal-missing-underscore': 'off',
2083
- },
2084
- },
2085
- })
2086
- `,
2087
- config
2088
- )
2089
- }), files.push({
2090
- name: "src/index.js",
2091
- contents: await prettierFormat(
2092
- path.resolve(packagePath, "src/index.js"),
2093
- outdent.outdent`
2094
- /** @public */
2095
- export function main() {
2096
- //
2097
- }
2098
- `,
2099
- config
2100
- )
2101
- }));
2102
- try {
2103
- pkgJson.dependencies = await resolveLatestDeps(pkgJson.dependencies ?? {});
2104
- } catch (error) {
2105
- logger.warn(error instanceof Error ? error.message : error);
2106
- }
2107
- try {
2108
- pkgJson.devDependencies = await resolveLatestDeps(pkgJson.devDependencies ?? {});
2109
- } catch (error) {
2110
- logger.warn(error instanceof Error ? error.message : error);
2111
- }
2112
- return files.push({
2113
- name: "package.json",
2114
- contents: await prettierFormat(
2115
- path.resolve(packagePath, "package.json"),
2116
- JSON.stringify(pkgJson, null, 2),
2117
- config
2118
- )
2119
- }), files;
2120
- }
2121
- };
2122
- };
2123
- function prettierFormat(filepath, input, prettierOptions) {
2124
- return prettier.format(input, { ...prettierOptions, plugins: [], filepath });
2125
- }
2126
- async function resolveLatestDeps(deps) {
2127
- const depsEntries = Object.entries(deps), latestDeps = {};
2128
- for (const entry of depsEntries) {
2129
- const [name, version] = entry;
2130
- if (version) {
2131
- const latestVersion = await getLatestVersion__default.default(name, version);
2132
- latestDeps[name] = latestVersion ? `^${latestVersion}` : version;
2133
- }
2134
- }
2135
- return latestDeps;
2136
- }
2137
- function getGitUserConfig(cwd) {
2138
- let user, email;
2139
- try {
2140
- user = node_child_process.execSync("git config user.name", { encoding: "utf8", cwd }).trim() || void 0, email = node_child_process.execSync("git config user.email", { encoding: "utf8", cwd }).trim() || void 0;
2141
- } catch {
2142
- }
2143
- return { user, email };
2144
- }
2145
- async function init(options) {
2146
- if (!options.cwd)
2147
- throw new Error("Missing required option: cwd");
2148
- if (!options.path)
2149
- throw new Error("Missing required option: path");
2150
- const logger = createLogger(), packagePath = path.resolve(options.cwd, options.path);
2151
- await ensurePackagePath(packagePath), await createFromTemplate({
2152
- cwd: options.cwd,
2153
- logger,
2154
- template: defaultTemplate,
2155
- packagePath
2156
- });
2157
- }
2158
- async function ensurePackagePath(packagePath) {
2159
- if (!fileExists(packagePath)) {
2160
- await mkdirp.mkdirp(packagePath);
2161
- return;
2162
- }
2163
- if (!(await fs.lstat(packagePath)).isDirectory())
2164
- throw new Error("the package path is a file, not a directory");
2165
- if (!await isEmptyDirectory(packagePath))
2166
- throw new Error("the package directory is not empty");
2167
- }
2168
- function resolveWatchTasks(ctx) {
2169
- const { pkg, target } = ctx, tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
2170
- ([_path, exp]) => ({ _path, ...exp })
2171
- ), dtsTask2 = {
2172
- type: "watch:dts",
2173
- entries: []
2174
- }, rollupTasks = {};
2175
- function addRollupTaskEntry(format, runtime, entry) {
2176
- const buildId = `${format}:${runtime}`;
2177
- rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
2178
- type: "watch:js",
2179
- buildId,
2180
- entries: [entry],
2181
- runtime,
2182
- format,
2183
- target: target[runtime]
2184
- };
2185
- }
2186
- for (const exp of exports2) {
2187
- const importId = path__default.default.join(pkg.name, exp._path);
2188
- exp.source?.endsWith(".ts") && dtsTask2.entries.push({
2189
- importId,
2190
- exportPath: exp._path,
2191
- sourcePath: exp.source,
2192
- targetPaths: getTargetPaths(pkg.type, exp)
2193
- }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
2194
- importId,
2195
- exportPath: exp._path,
2196
- sourcePath: exp.browser.source,
2197
- targetPaths: getTargetPaths(pkg.type, exp.browser)
2198
- }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
2199
- importId,
2200
- exportPath: exp._path,
2201
- sourcePath: exp.node.source,
2202
- targetPaths: getTargetPaths(pkg.type, exp.node)
2203
- });
2204
- }
2205
- for (const exp of exports2) {
2206
- const output = exp.require;
2207
- output && addRollupTaskEntry("commonjs", ctx.runtime, {
2208
- path: exp._path,
2209
- source: exp.source,
2210
- output
2211
- });
2212
- }
2213
- for (const exp of exports2) {
2214
- const output = exp.browser?.require;
2215
- output && addRollupTaskEntry("commonjs", "browser", {
2216
- path: exp._path,
2217
- source: exp.browser?.source || exp.source,
2218
- output
2219
- });
2220
- }
2221
- for (const exp of exports2) {
2222
- const output = exp.import;
2223
- output && addRollupTaskEntry("esm", ctx.runtime, {
2224
- path: exp._path,
2225
- source: exp.source,
2226
- output
2227
- });
2228
- }
2229
- for (const exp of exports2) {
2230
- const output = exp.browser?.import;
2231
- output && addRollupTaskEntry("esm", "browser", {
2232
- path: exp._path,
2233
- source: exp.browser?.source || exp.source,
2234
- output
2235
- });
2236
- }
2237
- return dtsTask2.entries.length && tasks.push(dtsTask2), tasks.push(...Object.values(rollupTasks)), tasks;
2238
- }
2239
- function globFiles(patterns) {
2240
- return globby__default.default(patterns.map((pattern) => pattern.split(path__default.default.sep).join(path__default.default.posix.sep)));
2241
- }
2242
- function watchFiles(patterns) {
2243
- return new rxjs.Observable((observer) => {
2244
- const watcher = chokidar__namespace.watch(patterns, {
2245
- ignoreInitial: !0
2246
- });
2247
- function handleFileEvent(type, file) {
2248
- type === "error" || file instanceof Error ? observer.error(file) : observer.next({ type, file });
2249
- }
2250
- return watcher.on("all", handleFileEvent), () => {
2251
- watcher.off("all", handleFileEvent), watcher.close();
2252
- };
2253
- });
2254
- }
2255
- async function watchConfigFiles(options) {
2256
- const { cwd, logger } = options, initialFiles = await globFiles([
2257
- path__default.default.resolve(cwd, "package.json"),
2258
- path__default.default.resolve(cwd, "package.config.cjs"),
2259
- path__default.default.resolve(cwd, "package.config.js"),
2260
- path__default.default.resolve(cwd, "package.config.ts")
2261
- ]);
2262
- return watchFiles([
2263
- path__default.default.resolve(cwd, "package.json"),
2264
- path__default.default.resolve(cwd, "package.config.cjs"),
2265
- path__default.default.resolve(cwd, "package.config.js"),
2266
- path__default.default.resolve(cwd, "package.config.ts")
2267
- ]).pipe(
2268
- operators.scan((files, fileEvent) => fileEvent.type === "add" ? files.concat(fileEvent.file) : fileEvent.type === "unlink" ? files.filter((f) => f !== fileEvent.file) : fileEvent.type === "change" ? (logger.log(
2269
- "--------------------------------------------------------------------------------"
2270
- ), logger.info(path__default.default.relative(cwd, fileEvent.file), "changed"), logger.log(""), files.slice(0)) : files, initialFiles),
2271
- operators.startWith(initialFiles),
2272
- operators.distinctUntilChanged()
2273
- );
2274
- }
2275
- async function watch(options) {
2276
- const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
593
+ ]), { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
2277
594
  (await watchConfigFiles({ cwd, logger })).pipe(
2278
595
  rxjs.switchMap(async (configFiles) => {
2279
596
  if (!configFiles.map((f) => path__default.default.relative(cwd, f)).find((f) => f === "package.json"))
@@ -2302,11 +619,15 @@ async function watch(options) {
2302
619
  exports.DEFAULT_BROWSERSLIST_QUERY = DEFAULT_BROWSERSLIST_QUERY;
2303
620
  exports.build = build;
2304
621
  exports.check = check;
622
+ exports.createConsoleSpy = createConsoleSpy;
2305
623
  exports.createLogger = createLogger;
2306
624
  exports.defineConfig = defineConfig;
2307
625
  exports.defineTemplateOption = defineTemplateOption;
626
+ exports.fileExists = fileExists;
2308
627
  exports.getExtractMessagesConfig = getExtractMessagesConfig;
628
+ exports.getTargetPaths = getTargetPaths;
2309
629
  exports.init = init;
630
+ exports.isRecord = isRecord;
2310
631
  exports.loadConfig = loadConfig;
2311
632
  exports.loadPkg = loadPkg;
2312
633
  exports.loadPkgWithReporting = loadPkgWithReporting;