@sanity/plugin-kit 4.0.20 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/assets/inject/semver-workflow/.github/workflows/main.yml +3 -3
  2. package/assets/inject/semver-workflow/.husky/commit-msg +0 -0
  3. package/assets/inject/semver-workflow/.husky/pre-commit +0 -0
  4. package/assets/inject/ui-workshop/src/__workshop__/props.tsx +2 -1
  5. package/bin/plugin-kit.js +3 -1
  6. package/dist/{_chunks-cjs/cli.js → _chunks-es/index.js} +53 -63
  7. package/dist/_chunks-es/index.js.map +1 -0
  8. package/dist/{_chunks-cjs/init2.js → _chunks-es/init.js} +25 -23
  9. package/dist/_chunks-es/init.js.map +1 -0
  10. package/dist/_chunks-es/init2.js +140 -0
  11. package/dist/_chunks-es/init2.js.map +1 -0
  12. package/{src/cmds/inject.ts → dist/_chunks-es/inject.js} +18 -32
  13. package/dist/{_chunks-cjs → _chunks-es}/inject.js.map +1 -1
  14. package/dist/_chunks-es/link-watch.js +91 -0
  15. package/dist/_chunks-es/link-watch.js.map +1 -0
  16. package/dist/_chunks-es/load-package-config.js +22 -0
  17. package/dist/_chunks-es/load-package-config.js.map +1 -0
  18. package/dist/_chunks-es/package.js +1759 -0
  19. package/dist/_chunks-es/package.js.map +1 -0
  20. package/dist/_chunks-es/package2.js +9 -0
  21. package/dist/{_chunks-cjs → _chunks-es}/package2.js.map +1 -1
  22. package/dist/_chunks-es/ts.js +171 -0
  23. package/dist/_chunks-es/ts.js.map +1 -0
  24. package/dist/_chunks-es/verify-package.js +92 -0
  25. package/dist/_chunks-es/verify-package.js.map +1 -0
  26. package/dist/_chunks-es/verify-studio.js +61 -0
  27. package/dist/_chunks-es/verify-studio.js.map +1 -0
  28. package/dist/_chunks-es/version.js +50 -0
  29. package/dist/_chunks-es/version.js.map +1 -0
  30. package/dist/index.d.ts +4 -1
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +4 -1
  33. package/dist/index.js.map +1 -1
  34. package/package.json +58 -116
  35. package/LICENSE +0 -21
  36. package/dist/_chunks-cjs/cli.js.map +0 -1
  37. package/dist/_chunks-cjs/init.js +0 -892
  38. package/dist/_chunks-cjs/init.js.map +0 -1
  39. package/dist/_chunks-cjs/init2.js.map +0 -1
  40. package/dist/_chunks-cjs/inject.js +0 -54
  41. package/dist/_chunks-cjs/link-watch.js +0 -84
  42. package/dist/_chunks-cjs/link-watch.js.map +0 -1
  43. package/dist/_chunks-cjs/package.js +0 -1809
  44. package/dist/_chunks-cjs/package.js.map +0 -1
  45. package/dist/_chunks-cjs/package2.js +0 -8
  46. package/dist/_chunks-cjs/ts.js +0 -160732
  47. package/dist/_chunks-cjs/ts.js.map +0 -1
  48. package/dist/_chunks-cjs/verify-package.js +0 -75
  49. package/dist/_chunks-cjs/verify-package.js.map +0 -1
  50. package/dist/_chunks-cjs/verify-studio.js +0 -57
  51. package/dist/_chunks-cjs/verify-studio.js.map +0 -1
  52. package/dist/_chunks-cjs/version.js +0 -51
  53. package/dist/_chunks-cjs/version.js.map +0 -1
  54. package/dist/cli.d.ts +0 -4
  55. package/dist/cli.js +0 -6
  56. package/dist/cli.js.map +0 -1
  57. package/src/actions/init.ts +0 -95
  58. package/src/actions/inject.ts +0 -399
  59. package/src/actions/link-watch.ts +0 -98
  60. package/src/actions/verify/types.ts +0 -56
  61. package/src/actions/verify/validations.ts +0 -505
  62. package/src/actions/verify/verify-common.ts +0 -93
  63. package/src/actions/verify-package.ts +0 -103
  64. package/src/actions/verify-studio.ts +0 -58
  65. package/src/cli.ts +0 -77
  66. package/src/cmds/index.ts +0 -20
  67. package/src/cmds/init.ts +0 -90
  68. package/src/cmds/link-watch.ts +0 -50
  69. package/src/cmds/verify-package.ts +0 -36
  70. package/src/cmds/verify-studio.ts +0 -36
  71. package/src/cmds/version.ts +0 -67
  72. package/src/configs/banned-packages.ts +0 -27
  73. package/src/configs/buildExtensions.ts +0 -1
  74. package/src/configs/default-source.ts +0 -64
  75. package/src/configs/eslint.ts +0 -51
  76. package/src/configs/forced-package-versions.ts +0 -12
  77. package/src/configs/git.ts +0 -68
  78. package/src/configs/pkg-config.ts +0 -30
  79. package/src/configs/prettier.ts +0 -11
  80. package/src/configs/tsconfig.ts +0 -78
  81. package/src/configs/uselessFiles.ts +0 -29
  82. package/src/constants.ts +0 -15
  83. package/src/dependencies/find.ts +0 -193
  84. package/src/dependencies/import-linter.ts +0 -95
  85. package/src/index.ts +0 -1
  86. package/src/npm/manager.ts +0 -44
  87. package/src/npm/package.ts +0 -427
  88. package/src/npm/publish.ts +0 -9
  89. package/src/npm/resolveLatestVersions.ts +0 -31
  90. package/src/presets/presets.ts +0 -54
  91. package/src/presets/renovatebot.ts +0 -21
  92. package/src/presets/semver-workflow.ts +0 -186
  93. package/src/presets/ui-workshop.ts +0 -97
  94. package/src/presets/ui.ts +0 -67
  95. package/src/sanity/manifest.ts +0 -340
  96. package/src/sharedFlags.ts +0 -14
  97. package/src/util/command-parser.ts +0 -36
  98. package/src/util/errorToUndefined.ts +0 -7
  99. package/src/util/files.ts +0 -260
  100. package/src/util/log.ts +0 -44
  101. package/src/util/prompt.ts +0 -70
  102. package/src/util/readme.ts +0 -88
  103. package/src/util/request.ts +0 -11
  104. package/src/util/ts.ts +0 -19
  105. package/src/util/user.ts +0 -129
