@sanity/pkg-utils 7.2.10-canary.4 → 7.4.0-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.
- package/bin/pkg-utils.js +2 -0
- package/dist/_chunks-cjs/index.cjs +1510 -45
- package/dist/_chunks-cjs/index.cjs.map +1 -1
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs +2 -2
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs.map +1 -1
- package/dist/{_chunks-cjs/build.cjs → _chunks-es/build.js} +28 -26
- package/dist/_chunks-es/build.js.map +1 -0
- package/dist/{_chunks-cjs/buildAction.cjs → _chunks-es/buildAction.js} +8 -6
- package/dist/_chunks-es/buildAction.js.map +1 -0
- package/dist/{_chunks-cjs/check.cjs → _chunks-es/check.js} +30 -26
- package/dist/_chunks-es/check.js.map +1 -0
- package/dist/_chunks-es/checkAction.js +17 -0
- package/dist/_chunks-es/checkAction.js.map +1 -0
- package/dist/{_chunks-cjs/consoleSpy.cjs → _chunks-es/consoleSpy.js} +105 -96
- package/dist/_chunks-es/consoleSpy.js.map +1 -0
- package/dist/_chunks-es/handleError.js +8 -0
- package/dist/_chunks-es/handleError.js.map +1 -0
- package/dist/_chunks-es/index.js +54 -1518
- package/dist/_chunks-es/index.js.map +1 -1
- package/dist/{_chunks-cjs/init.cjs → _chunks-es/init.js} +53 -47
- package/dist/_chunks-es/init.js.map +1 -0
- package/dist/_chunks-es/initAction.js +16 -0
- package/dist/_chunks-es/initAction.js.map +1 -0
- package/dist/_chunks-es/isRecord.js +37 -0
- package/dist/_chunks-es/isRecord.js.map +1 -0
- package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
- package/dist/_chunks-es/watch.js +146 -0
- package/dist/_chunks-es/watch.js.map +1 -0
- package/dist/_chunks-es/watchAction.js +17 -0
- package/dist/_chunks-es/watchAction.js.map +1 -0
- package/dist/{cli.cjs → cli.js} +9 -19
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +16 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
- package/bin/pkg-utils.cjs +0 -2
- package/dist/_chunks-cjs/build.cjs.map +0 -1
- package/dist/_chunks-cjs/buildAction.cjs.map +0 -1
- package/dist/_chunks-cjs/check.cjs.map +0 -1
- package/dist/_chunks-cjs/checkAction.cjs +0 -15
- package/dist/_chunks-cjs/checkAction.cjs.map +0 -1
- package/dist/_chunks-cjs/consoleSpy.cjs.map +0 -1
- package/dist/_chunks-cjs/handleError.cjs +0 -11
- package/dist/_chunks-cjs/handleError.cjs.map +0 -1
- package/dist/_chunks-cjs/init.cjs.map +0 -1
- package/dist/_chunks-cjs/initAction.cjs +0 -14
- package/dist/_chunks-cjs/initAction.cjs.map +0 -1
- package/dist/_chunks-cjs/isRecord.cjs +0 -39
- package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
- package/dist/_chunks-cjs/watch.cjs +0 -157
- package/dist/_chunks-cjs/watch.cjs.map +0 -1
- package/dist/_chunks-cjs/watchAction.cjs +0 -15
- package/dist/_chunks-cjs/watchAction.cjs.map +0 -1
- package/dist/cli.cjs.map +0 -1
- /package/dist/{cli.d.cts → cli.d.ts} +0 -0
|
@@ -18,7 +18,7 @@ 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
|
|
21
|
+
var path = require("node:path"), rimraf = require("rimraf"), 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");
|
|
22
22
|
function _interopDefaultCompat(e) {
|
|
23
23
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
|
24
24
|
}
|
|
@@ -37,7 +37,647 @@ function _interopNamespaceCompat(e) {
|
|
|
37
37
|
}
|
|
38
38
|
}), n.default = e, Object.freeze(n);
|
|
39
39
|
}
|
|
40
|
-
var
|
|
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
|
+
async function loadConfig(options) {
|
|
65
|
+
const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
|
|
66
|
+
if (!pkgPath) return;
|
|
67
|
+
const root = path__default.default.dirname(pkgPath), configFile = await findConfigFile(root);
|
|
68
|
+
if (!configFile || !configFile.startsWith(cwd))
|
|
69
|
+
return;
|
|
70
|
+
const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] }, { unregister } = globalThis.__DEV__ ? { unregister: () => {
|
|
71
|
+
} } : node.register(esbuildOptions), mod = require(configFile);
|
|
72
|
+
return unregister(), mod?.default || mod || void 0;
|
|
73
|
+
}
|
|
74
|
+
function assertLast(a, arr) {
|
|
75
|
+
const aIdx = arr.indexOf(a);
|
|
76
|
+
return aIdx === -1 ? !0 : aIdx === arr.length - 1;
|
|
77
|
+
}
|
|
78
|
+
function assertOrder(a, b, arr) {
|
|
79
|
+
const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
|
|
80
|
+
return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
|
|
81
|
+
}
|
|
82
|
+
const pkgSchema = zod.z.object({
|
|
83
|
+
type: zod.z.optional(zod.z.enum(["commonjs", "module"])),
|
|
84
|
+
name: zod.z.string(),
|
|
85
|
+
version: zod.z.string(),
|
|
86
|
+
license: zod.z.string(),
|
|
87
|
+
bin: zod.z.optional(zod.z.record(zod.z.string())),
|
|
88
|
+
dependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
89
|
+
devDependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
90
|
+
peerDependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
91
|
+
source: zod.z.optional(zod.z.string()),
|
|
92
|
+
main: zod.z.optional(zod.z.string()),
|
|
93
|
+
browser: zod.z.optional(zod.z.record(zod.z.string())),
|
|
94
|
+
module: zod.z.optional(zod.z.string()),
|
|
95
|
+
types: zod.z.optional(zod.z.string()),
|
|
96
|
+
exports: zod.z.optional(
|
|
97
|
+
zod.z.record(
|
|
98
|
+
zod.z.union([
|
|
99
|
+
zod.z.custom((val) => /^\.\/.*\.json$/.test(val)),
|
|
100
|
+
zod.z.custom((val) => /^\.\/.*\.css$/.test(val)),
|
|
101
|
+
zod.z.object({
|
|
102
|
+
types: zod.z.optional(zod.z.string()),
|
|
103
|
+
source: zod.z.optional(zod.z.string()),
|
|
104
|
+
browser: zod.z.optional(
|
|
105
|
+
zod.z.object({
|
|
106
|
+
source: zod.z.string(),
|
|
107
|
+
import: zod.z.optional(zod.z.string()),
|
|
108
|
+
require: zod.z.optional(zod.z.string())
|
|
109
|
+
})
|
|
110
|
+
),
|
|
111
|
+
node: zod.z.optional(
|
|
112
|
+
zod.z.object({
|
|
113
|
+
source: zod.z.optional(zod.z.string()),
|
|
114
|
+
import: zod.z.optional(zod.z.string()),
|
|
115
|
+
require: zod.z.optional(zod.z.string())
|
|
116
|
+
})
|
|
117
|
+
),
|
|
118
|
+
import: zod.z.optional(zod.z.string()),
|
|
119
|
+
require: zod.z.optional(zod.z.string()),
|
|
120
|
+
default: zod.z.string()
|
|
121
|
+
}),
|
|
122
|
+
zod.z.object({
|
|
123
|
+
types: zod.z.optional(zod.z.string()),
|
|
124
|
+
svelte: zod.z.string(),
|
|
125
|
+
default: zod.z.optional(zod.z.string())
|
|
126
|
+
})
|
|
127
|
+
])
|
|
128
|
+
)
|
|
129
|
+
),
|
|
130
|
+
browserslist: zod.z.optional(zod.z.union([zod.z.string(), zod.z.array(zod.z.string())])),
|
|
131
|
+
sideEffects: zod.z.optional(zod.z.union([zod.z.boolean(), zod.z.array(zod.z.string())])),
|
|
132
|
+
// @TODO type this properly
|
|
133
|
+
typesVersions: zod.z.optional(zod.z.any())
|
|
134
|
+
}), typoMap = /* @__PURE__ */ new Map();
|
|
135
|
+
for (const key of pkgSchema.keyof()._def.values)
|
|
136
|
+
typoMap.set(key.toUpperCase(), key);
|
|
137
|
+
function validatePkg(input) {
|
|
138
|
+
const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
|
|
139
|
+
const needle = key.toUpperCase();
|
|
140
|
+
return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
|
|
141
|
+
});
|
|
142
|
+
if (invalidKey)
|
|
143
|
+
throw new TypeError(
|
|
144
|
+
`
|
|
145
|
+
- package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
|
|
146
|
+
);
|
|
147
|
+
return pkg;
|
|
148
|
+
}
|
|
149
|
+
async function loadPkg(options) {
|
|
150
|
+
const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
|
|
151
|
+
if (!pkgPath) throw new Error("no package.json found");
|
|
152
|
+
const buf = await fs__default.default.readFile(pkgPath), raw = JSON.parse(buf.toString());
|
|
153
|
+
return validatePkg(raw), raw;
|
|
154
|
+
}
|
|
155
|
+
async function loadPkgWithReporting(options) {
|
|
156
|
+
const { cwd, logger, strict } = options;
|
|
157
|
+
try {
|
|
158
|
+
const pkg = await loadPkg({ cwd });
|
|
159
|
+
let shouldError = !1;
|
|
160
|
+
if (strict && (pkg.type || (shouldError = !0, logger.error(
|
|
161
|
+
'the `type` field in `./package.json` must be either "module" or "commonjs")'
|
|
162
|
+
))), pkg.exports) {
|
|
163
|
+
const _exports = Object.entries(pkg.exports);
|
|
164
|
+
for (const [expPath, exp] of _exports) {
|
|
165
|
+
if (typeof exp == "string" || "svelte" in exp)
|
|
166
|
+
continue;
|
|
167
|
+
const keys = Object.keys(exp);
|
|
168
|
+
exp.types && (shouldError = !0, logger.error(
|
|
169
|
+
`exports["${expPath}"]: the \`types\` condition shouldn't be used as dts files are generated in such a way that both CJS and ESM is supported`
|
|
170
|
+
)), exp.module && (shouldError = !0, logger.error(
|
|
171
|
+
`exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
|
|
172
|
+
)), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
|
|
173
|
+
`exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
|
|
174
|
+
)), exp.node.module && (shouldError = !0, logger.error(
|
|
175
|
+
`exports["${expPath}"]: the \`node.module\` condition shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the "dual package hazard"`
|
|
176
|
+
)), !exp.node.source && exp.node.import && (exp.node.require || exp.require) && (exp.node.import.endsWith(".cjs.js") || exp.node.import.endsWith(".cjs.mjs")) && (shouldError = !0, logger.error(
|
|
177
|
+
`exports["${expPath}"]: the \`node.import\` re-export pattern shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the "dual package hazard"`
|
|
178
|
+
)), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0, logger.error(
|
|
179
|
+
`exports["${expPath}"]: the \`node.require\` property isn't necessary as it's identical to \`require\``
|
|
180
|
+
)) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0, logger.error(
|
|
181
|
+
`exports["${expPath}"]: the \`node\` property should come before the \`require\` property`
|
|
182
|
+
))) : assertOrder("import", "require", keys) || logger.warn(
|
|
183
|
+
`exports["${expPath}"]: the \`import\` property should come before the \`require\` property`
|
|
184
|
+
), assertLast("default", keys) || (shouldError = !0, logger.error(
|
|
185
|
+
`exports["${expPath}"]: the \`default\` property should be the last property`
|
|
186
|
+
));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return shouldError && process.exit(1), pkg;
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (err instanceof zod.ZodError)
|
|
192
|
+
for (const issue of err.issues) {
|
|
193
|
+
if (issue.code === "invalid_type") {
|
|
194
|
+
logger.error(
|
|
195
|
+
[
|
|
196
|
+
`\`${formatPath(issue.path)}\` `,
|
|
197
|
+
`in \`./package.json\` must be of type ${chalk__default.default.magenta(issue.expected)} `,
|
|
198
|
+
`(received ${chalk__default.default.magenta(issue.received)})`
|
|
199
|
+
].join("")
|
|
200
|
+
);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
logger.error(issue);
|
|
204
|
+
}
|
|
205
|
+
else
|
|
206
|
+
logger.error(err);
|
|
207
|
+
process.exit(1);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function formatPath(segments) {
|
|
211
|
+
return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
|
|
212
|
+
}
|
|
213
|
+
function createLogger() {
|
|
214
|
+
return {
|
|
215
|
+
log: (...args) => {
|
|
216
|
+
console.log(...args);
|
|
217
|
+
},
|
|
218
|
+
info: (...args) => {
|
|
219
|
+
console.log(chalk__default.default.blue("[info]"), ...args);
|
|
220
|
+
},
|
|
221
|
+
warn: (...args) => {
|
|
222
|
+
console.log(chalk__default.default.yellow("[warning]"), ...args);
|
|
223
|
+
},
|
|
224
|
+
error: (...args) => {
|
|
225
|
+
console.log(chalk__default.default.red("[error]"), ...args);
|
|
226
|
+
},
|
|
227
|
+
success: (...args) => {
|
|
228
|
+
console.log(chalk__default.default.green("[success]"), ...args);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
function browserslistToEsbuild(browserslistConfig, options = {}) {
|
|
233
|
+
if (!browserslistConfig) {
|
|
234
|
+
const path2 = process.cwd();
|
|
235
|
+
browserslistConfig = browserslist__default.default.loadConfig({ path: path2, ...options });
|
|
236
|
+
}
|
|
237
|
+
const SUPPORTED_ESBUILD_TARGETS = [
|
|
238
|
+
"es",
|
|
239
|
+
"chrome",
|
|
240
|
+
"edge",
|
|
241
|
+
"firefox",
|
|
242
|
+
"ios",
|
|
243
|
+
"node",
|
|
244
|
+
"safari",
|
|
245
|
+
"opera",
|
|
246
|
+
"ie"
|
|
247
|
+
], UNSUPPORTED = ["android 4"], replaces = {
|
|
248
|
+
ios_saf: "ios",
|
|
249
|
+
android: "chrome"
|
|
250
|
+
}, separator = " ";
|
|
251
|
+
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) => {
|
|
252
|
+
const existingIndex = acc.findIndex((br) => br[0] === b[0]);
|
|
253
|
+
return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
|
|
254
|
+
}, []).map((b) => b.join(""));
|
|
255
|
+
}
|
|
256
|
+
function resolveConfigProperty(prop, initialValue) {
|
|
257
|
+
return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
|
|
258
|
+
}
|
|
259
|
+
const DEFAULT_BROWSERSLIST_QUERY = config__default.default;
|
|
260
|
+
function pathContains(containerPath, itemPath) {
|
|
261
|
+
return !path__default.default.relative(containerPath, itemPath).startsWith("..");
|
|
262
|
+
}
|
|
263
|
+
function findCommonDirPath(filePaths) {
|
|
264
|
+
let ret;
|
|
265
|
+
for (const filePath of filePaths) {
|
|
266
|
+
let dirPath = path__default.default.dirname(filePath);
|
|
267
|
+
if (!ret) {
|
|
268
|
+
ret = dirPath;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
for (; dirPath !== ret && (dirPath = path__default.default.dirname(dirPath), dirPath !== ret); ) {
|
|
272
|
+
if (pathContains(dirPath, ret)) {
|
|
273
|
+
ret = dirPath;
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
if (dirPath === ".") return;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return ret;
|
|
280
|
+
}
|
|
281
|
+
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
|
|
282
|
+
function getTargetPaths(_type, expOrBundle) {
|
|
283
|
+
const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
|
|
284
|
+
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(
|
|
285
|
+
expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
286
|
+
), expOrBundle.browser?.require && set.add(
|
|
287
|
+
expOrBundle.browser.require.replace(
|
|
288
|
+
fileEnding,
|
|
289
|
+
type === "commonjs" ? dtsEnding : ctsEnding
|
|
290
|
+
)
|
|
291
|
+
)), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
|
|
292
|
+
expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
293
|
+
), expOrBundle.node?.require && set.add(
|
|
294
|
+
expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
|
|
295
|
+
))), Array.from(set);
|
|
296
|
+
}
|
|
297
|
+
function isPkgExport$1(exp) {
|
|
298
|
+
return exp?.browser || exp?.node || exp?.default;
|
|
299
|
+
}
|
|
300
|
+
function isRecord(value) {
|
|
301
|
+
return !!value && !Array.isArray(value) && typeof value == "object";
|
|
302
|
+
}
|
|
303
|
+
const pkgExtMap = {
|
|
304
|
+
// pkg.type: "commonjs"
|
|
305
|
+
commonjs: {
|
|
306
|
+
commonjs: defaultEnding,
|
|
307
|
+
esm: mjsEnding
|
|
308
|
+
},
|
|
309
|
+
// pkg.type: "module"
|
|
310
|
+
module: {
|
|
311
|
+
commonjs: cjsEnding,
|
|
312
|
+
esm: defaultEnding
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
function validateExports(_exports, options) {
|
|
316
|
+
const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
|
|
317
|
+
for (const exp of _exports)
|
|
318
|
+
exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
|
|
319
|
+
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].require\` must end with "${ext.commonjs}"`
|
|
320
|
+
), exp.import && !exp.import.endsWith(ext.esm) && errors.push(
|
|
321
|
+
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].import\` must end with "${ext.esm}"`
|
|
322
|
+
);
|
|
323
|
+
return errors;
|
|
324
|
+
}
|
|
325
|
+
function parseExports(options) {
|
|
326
|
+
const { cwd, pkg, strict, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
|
|
327
|
+
kind === "warn" ? logger.warn(message) : errors.push(message);
|
|
328
|
+
};
|
|
329
|
+
if (!pkg.main && strict && strictOptions2.alwaysPackageJsonMain !== "off" && report(strictOptions2.alwaysPackageJsonMain, "package.json: `main` must be declared"), !Array.isArray(pkg.files) && strict && strictOptions2.alwaysPackageJsonFiles !== "off" && report(
|
|
330
|
+
strictOptions2.alwaysPackageJsonFiles,
|
|
331
|
+
"package.json: `files` should be used over `.npmignore`"
|
|
332
|
+
), pkg.source) {
|
|
333
|
+
if (strict && pkg.exports?.["."] && typeof pkg.exports["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source === pkg.source)
|
|
334
|
+
errors.push(
|
|
335
|
+
'package.json: the "source" property can be removed, as it is equal to exports["."].source.'
|
|
336
|
+
);
|
|
337
|
+
else if (!pkg.exports && pkg.main) {
|
|
338
|
+
const extMap = pkgExtMap[type], importExport = pkg.main.replace(fileEnding, extMap.esm), requireExport = pkg.main.replace(fileEnding, extMap.commonjs), defaultExport = pkg.main.replace(fileEnding, defaultEnding), maybeBrowserCondition = [];
|
|
339
|
+
if (pkg.browser) {
|
|
340
|
+
const browserConditions = [];
|
|
341
|
+
pkg.module && pkg.browser?.[pkg.module] ? browserConditions.push(
|
|
342
|
+
` "import": ${JSON.stringify(pkg.browser[pkg.module].replace(fileEnding, extMap.esm))}`
|
|
343
|
+
) : pkg.browser?.[pkg.main] && browserConditions.push(
|
|
344
|
+
` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`
|
|
345
|
+
), pkg.browser?.[pkg.main] && browserConditions.push(
|
|
346
|
+
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
|
|
347
|
+
), browserConditions.length && maybeBrowserCondition.push(
|
|
348
|
+
' "browser": {',
|
|
349
|
+
` "source": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,
|
|
350
|
+
...browserConditions,
|
|
351
|
+
" }"
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
errors.push(
|
|
355
|
+
...[
|
|
356
|
+
"package.json: `exports` are missing, it should be:",
|
|
357
|
+
'"exports": {',
|
|
358
|
+
' ".": {',
|
|
359
|
+
` "source": ${JSON.stringify(pkg.source)},`,
|
|
360
|
+
// If browser conditions are detected then add them to the suggestion
|
|
361
|
+
...maybeBrowserCondition.length > 0 ? maybeBrowserCondition : [],
|
|
362
|
+
type === "commonjs" && ` "import": ${JSON.stringify(importExport)},`,
|
|
363
|
+
type === "module" && ` "require": ${JSON.stringify(requireExport)},`,
|
|
364
|
+
` "default": ${JSON.stringify(defaultExport)}`,
|
|
365
|
+
" },",
|
|
366
|
+
' "./package.json": "./package.json"',
|
|
367
|
+
"}"
|
|
368
|
+
].filter(Boolean)
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (errors.length)
|
|
373
|
+
throw new Error(`
|
|
374
|
+
- ` + errors.join(`
|
|
375
|
+
- `));
|
|
376
|
+
if (!pkg.exports)
|
|
377
|
+
throw new Error(
|
|
378
|
+
`
|
|
379
|
+
- ` + [
|
|
380
|
+
"package.json: `exports` are missing, please set a minimal configuration, for example:",
|
|
381
|
+
'"exports": {',
|
|
382
|
+
' ".": {',
|
|
383
|
+
' "source": "./src/index.js",',
|
|
384
|
+
' "default": "./dist/index.js"',
|
|
385
|
+
" },",
|
|
386
|
+
' "./package.json": "./package.json"',
|
|
387
|
+
"}"
|
|
388
|
+
].join(`
|
|
389
|
+
- `)
|
|
390
|
+
);
|
|
391
|
+
const _exports = [];
|
|
392
|
+
strict && strictOptions2.noPackageJsonTypings !== "off" && "typings" in pkg && report(strictOptions2.noPackageJsonTypings, "package.json: `typings` should be `types`"), strict && strictOptions2.alwaysPackageJsonTypes !== "off" && !pkg.types && typeof pkg.exports?.["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source?.endsWith(".ts") && report(
|
|
393
|
+
strictOptions2.alwaysPackageJsonTypes,
|
|
394
|
+
"package.json: `types` must be declared for the npm listing to show as a TypeScript module."
|
|
395
|
+
), strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
|
|
396
|
+
for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
|
|
397
|
+
if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
|
|
398
|
+
exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
|
|
399
|
+
else if (exportPath.endsWith(".css"))
|
|
400
|
+
typeof exportEntry == "string" && !node_fs.existsSync(path.resolve(cwd, exportEntry)) ? errors.push(
|
|
401
|
+
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
|
|
402
|
+
) : typeof exportEntry != "string" && errors.push(
|
|
403
|
+
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
|
|
404
|
+
);
|
|
405
|
+
else if (!(isRecord(exportEntry) && "svelte" in exportEntry))
|
|
406
|
+
if (isPkgExport(exportEntry)) {
|
|
407
|
+
const exp = {
|
|
408
|
+
_exported: !0,
|
|
409
|
+
_path: exportPath,
|
|
410
|
+
...exportEntry
|
|
411
|
+
};
|
|
412
|
+
if (!exp.default) {
|
|
413
|
+
const fallback = type === "module" ? exp.import : exp.require;
|
|
414
|
+
fallback && (exp.default = fallback);
|
|
415
|
+
}
|
|
416
|
+
!exp.require && type === "commonjs" && exp.default && (exp.require = exp.default), !exp.import && type === "module" && exp.default && (exp.import = exp.default), exportPath === "." && (exportEntry.require && pkg.main && exportEntry.require !== pkg.main && errors.push(
|
|
417
|
+
'package.json: mismatch between "main" and "exports.require". These must be equal.'
|
|
418
|
+
), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
419
|
+
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
420
|
+
)), _exports.push(exp);
|
|
421
|
+
} else isRecord(exportEntry) || errors.push("package.json: exports must be an object");
|
|
422
|
+
if (errors.push(...validateExports(_exports, { pkg })), errors.length)
|
|
423
|
+
throw new Error(`
|
|
424
|
+
- ` + errors.join(`
|
|
425
|
+
- `));
|
|
426
|
+
return _exports;
|
|
427
|
+
}
|
|
428
|
+
function isPkgExport(value) {
|
|
429
|
+
return isRecord(value) && "source" in value && typeof value.source == "string";
|
|
430
|
+
}
|
|
431
|
+
async function loadTSConfig(options) {
|
|
432
|
+
const { cwd, tsconfigPath } = options, configPath = ts__default.default.findConfigFile(cwd, ts__default.default.sys.fileExists, tsconfigPath);
|
|
433
|
+
if (!configPath)
|
|
434
|
+
return;
|
|
435
|
+
const configFile = ts__default.default.readConfigFile(configPath, ts__default.default.sys.readFile);
|
|
436
|
+
return ts__default.default.parseJsonConfigFileContent(configFile.config, ts__default.default.sys, cwd);
|
|
437
|
+
}
|
|
438
|
+
function resolveBrowserTarget(versions) {
|
|
439
|
+
const target = versions.filter(
|
|
440
|
+
(version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
|
|
441
|
+
);
|
|
442
|
+
if (target.length !== 0)
|
|
443
|
+
return target;
|
|
444
|
+
}
|
|
445
|
+
function resolveNodeTarget(versions) {
|
|
446
|
+
const target = versions.filter((version) => version.startsWith("node"));
|
|
447
|
+
if (target.length !== 0)
|
|
448
|
+
return target;
|
|
449
|
+
}
|
|
450
|
+
const toggle = zod.z.union([zod.z.literal("error"), zod.z.literal("warn"), zod.z.literal("off")]), strictOptions = zod.z.object({
|
|
451
|
+
noPackageJsonTypings: toggle.default("error"),
|
|
452
|
+
noImplicitSideEffects: toggle.default("warn"),
|
|
453
|
+
noImplicitBrowsersList: toggle.default("warn"),
|
|
454
|
+
alwaysPackageJsonTypes: toggle.default("error"),
|
|
455
|
+
alwaysPackageJsonMain: toggle.default("error"),
|
|
456
|
+
alwaysPackageJsonFiles: toggle.default("error")
|
|
457
|
+
}).strict(), validationSchema = zod.z.object({
|
|
458
|
+
strictOptions: strictOptions.default({})
|
|
459
|
+
});
|
|
460
|
+
function parseStrictOptions(input) {
|
|
461
|
+
return validationSchema.parse({ strictOptions: input }, { errorMap: zodValidationError.errorMap }).strictOptions;
|
|
462
|
+
}
|
|
463
|
+
async function resolveBuildContext(options) {
|
|
464
|
+
const {
|
|
465
|
+
config: config2,
|
|
466
|
+
cwd,
|
|
467
|
+
emitDeclarationOnly = !1,
|
|
468
|
+
logger,
|
|
469
|
+
pkg,
|
|
470
|
+
strict,
|
|
471
|
+
tsconfig: tsconfigPath
|
|
472
|
+
} = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
|
|
473
|
+
let browserslist2 = pkg.browserslist;
|
|
474
|
+
if (!browserslist2) {
|
|
475
|
+
if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
|
|
476
|
+
if (strictOptions2.noImplicitBrowsersList === "error")
|
|
477
|
+
throw new Error(
|
|
478
|
+
'\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
|
|
479
|
+
);
|
|
480
|
+
logger.warn(
|
|
481
|
+
'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
|
|
485
|
+
}
|
|
486
|
+
const targetVersions = browserslistToEsbuild(browserslist2);
|
|
487
|
+
if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
|
|
488
|
+
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`";
|
|
489
|
+
if (strictOptions2.noImplicitSideEffects === "error")
|
|
490
|
+
throw new Error(msg);
|
|
491
|
+
logger.warn(msg);
|
|
492
|
+
}
|
|
493
|
+
const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
|
|
494
|
+
if (!nodeTarget)
|
|
495
|
+
throw new Error("no matching `node` target");
|
|
496
|
+
if (!webTarget)
|
|
497
|
+
throw new Error("no matching `web` target");
|
|
498
|
+
const target = {
|
|
499
|
+
"*": webTarget.concat(nodeTarget),
|
|
500
|
+
browser: webTarget,
|
|
501
|
+
node: nodeTarget
|
|
502
|
+
}, parsedExports = parseExports({
|
|
503
|
+
cwd,
|
|
504
|
+
pkg,
|
|
505
|
+
strict,
|
|
506
|
+
strictOptions: strictOptions2,
|
|
507
|
+
logger
|
|
508
|
+
}).reduce(
|
|
509
|
+
(acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
|
|
510
|
+
{}
|
|
511
|
+
), exports2 = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
|
|
512
|
+
...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
|
|
513
|
+
...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
|
|
514
|
+
], external = config2 && Array.isArray(config2.external) ? [...parsedExternal, ...config2.external] : resolveConfigProperty(config2?.external, parsedExternal), externalWithTypes = /* @__PURE__ */ new Set([pkg.name, ...external, ...external.map(transformPackageName)]), bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(
|
|
515
|
+
// Do not bundle anything that is marked as external
|
|
516
|
+
(_) => !externalWithTypes.has(_)
|
|
517
|
+
), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports2).flatMap((exportEntry) => [
|
|
518
|
+
exportEntry.import,
|
|
519
|
+
exportEntry.require,
|
|
520
|
+
exportEntry.browser?.import,
|
|
521
|
+
exportEntry.browser?.require,
|
|
522
|
+
exportEntry.node?.source && exportEntry.node.import,
|
|
523
|
+
exportEntry.node?.source && exportEntry.node.require
|
|
524
|
+
].filter(Boolean)).map((p) => path__default.default.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
|
|
525
|
+
if (commonDistPath === cwd)
|
|
526
|
+
throw new Error(
|
|
527
|
+
"all output files must share a common parent directory which is not the root package directory"
|
|
528
|
+
);
|
|
529
|
+
if (commonDistPath && !pathContains(cwd, commonDistPath))
|
|
530
|
+
throw new Error("all output files must be located within the package");
|
|
531
|
+
const configDistPath = config2?.dist ? path__default.default.resolve(cwd, config2.dist) : void 0;
|
|
532
|
+
if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
|
|
533
|
+
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");
|
|
534
|
+
const distPath = configDistPath || commonDistPath;
|
|
535
|
+
if (!distPath)
|
|
536
|
+
throw new Error("could not detect `dist` path");
|
|
537
|
+
return {
|
|
538
|
+
config: config2,
|
|
539
|
+
cwd,
|
|
540
|
+
distPath,
|
|
541
|
+
emitDeclarationOnly,
|
|
542
|
+
exports: exports2,
|
|
543
|
+
external,
|
|
544
|
+
bundledPackages,
|
|
545
|
+
files: [],
|
|
546
|
+
logger,
|
|
547
|
+
pkg,
|
|
548
|
+
runtime: config2?.runtime ?? "*",
|
|
549
|
+
strict,
|
|
550
|
+
target,
|
|
551
|
+
ts: {
|
|
552
|
+
config: tsconfig,
|
|
553
|
+
configPath: tsconfigPath
|
|
554
|
+
},
|
|
555
|
+
dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function transformPackageName(packageName) {
|
|
559
|
+
if (packageName.startsWith("@types/"))
|
|
560
|
+
return packageName;
|
|
561
|
+
if (packageName.startsWith("@")) {
|
|
562
|
+
const [scope, name] = packageName.split("/");
|
|
563
|
+
return `@types/${scope.slice(1)}__${name}`;
|
|
564
|
+
} else
|
|
565
|
+
return `@types/${packageName}`;
|
|
566
|
+
}
|
|
567
|
+
function resolveBuildTasks(ctx) {
|
|
568
|
+
const { config: config2, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
|
|
569
|
+
([_path, exp]) => ({ _path, ...exp })
|
|
570
|
+
), dtsTask2 = {
|
|
571
|
+
type: "build:dts",
|
|
572
|
+
entries: []
|
|
573
|
+
}, rolldownDtsTask2 = {}, rollupTasks = {};
|
|
574
|
+
function addRollupTaskEntry(format, runtime, entry) {
|
|
575
|
+
const buildId = `${format}:${runtime}`;
|
|
576
|
+
ctx.dts === "rolldown" && (rolldownDtsTask2[buildId] ? rolldownDtsTask2[buildId].entries.push(entry) : rolldownDtsTask2[buildId] = {
|
|
577
|
+
type: "rolldown:dts",
|
|
578
|
+
buildId,
|
|
579
|
+
entries: [entry],
|
|
580
|
+
runtime,
|
|
581
|
+
format,
|
|
582
|
+
target: target[runtime]
|
|
583
|
+
}), ctx.emitDeclarationOnly || (rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
584
|
+
type: "build:js",
|
|
585
|
+
buildId,
|
|
586
|
+
entries: [entry],
|
|
587
|
+
runtime,
|
|
588
|
+
format,
|
|
589
|
+
target: target[runtime]
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
if (ctx.dts === "api-extractor") {
|
|
593
|
+
for (const exp of exports2) {
|
|
594
|
+
const importId = path__default.default.join(pkg.name, exp._path);
|
|
595
|
+
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
596
|
+
importId,
|
|
597
|
+
exportPath: exp._path,
|
|
598
|
+
sourcePath: exp.source,
|
|
599
|
+
targetPaths: getTargetPaths(pkg.type, exp)
|
|
600
|
+
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
601
|
+
importId,
|
|
602
|
+
exportPath: exp._path,
|
|
603
|
+
sourcePath: exp.browser.source,
|
|
604
|
+
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
605
|
+
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
606
|
+
importId,
|
|
607
|
+
exportPath: exp._path,
|
|
608
|
+
sourcePath: exp.node.source,
|
|
609
|
+
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
for (const bundle of bundles)
|
|
613
|
+
if (bundle.source?.endsWith(".ts")) {
|
|
614
|
+
const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path__default.default.join(pkg.name, exportPath);
|
|
615
|
+
dtsTask2.entries.push({
|
|
616
|
+
importId,
|
|
617
|
+
exportPath,
|
|
618
|
+
sourcePath: bundle.source,
|
|
619
|
+
targetPaths: getTargetPaths(pkg.type, bundle)
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
dtsTask2.entries.length && tasks.push(dtsTask2);
|
|
623
|
+
}
|
|
624
|
+
for (const exp of exports2) {
|
|
625
|
+
const output = exp.require;
|
|
626
|
+
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
627
|
+
path: exp._path,
|
|
628
|
+
source: exp.source,
|
|
629
|
+
output
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
for (const exp of exports2) {
|
|
633
|
+
const output = exp.import;
|
|
634
|
+
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
635
|
+
path: exp._path,
|
|
636
|
+
source: exp.source,
|
|
637
|
+
output
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
for (const exp of exports2) {
|
|
641
|
+
const output = exp.browser?.require;
|
|
642
|
+
output && addRollupTaskEntry("commonjs", "browser", {
|
|
643
|
+
path: exp._path,
|
|
644
|
+
source: exp.browser?.source || exp.source,
|
|
645
|
+
output
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
for (const exp of exports2) {
|
|
649
|
+
const output = exp.browser?.import;
|
|
650
|
+
output && addRollupTaskEntry("esm", "browser", {
|
|
651
|
+
path: exp._path,
|
|
652
|
+
source: exp.browser?.source || exp.source,
|
|
653
|
+
output
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
for (const bundle of bundles) {
|
|
657
|
+
const idx = bundles.indexOf(bundle);
|
|
658
|
+
bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
|
|
659
|
+
path: `__$$bundle_cjs_${idx}$$__`,
|
|
660
|
+
source: bundle.source,
|
|
661
|
+
output: bundle.require
|
|
662
|
+
}), bundle.import && addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
|
|
663
|
+
path: `__$$bundle_esm_${idx}$$__`,
|
|
664
|
+
source: bundle.source,
|
|
665
|
+
output: bundle.import
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
return tasks.push(...Object.values(rolldownDtsTask2)), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
669
|
+
}
|
|
670
|
+
function createSpinner(msg) {
|
|
671
|
+
const startTime = Date.now();
|
|
672
|
+
return console.log(msg), {
|
|
673
|
+
complete: () => {
|
|
674
|
+
console.log(`${chalk__default.default.green("[success]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
|
|
675
|
+
},
|
|
676
|
+
error: () => {
|
|
677
|
+
console.log(`${chalk__default.default.red("[error]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
}
|
|
41
681
|
function printExtractMessages(ctx, messages) {
|
|
42
682
|
const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
|
|
43
683
|
warnings.length && logger.log();
|
|
@@ -188,7 +828,7 @@ async function extractModuleBlocksFromTypes({
|
|
|
188
828
|
function extractModuleBlocks(fileContent) {
|
|
189
829
|
return recast.parse(fileContent, {
|
|
190
830
|
parser: typeScriptParser__default.default
|
|
191
|
-
}).program.body.filter((
|
|
831
|
+
}).program.body.filter((node2) => node2.type === "TSModuleDeclaration").map((node2) => recast.print(node2).code);
|
|
192
832
|
}
|
|
193
833
|
const LOG_LEVELS = {
|
|
194
834
|
error: "error",
|
|
@@ -334,7 +974,7 @@ async function extractTypes(options) {
|
|
|
334
974
|
return shouldCleanUpDts && await fs__default.default.unlink(typesPath), { extractorResult, messages };
|
|
335
975
|
}
|
|
336
976
|
async function doExtract(ctx, task) {
|
|
337
|
-
const { config, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
|
|
977
|
+
const { config: config2, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
|
|
338
978
|
if (!ts2.config || !ts2.configPath)
|
|
339
979
|
return { type: "dts", messages: [], results: [] };
|
|
340
980
|
const { outDir, rootDir = cwd } = ts2.config.options;
|
|
@@ -349,18 +989,18 @@ async function doExtract(ctx, task) {
|
|
|
349
989
|
path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
|
|
350
990
|
), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath)), result = await extractTypes({
|
|
351
991
|
bundledPackages: bundledPackages || [],
|
|
352
|
-
customTags:
|
|
992
|
+
customTags: config2?.extract?.customTags,
|
|
353
993
|
distPath: outDir,
|
|
354
994
|
exportPath,
|
|
355
995
|
files,
|
|
356
996
|
filePaths,
|
|
357
997
|
projectPath: cwd,
|
|
358
|
-
rules:
|
|
998
|
+
rules: config2?.extract?.rules,
|
|
359
999
|
sourceTypesPath,
|
|
360
1000
|
tsconfig: ts2.config,
|
|
361
1001
|
tmpPath,
|
|
362
1002
|
tsconfigPath: path__default.default.resolve(cwd, ts2.configPath || "tsconfig.json"),
|
|
363
|
-
extractorDisabled:
|
|
1003
|
+
extractorDisabled: config2?.extract?.enabled === !1
|
|
364
1004
|
});
|
|
365
1005
|
messages.push(...result.messages);
|
|
366
1006
|
const errors = result.messages.filter((msg) => msg.logLevel === "error");
|
|
@@ -405,7 +1045,7 @@ const dtsTask = {
|
|
|
405
1045
|
].join(`
|
|
406
1046
|
`),
|
|
407
1047
|
exec: (ctx, task) => {
|
|
408
|
-
const { config, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
|
|
1048
|
+
const { config: config2, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
|
|
409
1049
|
return new rxjs.Observable((observer) => {
|
|
410
1050
|
if (!tsContext.config || !tsContext.configPath) {
|
|
411
1051
|
observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
|
|
@@ -459,19 +1099,19 @@ const dtsTask = {
|
|
|
459
1099
|
try {
|
|
460
1100
|
const result = await extractTypes({
|
|
461
1101
|
bundledPackages: bundledPackages || [],
|
|
462
|
-
customTags:
|
|
1102
|
+
customTags: config2?.extract?.customTags,
|
|
463
1103
|
cwd,
|
|
464
1104
|
distPath: outDir,
|
|
465
1105
|
exportPath,
|
|
466
1106
|
files,
|
|
467
1107
|
filePaths,
|
|
468
1108
|
projectPath: cwd,
|
|
469
|
-
rules:
|
|
1109
|
+
rules: config2?.extract?.rules,
|
|
470
1110
|
sourceTypesPath,
|
|
471
1111
|
tsconfig: tsContext.config,
|
|
472
1112
|
tmpPath,
|
|
473
1113
|
tsconfigPath: path__default.default.resolve(cwd, tsContext.configPath || "tsconfig.json"),
|
|
474
|
-
extractorDisabled:
|
|
1114
|
+
extractorDisabled: config2?.extract?.enabled === !1
|
|
475
1115
|
});
|
|
476
1116
|
messages.push(...result.messages), results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
|
|
477
1117
|
} catch (err) {
|
|
@@ -505,14 +1145,28 @@ const dtsTask = {
|
|
|
505
1145
|
const { logger } = ctx;
|
|
506
1146
|
err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
|
|
507
1147
|
}
|
|
508
|
-
}
|
|
1148
|
+
};
|
|
1149
|
+
function createConsoleSpy(options) {
|
|
1150
|
+
const { onRestored } = options || {}, original = {
|
|
1151
|
+
log: console.log,
|
|
1152
|
+
warn: console.warn,
|
|
1153
|
+
error: console.error
|
|
1154
|
+
}, messages = [];
|
|
1155
|
+
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 }), {
|
|
1156
|
+
messages,
|
|
1157
|
+
restore: () => {
|
|
1158
|
+
console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
const rolldownDtsTask = {
|
|
509
1163
|
name: (ctx, task) => {
|
|
510
1164
|
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 ? [
|
|
511
1165
|
" bundles:",
|
|
512
1166
|
...bundleEntries.map(
|
|
513
1167
|
(e) => [
|
|
514
1168
|
" - ",
|
|
515
|
-
`${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
|
|
1169
|
+
`${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
|
|
516
1170
|
].join("")
|
|
517
1171
|
)
|
|
518
1172
|
] : [], entriesLines = entries.length ? [
|
|
@@ -521,7 +1175,7 @@ const dtsTask = {
|
|
|
521
1175
|
(e) => [
|
|
522
1176
|
" - ",
|
|
523
1177
|
`${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
|
|
524
|
-
`${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
|
|
1178
|
+
`${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
|
|
525
1179
|
].join("")
|
|
526
1180
|
)
|
|
527
1181
|
] : [];
|
|
@@ -547,7 +1201,7 @@ async function execPromise$1(ctx, task) {
|
|
|
547
1201
|
Promise.resolve().then(function() {
|
|
548
1202
|
return require("./resolveRolldownConfig.cjs");
|
|
549
1203
|
})
|
|
550
|
-
]), { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy
|
|
1204
|
+
]), { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
|
|
551
1205
|
onRestored: (messages) => {
|
|
552
1206
|
for (const msg of messages) {
|
|
553
1207
|
const text = String(msg.args[0]);
|
|
@@ -559,7 +1213,7 @@ async function execPromise$1(ctx, task) {
|
|
|
559
1213
|
const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
|
|
560
1214
|
...inputOptions,
|
|
561
1215
|
onwarn(warning) {
|
|
562
|
-
consoleSpy
|
|
1216
|
+
consoleSpy.messages.push({
|
|
563
1217
|
type: "warn",
|
|
564
1218
|
code: warning.code,
|
|
565
1219
|
args: [warning.message]
|
|
@@ -574,20 +1228,30 @@ async function execPromise$1(ctx, task) {
|
|
|
574
1228
|
type: "chunk",
|
|
575
1229
|
path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
|
|
576
1230
|
});
|
|
577
|
-
await bundle.write(outputOptions), await bundle.close(), consoleSpy
|
|
1231
|
+
await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
|
|
578
1232
|
} catch (err) {
|
|
579
|
-
throw consoleSpy
|
|
1233
|
+
throw consoleSpy.restore(), err;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
function replaceFileEnding(path2) {
|
|
1237
|
+
switch (!0) {
|
|
1238
|
+
case path2.endsWith(".mjs"):
|
|
1239
|
+
return path2.replace(/\.mjs$/, ".d.mts");
|
|
1240
|
+
case path2.endsWith(".cjs"):
|
|
1241
|
+
return path2.replace(/\.cjs$/, ".d.cts");
|
|
1242
|
+
default:
|
|
1243
|
+
return path2.replace(/\.js$/, ".d.ts");
|
|
580
1244
|
}
|
|
581
1245
|
}
|
|
582
1246
|
function resolveRollupConfig(ctx, buildTask) {
|
|
583
|
-
const { format, runtime, target } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt =
|
|
1247
|
+
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(
|
|
584
1248
|
Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path__default.default.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
|
|
585
1249
|
), entries = buildTask.entries.map((entry) => ({
|
|
586
1250
|
...entry,
|
|
587
1251
|
name: path__default.default.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
|
|
588
1252
|
}), {}), 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(
|
|
589
|
-
Object.entries(
|
|
590
|
-
), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } =
|
|
1253
|
+
Object.entries(config2?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
|
|
1254
|
+
), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config2?.rollup || {}, defaultPlugins = [
|
|
591
1255
|
replace__default.default({
|
|
592
1256
|
preventAssignment: !0,
|
|
593
1257
|
values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
|
|
@@ -613,14 +1277,14 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
613
1277
|
}),
|
|
614
1278
|
commonjs__default.default(),
|
|
615
1279
|
json__default.default(),
|
|
616
|
-
(
|
|
1280
|
+
(config2?.babel?.reactCompiler || config2?.babel?.styledComponents) && pluginBabel.babel({
|
|
617
1281
|
babelrc: !1,
|
|
618
1282
|
presets: ["@babel/preset-typescript"],
|
|
619
1283
|
babelHelpers: "bundled",
|
|
620
1284
|
extensions: [".ts", ".tsx", ".js", ".jsx"],
|
|
621
1285
|
plugins: [
|
|
622
1286
|
// The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
|
|
623
|
-
|
|
1287
|
+
config2?.babel?.styledComponents && [
|
|
624
1288
|
"babel-plugin-styled-components",
|
|
625
1289
|
{
|
|
626
1290
|
// 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``"
|
|
@@ -631,35 +1295,35 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
631
1295
|
pure: !0,
|
|
632
1296
|
// disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
|
|
633
1297
|
cssProp: !1,
|
|
634
|
-
...typeof
|
|
1298
|
+
...typeof config2.babel.styledComponents == "object" ? config2.babel.styledComponents : {}
|
|
635
1299
|
}
|
|
636
1300
|
],
|
|
637
|
-
|
|
1301
|
+
config2?.babel?.reactCompiler && [
|
|
638
1302
|
"babel-plugin-react-compiler",
|
|
639
|
-
|
|
1303
|
+
config2?.reactCompilerOptions || {}
|
|
640
1304
|
]
|
|
641
1305
|
].filter(Boolean)
|
|
642
1306
|
}),
|
|
643
1307
|
esbuild__default.default({
|
|
644
|
-
jsx:
|
|
645
|
-
jsxFactory:
|
|
646
|
-
jsxFragment:
|
|
647
|
-
jsxImportSource:
|
|
1308
|
+
jsx: config2?.jsx ?? "automatic",
|
|
1309
|
+
jsxFactory: config2?.jsxFactory ?? "createElement",
|
|
1310
|
+
jsxFragment: config2?.jsxFragment ?? "Fragment",
|
|
1311
|
+
jsxImportSource: config2?.jsxImportSource ?? "react",
|
|
648
1312
|
target,
|
|
649
1313
|
tsconfig: ctx.ts.configPath || "tsconfig.json",
|
|
650
1314
|
treeShaking: !0,
|
|
651
|
-
minifySyntax:
|
|
1315
|
+
minifySyntax: config2?.minify !== !1,
|
|
652
1316
|
supported: {
|
|
653
1317
|
"template-literal": !0
|
|
654
1318
|
}
|
|
655
1319
|
}),
|
|
656
|
-
Array.isArray(
|
|
1320
|
+
Array.isArray(config2?.babel?.plugins) && pluginBabel.getBabelOutputPlugin({
|
|
657
1321
|
babelrc: !1,
|
|
658
|
-
plugins:
|
|
1322
|
+
plugins: config2.babel.plugins
|
|
659
1323
|
}),
|
|
660
1324
|
enableOptimizeLodash && rollupPlugin.optimizeLodashImports({
|
|
661
1325
|
useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
|
|
662
|
-
...typeof
|
|
1326
|
+
...typeof config2?.rollup?.optimizeLodash == "boolean" ? {} : config2?.rollup?.optimizeLodash
|
|
663
1327
|
}),
|
|
664
1328
|
minify && terser__default.default({
|
|
665
1329
|
compress: { directives: !1, passes: 10 },
|
|
@@ -672,7 +1336,7 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
672
1336
|
preserve_annotations: !0
|
|
673
1337
|
}
|
|
674
1338
|
})
|
|
675
|
-
].filter(Boolean), userPlugins =
|
|
1339
|
+
].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}`;
|
|
676
1340
|
return {
|
|
677
1341
|
inputOptions: {
|
|
678
1342
|
context: cwd,
|
|
@@ -706,9 +1370,9 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
706
1370
|
preset: "recommended",
|
|
707
1371
|
propertyReadSideEffects: !1,
|
|
708
1372
|
moduleSideEffects: "no-external",
|
|
709
|
-
...
|
|
1373
|
+
...config2?.rollup?.treeshake
|
|
710
1374
|
},
|
|
711
|
-
experimentalLogSideEffects:
|
|
1375
|
+
experimentalLogSideEffects: config2?.rollup?.experimentalLogSideEffects
|
|
712
1376
|
},
|
|
713
1377
|
outputOptions: {
|
|
714
1378
|
chunkFileNames,
|
|
@@ -718,10 +1382,10 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
718
1382
|
esModule: !0,
|
|
719
1383
|
format,
|
|
720
1384
|
interop: "compat",
|
|
721
|
-
sourcemap:
|
|
1385
|
+
sourcemap: config2?.sourcemap ?? !0,
|
|
722
1386
|
hoistTransitiveImports: !1,
|
|
723
1387
|
minifyInternalExports: minify,
|
|
724
|
-
...
|
|
1388
|
+
...config2?.rollup?.output
|
|
725
1389
|
}
|
|
726
1390
|
};
|
|
727
1391
|
}
|
|
@@ -769,7 +1433,7 @@ const rollupTask = {
|
|
|
769
1433
|
}
|
|
770
1434
|
};
|
|
771
1435
|
async function execPromise(ctx, task) {
|
|
772
|
-
const { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy
|
|
1436
|
+
const { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
|
|
773
1437
|
onRestored: (messages) => {
|
|
774
1438
|
for (const msg of messages) {
|
|
775
1439
|
const text = String(msg.args[0]);
|
|
@@ -781,7 +1445,7 @@ async function execPromise(ctx, task) {
|
|
|
781
1445
|
const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup.rollup({
|
|
782
1446
|
...inputOptions,
|
|
783
1447
|
onwarn(warning) {
|
|
784
|
-
consoleSpy
|
|
1448
|
+
consoleSpy.messages.push({
|
|
785
1449
|
type: "warn",
|
|
786
1450
|
code: warning.code,
|
|
787
1451
|
args: [warning.message]
|
|
@@ -796,9 +1460,9 @@ async function execPromise(ctx, task) {
|
|
|
796
1460
|
type: "chunk",
|
|
797
1461
|
path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
|
|
798
1462
|
});
|
|
799
|
-
await bundle.write(outputOptions), await bundle.close(), consoleSpy
|
|
1463
|
+
await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
|
|
800
1464
|
} catch (err) {
|
|
801
|
-
throw consoleSpy
|
|
1465
|
+
throw consoleSpy.restore(), err;
|
|
802
1466
|
}
|
|
803
1467
|
}
|
|
804
1468
|
const rollupWatchTask = {
|
|
@@ -846,7 +1510,808 @@ const rollupWatchTask = {
|
|
|
846
1510
|
"watch:dts": dtsWatchTask,
|
|
847
1511
|
"watch:js": rollupWatchTask
|
|
848
1512
|
};
|
|
849
|
-
|
|
1513
|
+
async function build(options) {
|
|
1514
|
+
const {
|
|
1515
|
+
cwd,
|
|
1516
|
+
emitDeclarationOnly,
|
|
1517
|
+
strict = !1,
|
|
1518
|
+
tsconfig: tsconfigOption,
|
|
1519
|
+
clean = !1
|
|
1520
|
+
} = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
|
|
1521
|
+
config: config2,
|
|
1522
|
+
cwd,
|
|
1523
|
+
emitDeclarationOnly,
|
|
1524
|
+
logger,
|
|
1525
|
+
pkg,
|
|
1526
|
+
strict,
|
|
1527
|
+
tsconfig
|
|
1528
|
+
});
|
|
1529
|
+
clean && (logger.log(
|
|
1530
|
+
`Deleting the \`dist\` folder: './${path__default.default.relative(cwd, ctx.distPath)}' before building...`
|
|
1531
|
+
), await rimraf.rimraf(ctx.distPath));
|
|
1532
|
+
const buildTasks = resolveBuildTasks(ctx);
|
|
1533
|
+
for (const task of buildTasks) {
|
|
1534
|
+
const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName);
|
|
1535
|
+
try {
|
|
1536
|
+
const result = await handler.exec(ctx, task).toPromise();
|
|
1537
|
+
spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
|
|
1538
|
+
} catch (err) {
|
|
1539
|
+
if (spinner.error(), err instanceof Error) {
|
|
1540
|
+
const RE_CWD = new RegExp(`${cwd}`, "g");
|
|
1541
|
+
ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
|
|
1542
|
+
}
|
|
1543
|
+
handler.error(ctx, task, err), process.exit(1);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
function getFilesize(file) {
|
|
1548
|
+
const stats = node_fs.statSync(file);
|
|
1549
|
+
return prettyBytes__default.default(stats.size);
|
|
1550
|
+
}
|
|
1551
|
+
function getFileInfo(cwd, filePath) {
|
|
1552
|
+
const p = path__default.default.resolve(cwd, filePath), exists = fileExists(p), size = exists ? getFilesize(p) : void 0;
|
|
1553
|
+
return { exists, size };
|
|
1554
|
+
}
|
|
1555
|
+
function printPackageTree(ctx) {
|
|
1556
|
+
const { cwd, exports: exports2, logger, pkg } = ctx;
|
|
1557
|
+
if (!exports2) return;
|
|
1558
|
+
logger.log(`${chalk__default.default.blue(pkg.name)}@${chalk__default.default.green(pkg.version)}`);
|
|
1559
|
+
const tree = {};
|
|
1560
|
+
pkg.type && (tree.type = chalk__default.default.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
|
|
1561
|
+
Object.entries(pkg.bin).map(([name, file]) => [chalk__default.default.cyan(name), fileInfo(file)])
|
|
1562
|
+
));
|
|
1563
|
+
function fileInfo(file) {
|
|
1564
|
+
const info = getFileInfo(cwd, file);
|
|
1565
|
+
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")}`;
|
|
1566
|
+
}
|
|
1567
|
+
tree.exports = Object.fromEntries(
|
|
1568
|
+
Object.entries(exports2).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
|
|
1569
|
+
const exp = {
|
|
1570
|
+
source: fileInfo(entry.source),
|
|
1571
|
+
browser: void 0,
|
|
1572
|
+
require: void 0,
|
|
1573
|
+
node: void 0,
|
|
1574
|
+
import: void 0,
|
|
1575
|
+
default: fileInfo(entry.default)
|
|
1576
|
+
};
|
|
1577
|
+
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];
|
|
1578
|
+
})
|
|
1579
|
+
), logger.log(treeify__default.default.asTree(tree, !0, !0));
|
|
1580
|
+
}
|
|
1581
|
+
async function check(options) {
|
|
1582
|
+
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 });
|
|
1583
|
+
if (printPackageTree(ctx), strict) {
|
|
1584
|
+
const missingFiles = [];
|
|
1585
|
+
for (const [, exp] of Object.entries(ctx.exports || {}))
|
|
1586
|
+
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);
|
|
1587
|
+
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));
|
|
1588
|
+
const exportPaths = {
|
|
1589
|
+
require: [],
|
|
1590
|
+
import: []
|
|
1591
|
+
};
|
|
1592
|
+
for (const exp of Object.values(ctx.exports || {}))
|
|
1593
|
+
exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
|
|
1594
|
+
const external = [
|
|
1595
|
+
...Object.keys(pkg.dependencies || {}),
|
|
1596
|
+
...Object.keys(pkg.devDependencies || {})
|
|
1597
|
+
], consoleSpy = createConsoleSpy();
|
|
1598
|
+
exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
async function checkExports(exportPaths, options) {
|
|
1602
|
+
const { cwd, external, format, logger } = options, code = exportPaths.map((id) => format ? `import('${id}');` : `require('${id}');`).join(`
|
|
1603
|
+
`);
|
|
1604
|
+
try {
|
|
1605
|
+
const esbuildResult = await esbuild__default$1.default.build({
|
|
1606
|
+
bundle: !0,
|
|
1607
|
+
external,
|
|
1608
|
+
format,
|
|
1609
|
+
logLevel: "silent",
|
|
1610
|
+
// otherwise output maps to stdout as we're using stdin
|
|
1611
|
+
outfile: "/dev/null",
|
|
1612
|
+
platform: "node",
|
|
1613
|
+
stdin: {
|
|
1614
|
+
contents: code,
|
|
1615
|
+
loader: "js",
|
|
1616
|
+
resolveDir: cwd
|
|
1617
|
+
}
|
|
1618
|
+
});
|
|
1619
|
+
if (esbuildResult.errors.length > 0) {
|
|
1620
|
+
for (const msg of esbuildResult.errors)
|
|
1621
|
+
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1622
|
+
process.exit(1);
|
|
1623
|
+
}
|
|
1624
|
+
const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
|
|
1625
|
+
(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
|
|
1626
|
+
});
|
|
1627
|
+
for (const msg of esbuildWarnings)
|
|
1628
|
+
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1629
|
+
} catch (err) {
|
|
1630
|
+
if (isEsbuildFailure(err)) {
|
|
1631
|
+
const { errors } = err;
|
|
1632
|
+
for (const msg of errors)
|
|
1633
|
+
printEsbuildMessage(logger.error, msg), logger.log();
|
|
1634
|
+
} else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
|
|
1635
|
+
process.exit(1);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
function printEsbuildMessage(log, msg) {
|
|
1639
|
+
msg.location ? log(
|
|
1640
|
+
[
|
|
1641
|
+
`${msg.detail || msg.text}
|
|
1642
|
+
`,
|
|
1643
|
+
`${msg.location.line} | ${msg.location.lineText}
|
|
1644
|
+
`,
|
|
1645
|
+
`in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
|
|
1646
|
+
].join("")
|
|
1647
|
+
) : log(msg.detail || msg.text);
|
|
1648
|
+
}
|
|
1649
|
+
function isEsbuildFailure(err) {
|
|
1650
|
+
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);
|
|
1651
|
+
}
|
|
1652
|
+
function isEsbuildMessage(msg) {
|
|
1653
|
+
return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
|
|
1654
|
+
}
|
|
1655
|
+
function defineConfig(configOptions) {
|
|
1656
|
+
return configOptions;
|
|
1657
|
+
}
|
|
1658
|
+
function defineTemplateOption(option) {
|
|
1659
|
+
return option;
|
|
1660
|
+
}
|
|
1661
|
+
const promptsTypes = {
|
|
1662
|
+
string: "text"
|
|
1663
|
+
};
|
|
1664
|
+
async function createFromTemplate(options) {
|
|
1665
|
+
const { cwd, logger, packagePath, template: templateOrResolver } = options, template = typeof templateOrResolver == "function" ? await templateOrResolver({ cwd, logger, packagePath }) : templateOrResolver;
|
|
1666
|
+
logger.log("create new package at", path.relative(cwd, packagePath));
|
|
1667
|
+
const templateOptions = {};
|
|
1668
|
+
for (const templateOption of template.options) {
|
|
1669
|
+
const templateValidate = templateOption.validate, res = await prompts__default.default(
|
|
1670
|
+
{
|
|
1671
|
+
type: promptsTypes[templateOption.type],
|
|
1672
|
+
name: templateOption.name,
|
|
1673
|
+
message: templateOption.description,
|
|
1674
|
+
validate: templateValidate ? (prev) => templateValidate(prev) : void 0,
|
|
1675
|
+
initial: typeof templateOption.initial == "function" ? templateOption.initial(templateOptions) : templateOption.initial
|
|
1676
|
+
},
|
|
1677
|
+
{ onCancel: () => process.exit(0) }
|
|
1678
|
+
);
|
|
1679
|
+
templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
|
|
1680
|
+
}
|
|
1681
|
+
const features = {};
|
|
1682
|
+
for (const templateFeature of template.features) {
|
|
1683
|
+
const res = templateFeature.optional ? await prompts__default.default(
|
|
1684
|
+
{
|
|
1685
|
+
type: "confirm",
|
|
1686
|
+
name: "confirm",
|
|
1687
|
+
message: `use ${templateFeature.name}?`,
|
|
1688
|
+
initial: templateFeature.initial
|
|
1689
|
+
},
|
|
1690
|
+
{ onCancel: () => process.exit(0) }
|
|
1691
|
+
) : void 0;
|
|
1692
|
+
features[templateFeature.name] = res?.confirm || !templateFeature.optional;
|
|
1693
|
+
}
|
|
1694
|
+
const files = await template.getFiles(templateOptions, features);
|
|
1695
|
+
files.sort((a, b) => a.name.localeCompare(b.name));
|
|
1696
|
+
for (const file of files) {
|
|
1697
|
+
const filePath = path.resolve(packagePath, file.name);
|
|
1698
|
+
await mkdirp.mkdirp(path.dirname(filePath)), await fs.writeFile(filePath, file.contents.trim() + `
|
|
1699
|
+
`), logger.success(`wrote ${path.relative(cwd, filePath)}`);
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
async function isEmptyDirectory(dirPath) {
|
|
1703
|
+
return (await fs.readdir(dirPath)).length === 0;
|
|
1704
|
+
}
|
|
1705
|
+
const overridableDefaults = {
|
|
1706
|
+
endOfLine: "lf",
|
|
1707
|
+
tabWidth: 2,
|
|
1708
|
+
useTabs: !1
|
|
1709
|
+
}, config = {
|
|
1710
|
+
...overridableDefaults,
|
|
1711
|
+
printWidth: 100,
|
|
1712
|
+
semi: !1,
|
|
1713
|
+
singleQuote: !0,
|
|
1714
|
+
quoteProps: "consistent",
|
|
1715
|
+
bracketSpacing: !1,
|
|
1716
|
+
plugins: ["prettier-plugin-packagejson"],
|
|
1717
|
+
overrides: [
|
|
1718
|
+
{
|
|
1719
|
+
files: ["*.json5"],
|
|
1720
|
+
options: {
|
|
1721
|
+
quoteProps: "preserve",
|
|
1722
|
+
singleQuote: !1
|
|
1723
|
+
}
|
|
1724
|
+
},
|
|
1725
|
+
{
|
|
1726
|
+
files: ["*.yml"],
|
|
1727
|
+
options: {
|
|
1728
|
+
singleQuote: !1
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
]
|
|
1732
|
+
}, RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i, defaultTemplate = async ({ cwd, logger, packagePath }) => {
|
|
1733
|
+
const gitConfig = getGitUserConfig(cwd);
|
|
1734
|
+
return {
|
|
1735
|
+
options: [
|
|
1736
|
+
{
|
|
1737
|
+
name: "repo",
|
|
1738
|
+
type: "string",
|
|
1739
|
+
description: "git url",
|
|
1740
|
+
validate: (v) => {
|
|
1741
|
+
if (!v) return !0;
|
|
1742
|
+
try {
|
|
1743
|
+
return gitUrlParse__default.default(v), !0;
|
|
1744
|
+
} catch {
|
|
1745
|
+
return "invalid git url";
|
|
1746
|
+
}
|
|
1747
|
+
},
|
|
1748
|
+
parse: (v) => {
|
|
1749
|
+
if (!v) return null;
|
|
1750
|
+
const result = gitUrlParse__default.default(v);
|
|
1751
|
+
return { source: result.source, owner: result.owner, name: result.name };
|
|
1752
|
+
}
|
|
1753
|
+
},
|
|
1754
|
+
{
|
|
1755
|
+
name: "pkgName",
|
|
1756
|
+
type: "string",
|
|
1757
|
+
description: "package name",
|
|
1758
|
+
initial: (options) => options.repo?.name || void 0,
|
|
1759
|
+
validate: (v) => v ? RE_NAME.exec(v) ? !0 : "invalid package name" : "package name is required",
|
|
1760
|
+
parse: (v) => {
|
|
1761
|
+
if (!v)
|
|
1762
|
+
throw new Error("package name is required");
|
|
1763
|
+
if (!RE_NAME.exec(v))
|
|
1764
|
+
throw new Error("invalid package name");
|
|
1765
|
+
const [scope, name] = v.split("/");
|
|
1766
|
+
return { scope, name, fullName: v };
|
|
1767
|
+
}
|
|
1768
|
+
},
|
|
1769
|
+
{
|
|
1770
|
+
name: "description",
|
|
1771
|
+
type: "string",
|
|
1772
|
+
description: "package description"
|
|
1773
|
+
},
|
|
1774
|
+
{
|
|
1775
|
+
name: "authorName",
|
|
1776
|
+
type: "string",
|
|
1777
|
+
description: "package author name",
|
|
1778
|
+
initial: gitConfig.user
|
|
1779
|
+
},
|
|
1780
|
+
{
|
|
1781
|
+
name: "authorEmail",
|
|
1782
|
+
type: "string",
|
|
1783
|
+
description: "package author email",
|
|
1784
|
+
initial: gitConfig.email
|
|
1785
|
+
},
|
|
1786
|
+
{
|
|
1787
|
+
name: "license",
|
|
1788
|
+
type: "string",
|
|
1789
|
+
description: "package license",
|
|
1790
|
+
initial: "MIT",
|
|
1791
|
+
validate: (v) => v ? !0 : "license is required"
|
|
1792
|
+
}
|
|
1793
|
+
],
|
|
1794
|
+
features: [
|
|
1795
|
+
{
|
|
1796
|
+
name: "eslint",
|
|
1797
|
+
optional: !0,
|
|
1798
|
+
initial: !0
|
|
1799
|
+
},
|
|
1800
|
+
{
|
|
1801
|
+
name: "prettier",
|
|
1802
|
+
optional: !0,
|
|
1803
|
+
initial: !0
|
|
1804
|
+
},
|
|
1805
|
+
{
|
|
1806
|
+
name: "typescript",
|
|
1807
|
+
optional: !0,
|
|
1808
|
+
initial: !0
|
|
1809
|
+
}
|
|
1810
|
+
],
|
|
1811
|
+
async getFiles(options, features) {
|
|
1812
|
+
const { pkgName, repo } = options, { fullName: name } = pkgName, author = [options.authorName, options.authorEmail && `<${options.authorEmail}>`].filter(Boolean).join(" ") ?? void 0, pkgJson = {
|
|
1813
|
+
name,
|
|
1814
|
+
version: "0.0.0",
|
|
1815
|
+
description: options.description ?? void 0,
|
|
1816
|
+
keywords: [],
|
|
1817
|
+
homepage: void 0,
|
|
1818
|
+
bugs: void 0,
|
|
1819
|
+
repository: void 0,
|
|
1820
|
+
license: options.license,
|
|
1821
|
+
author,
|
|
1822
|
+
sideEffects: !1,
|
|
1823
|
+
type: "module",
|
|
1824
|
+
exports: {
|
|
1825
|
+
".": {
|
|
1826
|
+
source: features.typescript ? "./src/index.ts" : "./src/index.js",
|
|
1827
|
+
require: "./dist/index.cjs",
|
|
1828
|
+
default: "./dist/index.js"
|
|
1829
|
+
},
|
|
1830
|
+
"./package.json": "./package.json"
|
|
1831
|
+
},
|
|
1832
|
+
main: "./dist/index.cjs",
|
|
1833
|
+
module: "./dist/index.js",
|
|
1834
|
+
types: void 0,
|
|
1835
|
+
files: ["dist", "src"],
|
|
1836
|
+
scripts: {
|
|
1837
|
+
build: "pkg build --strict --clean --check",
|
|
1838
|
+
format: features.prettier ? "prettier --write --cache --ignore-unknown ." : void 0
|
|
1839
|
+
},
|
|
1840
|
+
"lint-staged": features.prettier ? {
|
|
1841
|
+
"*": ["prettier --write --cache --ignore-unknown"]
|
|
1842
|
+
} : void 0,
|
|
1843
|
+
browserslist: "extends @sanity/browserslist-config",
|
|
1844
|
+
prettier: features.prettier ? "@sanity/prettier-config" : void 0,
|
|
1845
|
+
dependencies: {},
|
|
1846
|
+
devDependencies: {
|
|
1847
|
+
"@sanity/pkg-utils": "^6",
|
|
1848
|
+
"@sanity/prettier-config": features.prettier ? "^1" : void 0,
|
|
1849
|
+
"@typescript-eslint/eslint-plugin": void 0,
|
|
1850
|
+
"@typescript-eslint/parser": void 0,
|
|
1851
|
+
eslint: void 0,
|
|
1852
|
+
"eslint-config-prettier": void 0,
|
|
1853
|
+
"eslint-plugin-import": void 0,
|
|
1854
|
+
"eslint-plugin-prettier": void 0,
|
|
1855
|
+
"eslint-plugin-simple-import-sort": void 0,
|
|
1856
|
+
"lint-staged": "^15",
|
|
1857
|
+
prettier: features.prettier ? "^3" : void 0,
|
|
1858
|
+
typescript: void 0
|
|
1859
|
+
},
|
|
1860
|
+
engines: {
|
|
1861
|
+
node: ">=18.0.0"
|
|
1862
|
+
}
|
|
1863
|
+
}, files = [];
|
|
1864
|
+
if (files.push({
|
|
1865
|
+
name: ".editorconfig",
|
|
1866
|
+
contents: outdent.outdent`
|
|
1867
|
+
root = true
|
|
1868
|
+
|
|
1869
|
+
[*]
|
|
1870
|
+
charset = utf-8
|
|
1871
|
+
indent_style = space
|
|
1872
|
+
indent_size = 2
|
|
1873
|
+
end_of_line = lf
|
|
1874
|
+
insert_final_newline = true
|
|
1875
|
+
trim_trailing_whitespace = true
|
|
1876
|
+
`
|
|
1877
|
+
}), files.push({
|
|
1878
|
+
name: ".gitignore",
|
|
1879
|
+
contents: outdent.outdent`
|
|
1880
|
+
*.local
|
|
1881
|
+
*.log
|
|
1882
|
+
*.tgz
|
|
1883
|
+
|
|
1884
|
+
.DS_Store
|
|
1885
|
+
dist
|
|
1886
|
+
etc
|
|
1887
|
+
node_modules
|
|
1888
|
+
`
|
|
1889
|
+
}), features.prettier && files.push({
|
|
1890
|
+
name: ".prettierignore",
|
|
1891
|
+
contents: outdent.outdent`
|
|
1892
|
+
dist
|
|
1893
|
+
pnpm-lock.yaml
|
|
1894
|
+
`
|
|
1895
|
+
}), repo && (pkgJson.repository = {
|
|
1896
|
+
type: "git",
|
|
1897
|
+
url: `git+ssh://git@${repo.source}/${repo.owner}/${repo.name}.git`
|
|
1898
|
+
}, pkgJson.bugs = {
|
|
1899
|
+
url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
|
|
1900
|
+
}, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
|
|
1901
|
+
pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
|
|
1902
|
+
...pkgJson.scripts,
|
|
1903
|
+
"ts:check": "tsc --noEmit"
|
|
1904
|
+
};
|
|
1905
|
+
const devDependencies = pkgJson.devDependencies;
|
|
1906
|
+
isRecord(devDependencies) && (devDependencies.typescript = "^5.4");
|
|
1907
|
+
}
|
|
1908
|
+
if (features.eslint) {
|
|
1909
|
+
const eslintConfig = {
|
|
1910
|
+
root: !0,
|
|
1911
|
+
env: {
|
|
1912
|
+
browser: !0,
|
|
1913
|
+
es6: !0,
|
|
1914
|
+
node: !0
|
|
1915
|
+
},
|
|
1916
|
+
extends: [
|
|
1917
|
+
"eslint:recommended",
|
|
1918
|
+
features.prettier ? "plugin:prettier/recommended" : void 0
|
|
1919
|
+
].filter(Boolean),
|
|
1920
|
+
parserOptions: {
|
|
1921
|
+
ecmaVersion: 2020,
|
|
1922
|
+
sourceType: "module"
|
|
1923
|
+
},
|
|
1924
|
+
plugins: [
|
|
1925
|
+
"import",
|
|
1926
|
+
"simple-import-sort",
|
|
1927
|
+
features.prettier ? "prettier" : void 0
|
|
1928
|
+
].filter(Boolean),
|
|
1929
|
+
rules: {
|
|
1930
|
+
"no-console": "error",
|
|
1931
|
+
"no-shadow": "error",
|
|
1932
|
+
"no-warning-comments": ["warn", { location: "start", terms: ["todo", "fixme"] }],
|
|
1933
|
+
"quote-props": ["warn", "consistent-as-needed"],
|
|
1934
|
+
"simple-import-sort/exports": "warn",
|
|
1935
|
+
"simple-import-sort/imports": "warn",
|
|
1936
|
+
strict: ["warn", "global"]
|
|
1937
|
+
}
|
|
1938
|
+
};
|
|
1939
|
+
if (files.push({
|
|
1940
|
+
name: ".eslintignore",
|
|
1941
|
+
contents: outdent.outdent`
|
|
1942
|
+
dist
|
|
1943
|
+
`
|
|
1944
|
+
}), pkgJson.scripts = {
|
|
1945
|
+
...pkgJson.scripts,
|
|
1946
|
+
lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
|
|
1947
|
+
}, pkgJson.devDependencies = {
|
|
1948
|
+
...pkgJson.devDependencies,
|
|
1949
|
+
eslint: "^8",
|
|
1950
|
+
"eslint-config-prettier": features.prettier ? "^9" : void 0,
|
|
1951
|
+
"eslint-plugin-import": "^2",
|
|
1952
|
+
"eslint-plugin-prettier": features.prettier ? "^5" : void 0,
|
|
1953
|
+
"eslint-plugin-simple-import-sort": "^12"
|
|
1954
|
+
}, features.typescript) {
|
|
1955
|
+
pkgJson.devDependencies = {
|
|
1956
|
+
...pkgJson.devDependencies,
|
|
1957
|
+
"@typescript-eslint/eslint-plugin": "^7",
|
|
1958
|
+
"@typescript-eslint/parser": "^7"
|
|
1959
|
+
};
|
|
1960
|
+
const eslintConfigOverride = {
|
|
1961
|
+
files: ["**/*.ts", "**/*.tsx"],
|
|
1962
|
+
parser: "@typescript-eslint/parser",
|
|
1963
|
+
parserOptions: {
|
|
1964
|
+
project: ["./tsconfig.json"]
|
|
1965
|
+
},
|
|
1966
|
+
extends: [
|
|
1967
|
+
"eslint:recommended",
|
|
1968
|
+
features.prettier ? "plugin:prettier/recommended" : void 0,
|
|
1969
|
+
"plugin:@typescript-eslint/eslint-recommended",
|
|
1970
|
+
"plugin:@typescript-eslint/recommended"
|
|
1971
|
+
].filter(Boolean),
|
|
1972
|
+
plugins: [
|
|
1973
|
+
"import",
|
|
1974
|
+
"@typescript-eslint",
|
|
1975
|
+
"simple-import-sort",
|
|
1976
|
+
features.prettier ? "prettier" : void 0
|
|
1977
|
+
].filter(Boolean),
|
|
1978
|
+
rules: {
|
|
1979
|
+
"@typescript-eslint/explicit-module-boundary-types": "error",
|
|
1980
|
+
"@typescript-eslint/interface-name-prefix": "off",
|
|
1981
|
+
"@typescript-eslint/member-delimiter-style": "off",
|
|
1982
|
+
"@typescript-eslint/no-empty-interface": "off"
|
|
1983
|
+
}
|
|
1984
|
+
};
|
|
1985
|
+
eslintConfig.overrides = [eslintConfigOverride];
|
|
1986
|
+
}
|
|
1987
|
+
files.push({
|
|
1988
|
+
name: ".eslintrc.cjs",
|
|
1989
|
+
contents: await prettierFormat(
|
|
1990
|
+
path.resolve(packagePath, ".eslintrc.cjs"),
|
|
1991
|
+
outdent.outdent`
|
|
1992
|
+
'use strict'
|
|
1993
|
+
|
|
1994
|
+
/** @type import('eslint').Linter.Config */
|
|
1995
|
+
module.exports = ${JSON.stringify(eslintConfig, null, 2)}
|
|
1996
|
+
`,
|
|
1997
|
+
config
|
|
1998
|
+
)
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
features.typescript && (files.push({
|
|
2002
|
+
name: "tsconfig.settings.json",
|
|
2003
|
+
contents: await prettierFormat(
|
|
2004
|
+
path.resolve(packagePath, "tsconfig.settings.json"),
|
|
2005
|
+
outdent.outdent`
|
|
2006
|
+
{
|
|
2007
|
+
"extends": "@sanity/pkg-utils/tsconfig/strictest.json",
|
|
2008
|
+
"compilerOptions": {
|
|
2009
|
+
"rootDir": ".",
|
|
2010
|
+
"outDir": "./dist"
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
`,
|
|
2014
|
+
config
|
|
2015
|
+
)
|
|
2016
|
+
}), files.push({
|
|
2017
|
+
name: "tsconfig.dist.json",
|
|
2018
|
+
contents: await prettierFormat(
|
|
2019
|
+
path.resolve(packagePath, "tsconfig.dist.json"),
|
|
2020
|
+
outdent.outdent`
|
|
2021
|
+
{
|
|
2022
|
+
"extends": "./tsconfig.settings",
|
|
2023
|
+
"include": ["./src"],
|
|
2024
|
+
"exclude": ["./src/**/*.test.ts"]
|
|
2025
|
+
}
|
|
2026
|
+
`,
|
|
2027
|
+
config
|
|
2028
|
+
)
|
|
2029
|
+
}), files.push({
|
|
2030
|
+
name: "tsconfig.json",
|
|
2031
|
+
contents: await prettierFormat(
|
|
2032
|
+
path.resolve(packagePath, "tsconfig.json"),
|
|
2033
|
+
outdent.outdent`
|
|
2034
|
+
{
|
|
2035
|
+
"extends": "./tsconfig.settings",
|
|
2036
|
+
"include": ["./**/*.cjs", "./**/*.ts", "./**/*.tsx"],
|
|
2037
|
+
"exclude": ["./node_modules"]
|
|
2038
|
+
}
|
|
2039
|
+
`,
|
|
2040
|
+
config
|
|
2041
|
+
)
|
|
2042
|
+
})), features.typescript ? (files.push({
|
|
2043
|
+
name: "package.config.ts",
|
|
2044
|
+
contents: await prettierFormat(
|
|
2045
|
+
path.resolve(packagePath, "package.config.ts"),
|
|
2046
|
+
outdent.outdent`
|
|
2047
|
+
import {defineConfig} from '@sanity/pkg-utils'
|
|
2048
|
+
|
|
2049
|
+
// https://github.com/sanity-io/pkg-utils#configuration
|
|
2050
|
+
export default defineConfig({
|
|
2051
|
+
// the path to the tsconfig file for distributed builds
|
|
2052
|
+
tsconfig: 'tsconfig.dist.json',
|
|
2053
|
+
})
|
|
2054
|
+
`,
|
|
2055
|
+
config
|
|
2056
|
+
)
|
|
2057
|
+
}), files.push({
|
|
2058
|
+
name: "src/index.ts",
|
|
2059
|
+
contents: await prettierFormat(
|
|
2060
|
+
path.resolve(packagePath, "src/index.ts"),
|
|
2061
|
+
outdent.outdent`
|
|
2062
|
+
/** @public */
|
|
2063
|
+
export function main(): void {
|
|
2064
|
+
//
|
|
2065
|
+
}
|
|
2066
|
+
`,
|
|
2067
|
+
config
|
|
2068
|
+
)
|
|
2069
|
+
})) : (files.push({
|
|
2070
|
+
name: "package.config.js",
|
|
2071
|
+
contents: await prettierFormat(
|
|
2072
|
+
path.resolve(packagePath, "package.config.js"),
|
|
2073
|
+
outdent.outdent`
|
|
2074
|
+
import {defineConfig} from '@sanity/pkg-utils'
|
|
2075
|
+
|
|
2076
|
+
export default defineConfig({
|
|
2077
|
+
extract: {
|
|
2078
|
+
rules: {
|
|
2079
|
+
// do not require internal members to be prefixed with \`_\`
|
|
2080
|
+
'ae-internal-missing-underscore': 'off',
|
|
2081
|
+
},
|
|
2082
|
+
},
|
|
2083
|
+
})
|
|
2084
|
+
`,
|
|
2085
|
+
config
|
|
2086
|
+
)
|
|
2087
|
+
}), files.push({
|
|
2088
|
+
name: "src/index.js",
|
|
2089
|
+
contents: await prettierFormat(
|
|
2090
|
+
path.resolve(packagePath, "src/index.js"),
|
|
2091
|
+
outdent.outdent`
|
|
2092
|
+
/** @public */
|
|
2093
|
+
export function main() {
|
|
2094
|
+
//
|
|
2095
|
+
}
|
|
2096
|
+
`,
|
|
2097
|
+
config
|
|
2098
|
+
)
|
|
2099
|
+
}));
|
|
2100
|
+
try {
|
|
2101
|
+
pkgJson.dependencies = await resolveLatestDeps(pkgJson.dependencies ?? {});
|
|
2102
|
+
} catch (error) {
|
|
2103
|
+
logger.warn(error instanceof Error ? error.message : error);
|
|
2104
|
+
}
|
|
2105
|
+
try {
|
|
2106
|
+
pkgJson.devDependencies = await resolveLatestDeps(pkgJson.devDependencies ?? {});
|
|
2107
|
+
} catch (error) {
|
|
2108
|
+
logger.warn(error instanceof Error ? error.message : error);
|
|
2109
|
+
}
|
|
2110
|
+
return files.push({
|
|
2111
|
+
name: "package.json",
|
|
2112
|
+
contents: await prettierFormat(
|
|
2113
|
+
path.resolve(packagePath, "package.json"),
|
|
2114
|
+
JSON.stringify(pkgJson, null, 2),
|
|
2115
|
+
config
|
|
2116
|
+
)
|
|
2117
|
+
}), files;
|
|
2118
|
+
}
|
|
2119
|
+
};
|
|
2120
|
+
};
|
|
2121
|
+
function prettierFormat(filepath, input, prettierOptions) {
|
|
2122
|
+
return prettier.format(input, { ...prettierOptions, plugins: [], filepath });
|
|
2123
|
+
}
|
|
2124
|
+
async function resolveLatestDeps(deps) {
|
|
2125
|
+
const depsEntries = Object.entries(deps), latestDeps = {};
|
|
2126
|
+
for (const entry of depsEntries) {
|
|
2127
|
+
const [name, version] = entry;
|
|
2128
|
+
if (version) {
|
|
2129
|
+
const latestVersion = await getLatestVersion__default.default(name, version);
|
|
2130
|
+
latestDeps[name] = latestVersion ? `^${latestVersion}` : version;
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
return latestDeps;
|
|
2134
|
+
}
|
|
2135
|
+
function getGitUserConfig(cwd) {
|
|
2136
|
+
let user, email;
|
|
2137
|
+
try {
|
|
2138
|
+
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;
|
|
2139
|
+
} catch {
|
|
2140
|
+
}
|
|
2141
|
+
return { user, email };
|
|
2142
|
+
}
|
|
2143
|
+
async function init(options) {
|
|
2144
|
+
if (!options.cwd)
|
|
2145
|
+
throw new Error("Missing required option: cwd");
|
|
2146
|
+
if (!options.path)
|
|
2147
|
+
throw new Error("Missing required option: path");
|
|
2148
|
+
const logger = createLogger(), packagePath = path.resolve(options.cwd, options.path);
|
|
2149
|
+
await ensurePackagePath(packagePath), await createFromTemplate({
|
|
2150
|
+
cwd: options.cwd,
|
|
2151
|
+
logger,
|
|
2152
|
+
template: defaultTemplate,
|
|
2153
|
+
packagePath
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
async function ensurePackagePath(packagePath) {
|
|
2157
|
+
if (!fileExists(packagePath)) {
|
|
2158
|
+
await mkdirp.mkdirp(packagePath);
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
if (!(await fs.lstat(packagePath)).isDirectory())
|
|
2162
|
+
throw new Error("the package path is a file, not a directory");
|
|
2163
|
+
if (!await isEmptyDirectory(packagePath))
|
|
2164
|
+
throw new Error("the package directory is not empty");
|
|
2165
|
+
}
|
|
2166
|
+
function resolveWatchTasks(ctx) {
|
|
2167
|
+
const { pkg, target } = ctx, tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
|
|
2168
|
+
([_path, exp]) => ({ _path, ...exp })
|
|
2169
|
+
), dtsTask2 = {
|
|
2170
|
+
type: "watch:dts",
|
|
2171
|
+
entries: []
|
|
2172
|
+
}, rollupTasks = {};
|
|
2173
|
+
function addRollupTaskEntry(format, runtime, entry) {
|
|
2174
|
+
const buildId = `${format}:${runtime}`;
|
|
2175
|
+
rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
2176
|
+
type: "watch:js",
|
|
2177
|
+
buildId,
|
|
2178
|
+
entries: [entry],
|
|
2179
|
+
runtime,
|
|
2180
|
+
format,
|
|
2181
|
+
target: target[runtime]
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
for (const exp of exports2) {
|
|
2185
|
+
const importId = path__default.default.join(pkg.name, exp._path);
|
|
2186
|
+
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2187
|
+
importId,
|
|
2188
|
+
exportPath: exp._path,
|
|
2189
|
+
sourcePath: exp.source,
|
|
2190
|
+
targetPaths: getTargetPaths(pkg.type, exp)
|
|
2191
|
+
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2192
|
+
importId,
|
|
2193
|
+
exportPath: exp._path,
|
|
2194
|
+
sourcePath: exp.browser.source,
|
|
2195
|
+
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
2196
|
+
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2197
|
+
importId,
|
|
2198
|
+
exportPath: exp._path,
|
|
2199
|
+
sourcePath: exp.node.source,
|
|
2200
|
+
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
for (const exp of exports2) {
|
|
2204
|
+
const output = exp.require;
|
|
2205
|
+
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
2206
|
+
path: exp._path,
|
|
2207
|
+
source: exp.source,
|
|
2208
|
+
output
|
|
2209
|
+
});
|
|
2210
|
+
}
|
|
2211
|
+
for (const exp of exports2) {
|
|
2212
|
+
const output = exp.browser?.require;
|
|
2213
|
+
output && addRollupTaskEntry("commonjs", "browser", {
|
|
2214
|
+
path: exp._path,
|
|
2215
|
+
source: exp.browser?.source || exp.source,
|
|
2216
|
+
output
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
for (const exp of exports2) {
|
|
2220
|
+
const output = exp.import;
|
|
2221
|
+
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
2222
|
+
path: exp._path,
|
|
2223
|
+
source: exp.source,
|
|
2224
|
+
output
|
|
2225
|
+
});
|
|
2226
|
+
}
|
|
2227
|
+
for (const exp of exports2) {
|
|
2228
|
+
const output = exp.browser?.import;
|
|
2229
|
+
output && addRollupTaskEntry("esm", "browser", {
|
|
2230
|
+
path: exp._path,
|
|
2231
|
+
source: exp.browser?.source || exp.source,
|
|
2232
|
+
output
|
|
2233
|
+
});
|
|
2234
|
+
}
|
|
2235
|
+
return dtsTask2.entries.length && tasks.push(dtsTask2), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
2236
|
+
}
|
|
2237
|
+
function globFiles(patterns) {
|
|
2238
|
+
return globby__default.default(patterns.map((pattern) => pattern.split(path__default.default.sep).join(path__default.default.posix.sep)));
|
|
2239
|
+
}
|
|
2240
|
+
function watchFiles(patterns) {
|
|
2241
|
+
return new rxjs.Observable((observer) => {
|
|
2242
|
+
const watcher = chokidar__namespace.watch(patterns, {
|
|
2243
|
+
ignoreInitial: !0
|
|
2244
|
+
});
|
|
2245
|
+
function handleFileEvent(type, file) {
|
|
2246
|
+
type === "error" || file instanceof Error ? observer.error(file) : observer.next({ type, file });
|
|
2247
|
+
}
|
|
2248
|
+
return watcher.on("all", handleFileEvent), () => {
|
|
2249
|
+
watcher.off("all", handleFileEvent), watcher.close();
|
|
2250
|
+
};
|
|
2251
|
+
});
|
|
2252
|
+
}
|
|
2253
|
+
async function watchConfigFiles(options) {
|
|
2254
|
+
const { cwd, logger } = options, initialFiles = await globFiles([
|
|
2255
|
+
path__default.default.resolve(cwd, "package.json"),
|
|
2256
|
+
path__default.default.resolve(cwd, "package.config.cjs"),
|
|
2257
|
+
path__default.default.resolve(cwd, "package.config.js"),
|
|
2258
|
+
path__default.default.resolve(cwd, "package.config.ts")
|
|
2259
|
+
]);
|
|
2260
|
+
return watchFiles([
|
|
2261
|
+
path__default.default.resolve(cwd, "package.json"),
|
|
2262
|
+
path__default.default.resolve(cwd, "package.config.cjs"),
|
|
2263
|
+
path__default.default.resolve(cwd, "package.config.js"),
|
|
2264
|
+
path__default.default.resolve(cwd, "package.config.ts")
|
|
2265
|
+
]).pipe(
|
|
2266
|
+
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(
|
|
2267
|
+
"--------------------------------------------------------------------------------"
|
|
2268
|
+
), logger.info(path__default.default.relative(cwd, fileEvent.file), "changed"), logger.log(""), files.slice(0)) : files, initialFiles),
|
|
2269
|
+
operators.startWith(initialFiles),
|
|
2270
|
+
operators.distinctUntilChanged()
|
|
2271
|
+
);
|
|
2272
|
+
}
|
|
2273
|
+
async function watch(options) {
|
|
2274
|
+
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
|
|
2275
|
+
(await watchConfigFiles({ cwd, logger })).pipe(
|
|
2276
|
+
rxjs.switchMap(async (configFiles) => {
|
|
2277
|
+
if (!configFiles.map((f) => path__default.default.relative(cwd, f)).find((f) => f === "package.json"))
|
|
2278
|
+
throw new Error("missing package.json");
|
|
2279
|
+
const config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json";
|
|
2280
|
+
return resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
|
|
2281
|
+
})
|
|
2282
|
+
).subscribe(async (ctx) => {
|
|
2283
|
+
const watchTasks = resolveWatchTasks(ctx);
|
|
2284
|
+
for (const task of watchTasks) {
|
|
2285
|
+
const handler = watchTaskHandlers[task.type];
|
|
2286
|
+
handler.exec(ctx, task).subscribe({
|
|
2287
|
+
error: (err) => {
|
|
2288
|
+
ctx.logger.error(err), ctx.logger.log(), process.exit(1);
|
|
2289
|
+
},
|
|
2290
|
+
next: (result) => {
|
|
2291
|
+
handler.complete(ctx, task, result);
|
|
2292
|
+
},
|
|
2293
|
+
complete: () => {
|
|
2294
|
+
ctx.logger.success(handler.name(ctx, task)), ctx.logger.log();
|
|
2295
|
+
}
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
});
|
|
2299
|
+
}
|
|
2300
|
+
exports.DEFAULT_BROWSERSLIST_QUERY = DEFAULT_BROWSERSLIST_QUERY;
|
|
2301
|
+
exports.build = build;
|
|
2302
|
+
exports.check = check;
|
|
2303
|
+
exports.createLogger = createLogger;
|
|
2304
|
+
exports.defineConfig = defineConfig;
|
|
2305
|
+
exports.defineTemplateOption = defineTemplateOption;
|
|
850
2306
|
exports.getExtractMessagesConfig = getExtractMessagesConfig;
|
|
851
|
-
exports.
|
|
2307
|
+
exports.init = init;
|
|
2308
|
+
exports.loadConfig = loadConfig;
|
|
2309
|
+
exports.loadPkg = loadPkg;
|
|
2310
|
+
exports.loadPkgWithReporting = loadPkgWithReporting;
|
|
2311
|
+
exports.parseExports = parseExports;
|
|
2312
|
+
exports.parseStrictOptions = parseStrictOptions;
|
|
2313
|
+
exports.pkgExtMap = pkgExtMap;
|
|
2314
|
+
exports.strictOptions = strictOptions;
|
|
2315
|
+
exports.toggle = toggle;
|
|
2316
|
+
exports.watch = watch;
|
|
852
2317
|
//# sourceMappingURL=index.cjs.map
|