@@ -1,892 +0,0 @@
1
- "use strict";
2
- var path = require("path"), licenses = require("@rexxars/choosealicense-list"), gitRemoteOriginUrl = require("git-remote-origin-url"), cli = require("./cli.js"), childProcess = require("child_process"), xdgBasedir = require("xdg-basedir"), emailValidator = require("email-validator"), _package$1 = require("./package.js"), getIt = require("get-it"), middleware = require("get-it/middleware"), _package = require("./package2.js"), outdent = require("outdent"), chalk = require("chalk");
3
- function _interopDefaultCompat(e) {
4
- return e && typeof e == "object" && "default" in e ? e : { default: e };
5
- }
6
- var path__default = /* @__PURE__ */ _interopDefaultCompat(path), licenses__default = /* @__PURE__ */ _interopDefaultCompat(licenses), gitRemoteOriginUrl__default = /* @__PURE__ */ _interopDefaultCompat(gitRemoteOriginUrl), xdgBasedir__default = /* @__PURE__ */ _interopDefaultCompat(xdgBasedir), outdent__default = /* @__PURE__ */ _interopDefaultCompat(outdent), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
7
- const request = getIt.getIt([
8
- middleware.promise({ onlyBody: !0 }),
9
- middleware.jsonRequest(),
10
- middleware.jsonResponse(),
11
- middleware.httpErrors(),
12
- middleware.headers({ "User-Agent": `${_package.pkg.name}@${_package.pkg.version}` })
13
- ]);
14
- async function getUserInfo({ requireUserConfirmation, flags }, pkg) {
15
- const userInfo = getPackageUserInfo({ author: flags.author ?? pkg?.author }) || await getSanityUserInfo() || await getGitUserInfo();
16
- return requireUserConfirmation ? promptForInfo(userInfo) : userInfo;
17
- }
18
- function getPackageUserInfo(pkg) {
19
- let author = pkg?.author;
20
- if (!author)
21
- return;
22
- if (author && typeof author != "string")
23
- return author;
24
- if (!author.includes("@"))
25
- return { name: author };
26
- const [pre, ...post] = author.replace(/[<>[\]]/g, "").split(/@/), nameParts = pre.split(/\s+/), email = [nameParts[nameParts.length - 1], ...post].join("@");
27
- return { name: nameParts.slice(0, -1).join(" "), email };
28
- }
29
- async function promptForInfo(defValue) {
30
- const name = await _package$1.prompt("Author name", {
31
- filter: filterString,
32
- default: defValue && defValue.name,
33
- validate: requiredString
34
- }), email = await _package$1.prompt("Author email", {
35
- filter: filterString,
36
- default: defValue && defValue.email,
37
- validate: validOrEmptyEmail
38
- });
39
- return { name, email };
40
- }
41
- async function getSanityUserInfo() {
42
- try {
43
- const token = (await _package$1.readJsonFile(
44
- path__default.default.join(xdgBasedir__default.default.config ?? "", "sanity", "config.json")
45
- ))?.authToken;
46
- if (!token)
47
- return;
48
- const user = await request({
49
- url: "https://api.sanity.io/v1/users/me",
50
- headers: { Authorization: `Bearer ${token}` }
51
- });
52
- if (!user)
53
- return;
54
- const { name, email } = user;
55
- return { name, email };
56
- } catch {
57
- return;
58
- }
59
- }
60
- async function getGitUserInfo() {
61
- try {
62
- const name = childProcess.execSync("git config user.name", { encoding: "utf8" }).trim(), email = childProcess.execSync("git config user.email", { encoding: "utf8" }).trim();
63
- return name ? { name, email: email || void 0 } : void 0;
64
- } catch {
65
- return;
66
- }
67
- }
68
- function filterString(val) {
69
- return (val || "").trim();
70
- }
71
- function requiredString(value) {
72
- return value.length > 1 ? !0 : "Required";
73
- }
74
- function validOrEmptyEmail(value) {
75
- return value ? emailValidator.validate(value) ? !0 : "Must either be a valid email or empty" : !0;
76
- }
77
- function generateReadme(data) {
78
- const { user, pluginName, license } = data;
79
- return outdent__default.default`
80
- # ${pluginName}
81
-
82
-
83
- ${installationSnippet(pluginName ?? "unknown")}
84
-
85
- ## Usage
86
-
87
- Add it as a plugin in \`sanity.config.ts\` (or .js):
88
-
89
- \`\`\`ts
90
- import {defineConfig} from 'sanity'
91
- import {myPlugin} from '${pluginName}'
92
-
93
- export default defineConfig({
94
- //...
95
- plugins: [myPlugin({})],
96
- })
97
- \`\`\`
98
-
99
- ${getLicenseText(license?.id, user?.name ? user : void 0)}
100
- ${developTestSnippet()}
101
- ` + `
102
- `;
103
- }
104
- function installationSnippet(packageName) {
105
- return outdent__default.default`
106
- ## Installation
107
-
108
- \`\`\`sh
109
- npm install ${packageName}
110
- \`\`\`
111
- `;
112
- }
113
- function developTestSnippet() {
114
- return outdent__default.default`
115
- ## Develop & test
116
-
117
- This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
118
- with default configuration for build & watch scripts.
119
-
120
- See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
121
- on how to run this plugin with hotreload in the studio.
122
- `;
123
- }
124
- function getLicenseText(licenseId, user) {
125
- if (!licenseId)
126
- return "";
127
- let licenseName = licenses__default.default.find(licenseId).title;
128
- licenseName = licenseName?.replace(/\s+license$/i, "");
129
- let licenseText = `## License
130
- `;
131
- return licenseName && user?.name ? licenseText = `${licenseText}
132
- [${licenseName}](LICENSE) \xA9 ${user?.name}
133
- ` : licenseName ? licenseText = `${licenseText}
134
- [${licenseName}](LICENSE)
135
- ` : licenseText = `${licenseText}
136
- See [LICENSE](LICENSE)`, licenseText;
137
- }
138
- function isDefaultGitHubReadme(readme) {
139
- if (!readme)
140
- return !1;
141
- const lines = readme.split(`
142
- `, 20).filter(Boolean);
143
- return lines.length <= 2 && lines[0].startsWith("#");
144
- }
145
- const semverWorkflowPreset = {
146
- name: "semver-workflow",
147
- description: "Files and dependencies for conventional-commits, github workflow and semantic-release.",
148
- apply: applyPreset$3
149
- }, info = (write, msg, ...args) => write && cli.log.info(msg, ...args);
150
- async function applyPreset$3(options) {
151
- await writeAssets(semverWorkflowFiles(), options), await addPrepareScript(options), await addDevDependencies$2(options), await updateReadme(options);
152
- }
153
- async function addPrepareScript(options) {
154
- const pkg = await _package$1.getPackage(options), didWrite = await _package$1.addPackageJsonScripts(pkg, options, (scripts) => (scripts.prepare = _package$1.addScript("husky", scripts.prepare), scripts));
155
- info(didWrite, "Added prepare script to package.json");
156
- }
157
- async function addDevDependencies$2(options) {
158
- const pkg = await _package$1.getPackage(options), devDeps = _package$1.sortKeys({
159
- ...pkg.devDependencies,
160
- ...await semverWorkflowDependencies()
161
- }), newPkg = { ...pkg };
162
- newPkg.devDependencies = devDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies."), cli.log.info(
163
- chalk__default.default.green(
164
- outdent__default.default`
165
- semantic-release preset injected.
166
-
167
- Please confer
168
- https://github.com/sanity-io/plugin-kit/blob/main/docs/semver-workflow.md#manual-steps-after-inject
169
- to finalize configuration for this preset.
170
- `.trim()
171
- )
172
- );
173
- }
174
- async function updateReadme(options) {
175
- const { basePath } = options, readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8").catch(_package$1.errorToUndefined) ?? "", { install, usage, developTest, license, releaseSnippet } = await readmeSnippets(options), prependSections = missingSections(readme, [install, usage]), appendSections = missingSections(readme, [license, developTest, releaseSnippet]);
176
- if (prependSections.length || appendSections.length) {
177
- const updatedReadme = [...prependSections, readme, ...appendSections].filter(Boolean).join(`
178
-
179
- `);
180
- await _package$1.writeFile(readmePath, updatedReadme, { encoding: "utf8" }), cli.log.info("Updated README. Please review the changes.");
181
- }
182
- }
183
- async function readmeSnippets(options) {
184
- const pkg = await _package$1.getPackage(options), user = await getUserInfo(options, pkg), bestEffortUrl = readmeBaseurl(pkg), install = installationSnippet(pkg.name ?? "unknown"), usage = outdent__default.default`
185
- ## Usage
186
- `, license = getLicenseText(typeof pkg.license == "string" ? pkg.license : void 0, user), releaseSnippet = outdent__default.default`
187
- ### Release new version
188
-
189
- Run ["CI & Release" workflow](${bestEffortUrl}/actions/workflows/main.yml).
190
- Make sure to select the main branch and check "Release new version".
191
-
192
- Semantic release will only release on configured branches, so it is safe to run release on any branch.
193
- `;
194
- return {
195
- install,
196
- usage,
197
- license,
198
- developTest: developTestSnippet(),
199
- releaseSnippet
200
- };
201
- }
202
- function missingSections(readme, sections) {
203
- return sections.filter((section) => !closeEnough(section, readme));
204
- }
205
- function closeEnough(a, b) {
206
- const aLines = a.split(`
207
- `), bLines = b.split(`
208
- `);
209
- return aLines.filter((line) => bLines.find((bLine) => bLine === line)).length >= aLines.length * 0.5;
210
- }
211
- function semverWorkflowFiles() {
212
- return [
213
- {
214
- type: "copy",
215
- from: [".github", "workflows", "main.yml"],
216
- to: [".github", "workflows", "main.yml"]
217
- },
218
- { type: "copy", from: [".husky", "commit-msg"], to: [".husky", "commit-msg"] },
219
- { type: "copy", from: [".husky", "pre-commit"], to: [".husky", "pre-commit"] },
220
- { type: "copy", from: [".releaserc.json"], to: ".releaserc.json" },
221
- { type: "copy", from: ["commitlint.template.js"], to: "commitlint.config.js" },
222
- { type: "copy", from: ["lint-staged.template.js"], to: "lint-staged.config.js" }
223
- ].map((fromTo) => fromTo.type === "copy" ? {
224
- ...fromTo,
225
- from: ["semver-workflow", ...fromTo.from]
226
- } : fromTo);
227
- }
228
- async function semverWorkflowDependencies() {
229
- return _package$1.resolveLatestVersions([
230
- "@commitlint/cli",
231
- "@commitlint/config-conventional",
232
- "@sanity/semantic-release-preset",
233
- "husky",
234
- "lint-staged"
235
- ]);
236
- }
237
- function readmeBaseurl(pkg) {
238
- return (pkg.repository?.url ?? pkg.homepage ?? "TODO").replace(/.+:\/\//g, "https://").replace(/\.git/g, "").replace(/git@github.com\//g, "github.com/").replace(/git@github.com:/g, "https://github.com/").replace(/#.+/g, "");
239
- }
240
- const renovatePreset = {
241
- name: "renovatebot",
242
- description: "Files to enable renovatebot.",
243
- apply: applyPreset$2
244
- };
245
- async function applyPreset$2(options) {
246
- await writeAssets(
247
- [
248
- {
249
- type: "copy",
250
- from: ["renovatebot", "renovate.json"],
251
- to: "renovate.json"
252
- }
253
- ],
254
- options
255
- );
256
- }
257
- const ui = {
258
- name: "ui",
259
- description: "`@sanity/ui` and dependencies",
260
- apply: applyPreset$1
261
- };
262
- async function applyPreset$1(options) {
263
- await addDependencies(options), await addDevDependencies$1(options), cli.log.info(chalk__default.default.green("ui preset injected"));
264
- }
265
- async function addDependencies(options) {
266
- const pkg = await _package$1.getPackage(options), newDeps = _package$1.sortKeys(
267
- _package$1.forceDependencyVersions(
268
- {
269
- ...pkg.dependencies,
270
- ...await resolveDependencyList()
271
- },
272
- _package$1.forcedPackageVersions
273
- )
274
- ), newPkg = { ...pkg };
275
- newPkg.dependencies = newDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated dependencies.");
276
- }
277
- async function addDevDependencies$1(options) {
278
- const pkg = await _package$1.getPackage(options), newDeps = _package$1.sortKeys(
279
- _package$1.forceDependencyVersions(
280
- {
281
- ...pkg.devDependencies,
282
- ...await resolveDevDependencyList()
283
- },
284
- _package$1.forcedDevPackageVersions
285
- )
286
- ), newPkg = { ...pkg };
287
- newPkg.devDependencies = newDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies.");
288
- }
289
- async function resolveDependencyList() {
290
- return _package$1.resolveLatestVersions(["@sanity/icons", "@sanity/ui"]);
291
- }
292
- async function resolveDevDependencyList() {
293
- return _package$1.resolveLatestVersions([
294
- // install the peer dependencies of `@sanity/ui` as dev dependencies
295
- "react",
296
- "react-dom",
297
- "styled-components"
298
- ]);
299
- }
300
- const uiWorkshop = {
301
- name: "ui-workshop",
302
- description: "Files for testing custom components with @sanity/ui-workshop",
303
- apply: applyPreset
304
- };
305
- async function applyPreset(options) {
306
- await writeAssets(files(), options), await addDevDependencies(options), await updateGitIgnore(options), cli.log.info(
307
- chalk__default.default.green(
308
- outdent__default.default`
309
- ui-workshop preset injected.
310
-
311
- Please confer
312
- https://github.com/sanity-io/plugin-kit/blob/main/docs/ui-workshop.md#manual-steps-after-inject
313
- to finalize configuration for this preset.
314
- `.trim()
315
- )
316
- );
317
- }
318
- function files() {
319
- return [
320
- { type: "copy", from: ["workshop.config.ts"], to: ["workshop.config.ts"] },
321
- { type: "copy", from: ["src", "CustomField.tsx"], to: ["src", "CustomField.tsx"] },
322
- {
323
- type: "copy",
324
- from: ["src", "__workshop__", "index.tsx"],
325
- to: ["src", "__workshop__", "index.tsx"]
326
- },
327
- {
328
- type: "copy",
329
- from: ["src", "__workshop__", "props.tsx"],
330
- to: ["src", "__workshop__", "props.tsx"]
331
- }
332
- ].map((fromTo) => fromTo.type === "copy" ? {
333
- ...fromTo,
334
- from: ["ui-workshop", ...fromTo.from]
335
- } : fromTo);
336
- }
337
- async function updateGitIgnore(options) {
338
- const { basePath } = options, gitignorePath = path__default.default.join(basePath, ".gitignore");
339
- let gitignore = await _package$1.readFile(gitignorePath, "utf8").catch(_package$1.errorToUndefined) ?? "";
340
- const value = ".workshop";
341
- gitignore.includes(value) || (gitignore += `
342
-
343
- ${value}`, await _package$1.writeFile(gitignorePath, gitignore, { encoding: "utf8" }));
344
- }
345
- async function addDevDependencies(options) {
346
- const pkg = await _package$1.getPackage(options), devDeps = _package$1.sortKeys({
347
- ...pkg.devDependencies,
348
- ...await devDependencies()
349
- }), newPkg = { ...pkg };
350
- newPkg.devDependencies = devDeps, await _package$1.writePackageJsonDirect(newPkg, options), cli.log.info("Updated devDependencies.");
351
- }
352
- async function devDependencies() {
353
- return _package$1.resolveLatestVersions([
354
- "@sanity/ui-workshop",
355
- "@sanity/icons",
356
- "@sanity/ui",
357
- "react",
358
- "react-dom",
359
- "styled-components"
360
- ]);
361
- }
362
- const presets = [semverWorkflowPreset, renovatePreset, ui, uiWorkshop], presetNames = presets.map((p) => p?.name);
363
- function presetHelpList(padStart) {
364
- return presets.map((p) => `${"".padStart(padStart)}${p.name.padEnd(20)}${p.description}`).join(`
365
- `);
366
- }
367
- async function injectPresets(options) {
368
- if (options.flags.presetOnly && !options.flags.preset?.length)
369
- throw new Error("--preset-only, but no --preset [preset-name] was provided.");
370
- const applyPresets = presetsFromInput(options.flags.preset);
371
- for (const preset of applyPresets)
372
- await preset.apply(options);
373
- }
374
- function presetsFromInput(inputPresets) {
375
- if (!inputPresets)
376
- return [];
377
- const unknownPresets = inputPresets.filter((p) => !presetNames.includes(p));
378
- if (unknownPresets.length)
379
- throw new Error(
380
- `Unknown --preset(s): [${unknownPresets.join(", ")}]. Must be one of: [${presetNames.join(
381
- ", "
382
- )}]`
383
- );
384
- return inputPresets.filter(onlyUnique).map((presetName) => presets.find((p) => p.name === presetName)).filter((p) => !!p);
385
- }
386
- function onlyUnique(value, index, arr) {
387
- return arr.indexOf(value) === index;
388
- }
389
- function tsconfigTemplate(options) {
390
- const { flags } = options;
391
- return {
392
- type: "template",
393
- force: flags.force,
394
- to: "tsconfig.json",
395
- value: outdent.outdent`
396
- {
397
- "extends": "./tsconfig.settings",
398
- "include": ["./src", "./package.config.ts"]
399
- }
400
- `
401
- };
402
- }
403
- function tsconfigTemplateDist(options) {
404
- const { flags, outDir } = options;
405
- return {
406
- type: "template",
407
- force: flags.force,
408
- to: `tsconfig.${outDir}.json`,
409
- value: outdent.outdent`
410
- {
411
- "extends": "./tsconfig.settings",
412
- "include": ["./src"],
413
- "exclude": [
414
- "./src/**/__fixtures__",
415
- "./src/**/__mocks__",
416
- "./src/**/*.test.ts",
417
- "./src/**/*.test.tsx"
418
- ]
419
- }
420
- `
421
- };
422
- }
423
- function tsconfigTemplateSettings(options) {
424
- const { flags, outDir } = options;
425
- return {
426
- type: "template",
427
- force: flags.force,
428
- to: "tsconfig.settings.json",
429
- value: outdent.outdent`
430
- {
431
- "compilerOptions": {
432
- "rootDir": ".",
433
- "outDir": "./${outDir}",
434
-
435
- "target": "esnext",
436
- "jsx": "preserve",
437
- "module": "preserve",
438
- "moduleResolution": "bundler",
439
- "esModuleInterop": true,
440
- "resolveJsonModule": true,
441
- "moduleDetection": "force",
442
- "strict": true,
443
- "allowSyntheticDefaultImports": true,
444
- "skipLibCheck": true,
445
- "forceConsistentCasingInFileNames": true,
446
- "isolatedModules": true,
447
-
448
- // Don't emit by default, pkg-utils will ignore this when generating .d.ts files
449
- "noEmit": true
450
- }
451
- }
452
- `
453
- };
454
- }
455
- function pkgConfigTemplate(options) {
456
- const { flags, outDir } = options;
457
- return {
458
- type: "template",
459
- force: flags.force,
460
- to: flags.typescript ? "package.config.ts" : "package.config.js",
461
- value: outdent.outdent`
462
- import {defineConfig} from '@sanity/pkg-utils'
463
-
464
- export default defineConfig({
465
- dist: '${outDir}',
466
- tsconfig: 'tsconfig.${outDir}.json',
467
-
468
- // Remove this block to enable strict export validation
469
- extract: {
470
- rules: {
471
- 'ae-incompatible-release-tags': 'off',
472
- 'ae-internal-missing-underscore': 'off',
473
- 'ae-missing-release-tag': 'off',
474
- },
475
- },
476
- })
477
- `
478
- };
479
- }
480
- function gitignoreTemplate() {
481
- return {
482
- type: "template",
483
- to: ".gitignore",
484
- value: outdent.outdent`
485
- # Logs
486
- logs
487
- *.log
488
- npm-debug.log*
489
-
490
- # Runtime data
491
- pids
492
- *.pid
493
- *.seed
494
-
495
- # Directory for instrumented libs generated by jscoverage/JSCover
496
- lib-cov
497
-
498
- # Coverage directory used by tools like istanbul
499
- coverage
500
-
501
- # nyc test coverage
502
- .nyc_output
503
-
504
- # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
505
- .grunt
506
-
507
- # node-waf configuration
508
- .lock-wscript
509
-
510
- # Compiled binary addons (http://nodejs.org/api/addons.html)
511
- build/Release
512
-
513
- # Dependency directories
514
- node_modules
515
- jspm_packages
516
-
517
- # Optional npm cache directory
518
- .npm
519
-
520
- # Optional REPL history
521
- .node_repl_history
522
-
523
- # macOS finder cache file
524
- .DS_Store
525
-
526
- # VS Code settings
527
- .vscode
528
-
529
- # IntelliJ
530
- .idea
531
- *.iml
532
-
533
- # Cache
534
- .cache
535
-
536
- # Yalc
537
- .yalc
538
- yalc.lock
539
-
540
- # npm package zips
541
- *.tgz
542
- `
543
- };
544
- }
545
- function eslintrcTemplate(options) {
546
- const { flags } = options, eslintConfig = {
547
- root: !0,
548
- env: {
549
- node: !0,
550
- browser: !0
551
- },
552
- extends: [
553
- "sanity",
554
- flags.typescript && "sanity/typescript",
555
- "sanity/react",
556
- "plugin:react-hooks/recommended",
557
- flags.prettier && "plugin:prettier/recommended",
558
- "plugin:react/jsx-runtime"
559
- ].filter(Boolean)
560
- };
561
- return {
562
- type: "template",
563
- force: flags.force,
564
- to: ".eslintrc",
565
- value: JSON.stringify(eslintConfig, null, 2)
566
- };
567
- }
568
- function eslintignoreTemplate(options) {
569
- const { flags, outDir } = options, patterns = [
570
- ".eslintrc.js",
571
- "commitlint.config.js",
572
- outDir,
573
- "lint-staged.config.js",
574
- flags.typescript ? "package.config.ts" : "package.config.js",
575
- flags.typescript ? "*.js" : ""
576
- ].filter(Boolean);
577
- return patterns.sort(), {
578
- type: "template",
579
- force: flags.force,
580
- to: ".eslintignore",
581
- value: patterns.join(`
582
- `)
583
- };
584
- }
585
- function prettierignoreTemplate(options) {
586
- const { outDir } = options;
587
- return {
588
- type: "template",
589
- to: ".prettierignore",
590
- value: [outDir, "pnpm-lock.yaml", "yarn.lock", "package-lock.json"].join(`
591
- `)
592
- };
593
- }
594
- const bannedFields = ["login", "description", "projecturl", "email"], preferredLicenses = ["MIT", "ISC", "BSD-3-Clause"], otherLicenses = Object.keys(licenses__default.default.list).filter((id) => {
595
- const license = licenses__default.default.list[id];
596
- return !preferredLicenses.includes(id) && !bannedFields.some((field) => license.body.includes(`[${field}]`));
597
- });
598
- async function inject(options) {
599
- options.flags.presetOnly ? cli.log.info("Only apply presets, skipping default inject.") : await injectBase(options), await injectPresets(options);
600
- }
601
- async function injectBase(options) {
602
- const { basePath, flags, requireUserConfirmation } = options, info2 = (write, msg, ...args) => write && cli.log.info(msg, ...args), pkg = await _package$1.getPackage(options).catch(_package$1.errorToUndefined);
603
- cli.log.debug("Plugin has package.json: %s", pkg ? "yes" : "no");
604
- const user = await getUserInfo(options, pkg);
605
- cli.log.debug("User information: %o", user);
606
- const pkgName = flags.name ?? pkg?.name, pluginName = requireUserConfirmation || !pkgName ? await _package$1.promptForPackageName(options, pkgName) : pkgName;
607
- cli.log.debug("Plugin name: %s", pluginName);
608
- const license = await getLicense(flags, { user, pluginName, pkg, requireUserConfirmation }), licenseChanged = (pkg && pkg.license) !== (license && license.id);
609
- cli.log.debug("License: %s", license ? license.id : "<none>");
610
- const description = await getProjectDescription(basePath, pkg, requireUserConfirmation);
611
- cli.log.debug("Description: %s", description || "<none>");
612
- const repoUrl = flags.repo ?? (await gitRemoteOriginUrl__default.default(basePath).catch(_package$1.errorToUndefined) || pkg?.repository?.url), gitOrigin = requireUserConfirmation ? await _package$1.promptForRepoOrigin(options, repoUrl) : repoUrl;
613
- cli.log.debug("Remote origin: %s", gitOrigin || "<none>");
614
- const data = { user, pluginName, license, description, pkg, gitOrigin };
615
- let didWrite;
616
- const newPkg = await _package$1.writePackageJson(data, options);
617
- info2(newPkg !== pkg, "Wrote package.json"), data.pkg = newPkg, didWrite = await writeLicense(data, options, licenseChanged), info2(didWrite, "Wrote license file (LICENSE)"), didWrite = await writeReadme(data, options), info2(didWrite, "Wrote readme file (README.md)"), didWrite = await writeStaticAssets(options), info2(didWrite.length > 0, "Wrote static asset files: %s", didWrite.join(", ")), didWrite = await _package$1.addBuildScripts(newPkg, options), info2(didWrite, "Added build scripts to package.json"), didWrite = await addCompileDirToGitIgnore(data, options), info2(didWrite, "Added compilation output directory to .gitignore");
618
- }
619
- async function writeReadme(data, options) {
620
- const { basePath } = options, readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8").catch(_package$1.errorToUndefined);
621
- return readme && !isDefaultGitHubReadme(readme) ? !1 : (await _package$1.writeFileWithOverwritePrompt(readmePath, generateReadme(data), {
622
- encoding: "utf8",
623
- force: options.flags.force
624
- }), !0);
625
- }
626
- async function writeLicense({ license }, options, licenseChanged) {
627
- const { basePath, flags } = options;
628
- if (flags.license === !1 || !license)
629
- return !1;
630
- const hasLicenseMdFile = await _package$1.fileExists(path__default.default.join(basePath, "LICENSE.md")), licensePath = path__default.default.join(basePath, hasLicenseMdFile ? "LICENSE.md" : "LICENSE");
631
- return await _package$1.writeFileWithOverwritePrompt(licensePath, license.text, {
632
- encoding: "utf8",
633
- default: licenseChanged,
634
- force: flags.force
635
- }), !0;
636
- }
637
- async function getLicense(flags, {
638
- user,
639
- pluginName,
640
- pkg,
641
- requireUserConfirmation
642
- }) {
643
- const license = await getLicenseIdentifier(flags, pkg, requireUserConfirmation);
644
- if (!license)
645
- return;
646
- const text = license.body.replace(/\[fullname\]/g, user?.name).replace(/\[project\]/g, pluginName).replace(/\[year\]/g, (/* @__PURE__ */ new Date()).getFullYear());
647
- return { id: license.id, text };
648
- }
649
- async function getLicenseIdentifier(flags, pkg, requireUserConfirmation = !1) {
650
- if (flags.license === !1)
651
- return null;
652
- if (typeof flags.license == "string") {
653
- const license = licenses__default.default.find(`${flags.license}`);
654
- if (!license)
655
- throw new Error(`License "${flags.license}" not found`);
656
- return license;
657
- }
658
- if (pkg && pkg.license && !requireUserConfirmation) {
659
- const license = licenses__default.default.find(`${pkg.license}`);
660
- if (license)
661
- return license;
662
- cli.log.warn(`package.json contains license "${pkg.license}", which is not recognized`);
663
- }
664
- const licenseId = await _package$1.prompt("Which license do you want to use?", {
665
- default: pkg && pkg.license && licenses__default.default.find(pkg.license) ? pkg.license : preferredLicenses[0],
666
- choices: [
667
- _package$1.prompt.separator(),
668
- ...preferredLicenses.map((value) => ({ value, name: licenses__default.default.list[value].title })),
669
- _package$1.prompt.separator(),
670
- ...otherLicenses.map((value) => ({ value, name: licenses__default.default.list[value].title }))
671
- ]
672
- });
673
- return licenses__default.default.find(licenseId);
674
- }
675
- async function getProjectDescription(basePath, pkg, requireUserConfirmation = !1) {
676
- let description = await resolveProjectDescription(basePath, pkg);
677
- return requireUserConfirmation && (description = await _package$1.prompt("Plugin description", { default: description || "" })), description ?? "";
678
- }
679
- async function resolveProjectDescription(basePath, pkg) {
680
- if (pkg && typeof pkg.description == "string" && pkg.description.length > 5)
681
- return pkg.description;
682
- try {
683
- const readmePath = path__default.default.join(basePath, "README.md"), readme = await _package$1.readFile(readmePath, "utf8"), [title, description] = readme.split(`
684
- `).filter(Boolean);
685
- if (!title || !description || !title.match(/^#\s+\w+/))
686
- return null;
687
- const unlinked = description.replace(/\[(.*?)\]\(.*?\)/g, "$1");
688
- return /^[^#]/.test(unlinked) ? unlinked : null;
689
- } catch (err) {
690
- return _package$1.errorToUndefined(err);
691
- }
692
- }
693
- async function writeAssets(injectables, { basePath, flags }) {
694
- const assetsDir = await findAssetsDir(), from = (...segments) => path__default.default.join(assetsDir, "inject", ...segments), to = (...segments) => path__default.default.join(basePath, ...segments), writes = [];
695
- for (const injectable of injectables) {
696
- if (injectable.type === "copy") {
697
- const fromPath = asArray(injectable.from), toPath = asArray(injectable.to);
698
- await _package$1.copyFileWithOverwritePrompt(from(...fromPath), to(...toPath), flags) && writes.push(path__default.default.join(...toPath));
699
- continue;
700
- }
701
- if (injectable.type === "template") {
702
- const toPath = asArray(injectable.to);
703
- await _package$1.writeFileWithOverwritePrompt(to(...toPath), `${injectable.value.trim()}
704
- `, {
705
- default: "n",
706
- force: injectable.force || flags.force
707
- }), writes.push(path__default.default.join(...toPath));
708
- continue;
709
- }
710
- throw new Error(`Unknown operation type "${injectable.type}"`);
711
- }
712
- return writes;
713
- }
714
- async function writeStaticAssets(options) {
715
- const { outDir, flags } = options, files2 = [
716
- flags.eslint && eslintrcTemplate({ flags: options.flags }),
717
- flags.eslint && eslintignoreTemplate({ outDir, flags: options.flags }),
718
- { type: "copy", from: "editorconfig", to: ".editorconfig" },
719
- { type: "copy", from: "sanity.json", to: "sanity.json" },
720
- { type: "copy", from: "v2-incompatible.js.template", to: "v2-incompatible.js" },
721
- pkgConfigTemplate({ outDir, flags: options.flags }),
722
- flags.gitignore && gitignoreTemplate(),
723
- flags.typescript && tsconfigTemplate({ flags: options.flags }),
724
- flags.typescript && tsconfigTemplateDist({ outDir, flags: options.flags }),
725
- flags.typescript && tsconfigTemplateSettings({ outDir, flags: options.flags }),
726
- flags.prettier && prettierignoreTemplate({ outDir }),
727
- flags.prettier && { type: "copy", from: "prettierrc.json", to: ".prettierrc" }
728
- ].map((f) => f || void 0).filter((f) => !!f);
729
- return writeAssets(files2, options);
730
- }
731
- function asArray(input) {
732
- return typeof input == "string" ? [input] : input;
733
- }
734
- async function findAssetsDir() {
735
- let maxBackpaddle = 3, currDir = __dirname, assetsDir = "";
736
- for (; !assetsDir && maxBackpaddle; ) {
737
- currDir = path__default.default.join(currDir, "..");
738
- const assets = path__default.default.join(currDir, "assets");
739
- await _package$1.fileExists(assets) ? assetsDir = assets : maxBackpaddle--;
740
- }
741
- if (!assetsDir)
742
- throw new Error("Could not find assets directory!");
743
- return assetsDir;
744
- }
745
- async function addCompileDirToGitIgnore(data, options) {
746
- const gitIgnorePath = path__default.default.join(options.basePath, ".gitignore"), gitignore = await _package$1.readFile(gitIgnorePath, "utf8").catch(_package$1.errorToUndefined);
747
- if (!gitignore)
748
- return !1;
749
- const output = data.pkg?.main ?? data.pkg?.module;
750
- if (!output)
751
- return !1;
752
- const ignore = output.replace(/^[./]+/, "").split("/")[0];
753
- if (!ignore)
754
- return !1;
755
- const lines = gitignore.trim().split(`
756
- `);
757
- return lines.includes(ignore) ? !1 : (lines.push("", "# Compiled plugin", ignore), await _package$1.writeFile(gitIgnorePath, lines.join(`
758
- `) + `
759
- `, { encoding: "utf8" }), !0);
760
- }
761
- function defaultSourceJs(pkg) {
762
- return outdent__default.default`
763
- import {definePlugin} from 'sanity'
764
-
765
- /**
766
- * Usage in sanity.config.js (or .ts)
767
- *
768
- * \`\`\`js
769
- * import {defineConfig} from 'sanity'
770
- * import {myPlugin} from '${pkg.name}'
771
- *
772
- * export default defineConfig({
773
- * // ...
774
- * plugins: [myPlugin({})],
775
- * })
776
- * \`\`\`
777
- */
778
- export const myPlugin = definePlugin((config = {}) => {
779
- // eslint-disable-next-line no-console
780
- console.log(\`hello from ${pkg.name}\`)
781
- return {
782
- name: '${pkg.name}',
783
- }
784
- })
785
- `.trimStart() + `
786
- `;
787
- }
788
- function defaultSourceTs(pkg) {
789
- return outdent__default.default`
790
- import {definePlugin} from 'sanity'
791
-
792
- interface MyPluginConfig {
793
- /* nothing here yet */
794
- }
795
-
796
- /**
797
- * Usage in \`sanity.config.ts\` (or .js)
798
- *
799
- * \`\`\`ts
800
- * import {defineConfig} from 'sanity'
801
- * import {myPlugin} from '${pkg.name}'
802
- *
803
- * export default defineConfig({
804
- * // ...
805
- * plugins: [myPlugin()],
806
- * })
807
- * \`\`\`
808
- */
809
- export const myPlugin = definePlugin<MyPluginConfig | void>((config = {}) => {
810
- // eslint-disable-next-line no-console
811
- console.log('hello from ${pkg.name}')
812
- return {
813
- name: '${pkg.name}',
814
- }
815
- })
816
- `.trimStart() + `
817
- `;
818
- }
819
- const initFlags = {
820
- ...cli.sharedFlags,
821
- scripts: {
822
- type: "boolean",
823
- default: !0
824
- },
825
- eslint: {
826
- type: "boolean",
827
- default: !0
828
- },
829
- typescript: {
830
- type: "boolean",
831
- default: !0
832
- },
833
- prettier: {
834
- type: "boolean",
835
- default: !0
836
- },
837
- license: {
838
- type: "string"
839
- },
840
- editorconfig: {
841
- type: "boolean",
842
- default: !0
843
- },
844
- gitignore: {
845
- type: "boolean",
846
- default: !0
847
- },
848
- force: {
849
- type: "boolean",
850
- default: !1
851
- },
852
- install: {
853
- type: "boolean",
854
- default: !0
855
- },
856
- name: {
857
- type: "string"
858
- },
859
- author: {
860
- type: "string"
861
- },
862
- repo: {
863
- type: "string"
864
- },
865
- presetOnly: {
866
- type: "boolean",
867
- default: !1
868
- },
869
- preset: {
870
- type: "string",
871
- isMultiple: !0
872
- }
873
- };
874
- async function init(options) {
875
- let dependencies = {}, devDependencies2 = {}, peerDependencies = {};
876
- await inject({
877
- ...options,
878
- outDir: cli.defaultOutDir,
879
- requireUserConfirmation: !options.flags.force,
880
- dependencies,
881
- devDependencies: devDependencies2,
882
- peerDependencies,
883
- validate: !1
884
- });
885
- const packageJson = await _package$1.getPackage({ basePath: options.basePath, validate: !1 }), typescript = options.flags.typescript, source = typescript ? defaultSourceTs(packageJson) : defaultSourceJs(packageJson), filename = typescript ? "index.ts" : "index.js", srcDir = path__default.default.resolve(options.basePath, "src");
886
- await _package$1.ensureDir(srcDir), await _package$1.writeFile(path__default.default.join(srcDir, filename), source, { encoding: "utf8" });
887
- }
888
- exports.init = init;
889
- exports.initFlags = initFlags;
890
- exports.inject = inject;
891
- exports.presetHelpList = presetHelpList;
892
- //# sourceMappingURL=init.js.map