tegami 0.2.1 → 1.0.0-beta.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.
@@ -0,0 +1,362 @@
1
+ import { i as isNodeError, n as execFailure } from "./error-DNy8R5ue.js";
2
+ import { n as WorkspacePackage } from "./graph-OnX9ncdQ.js";
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { x } from "tinyexec";
6
+ import * as semver from "semver";
7
+ import z from "zod";
8
+ import { load } from "js-yaml";
9
+ import { glob } from "tinyglobby";
10
+ import { detect } from "package-manager-detector";
11
+ //#region src/providers/npm/schema.ts
12
+ const stringRecordSchema = z.record(z.string(), z.string());
13
+ const pnpmWorkspaceSchema = z.looseObject({ packages: z.array(z.string()).optional() });
14
+ const packageManifestSchema = z.looseObject({
15
+ name: z.string(),
16
+ version: z.string().optional(),
17
+ private: z.boolean().optional(),
18
+ publishConfig: z.looseObject({
19
+ access: z.enum(["public", "restricted"]).optional(),
20
+ registry: z.string().optional(),
21
+ tag: z.string().optional()
22
+ }).optional(),
23
+ scripts: z.record(z.string(), z.string()).optional(),
24
+ workspaces: z.array(z.string()).optional(),
25
+ dependencies: stringRecordSchema.optional(),
26
+ devDependencies: stringRecordSchema.optional(),
27
+ peerDependencies: stringRecordSchema.optional(),
28
+ optionalDependencies: stringRecordSchema.optional()
29
+ });
30
+ //#endregion
31
+ //#region src/providers/npm.ts
32
+ const DEP_FIELDS = [
33
+ "dependencies",
34
+ "devDependencies",
35
+ "peerDependencies",
36
+ "optionalDependencies"
37
+ ];
38
+ var NpmPackage = class extends WorkspacePackage {
39
+ path;
40
+ manifest;
41
+ manager = "npm";
42
+ constructor(path, manifest) {
43
+ super();
44
+ this.path = path;
45
+ this.manifest = manifest;
46
+ }
47
+ get name() {
48
+ return this.manifest.name;
49
+ }
50
+ get version() {
51
+ return this.manifest.version ?? "0.0.0";
52
+ }
53
+ async write() {
54
+ await writeFile(path.join(this.path, "package.json"), `${JSON.stringify(this.manifest, null, 2)}\n`);
55
+ }
56
+ initDraft() {
57
+ const defaults = super.initDraft();
58
+ defaults.npm = { distTag: this.manifest.publishConfig?.tag };
59
+ return defaults;
60
+ }
61
+ configureDraft(draft, group) {
62
+ super.configureDraft(draft, group);
63
+ const { distTag = group?.options?.npm?.distTag } = this.getPackageOptions().npm ?? {};
64
+ if (distTag) {
65
+ draft.npm ??= {};
66
+ draft.npm.distTag = distTag;
67
+ } else if (draft.prerelease) {
68
+ draft.npm ??= {};
69
+ draft.npm.distTag ??= draft.prerelease;
70
+ }
71
+ }
72
+ };
73
+ function parseDependencySpec(context, dependent, name, range) {
74
+ const { graph } = context;
75
+ if (range.startsWith("workspace:")) return {
76
+ range: range.slice(10),
77
+ linked: graph.get(`npm:${name}`),
78
+ protocol: "workspace"
79
+ };
80
+ if (range.startsWith("file:")) {
81
+ let target = path.resolve(dependent.path, range.slice(5));
82
+ if (path.basename(target) === "package.json") target = path.dirname(target);
83
+ return {
84
+ protocol: "file",
85
+ raw: range,
86
+ linked: graph.getPackages().find((pkg) => pkg instanceof NpmPackage && pkg.path === target)
87
+ };
88
+ }
89
+ if (range.startsWith("npm:")) {
90
+ const spec = range.slice(4);
91
+ const separator = spec.lastIndexOf("@");
92
+ if (separator <= 0) return;
93
+ const alias = spec.slice(0, separator);
94
+ return {
95
+ alias,
96
+ linked: graph.get(`npm:${alias}`),
97
+ range: spec.slice(separator + 1),
98
+ protocol: "npm"
99
+ };
100
+ }
101
+ return {
102
+ linked: graph.get(`npm:${name}`),
103
+ range
104
+ };
105
+ }
106
+ function formatDependencySpec(spec) {
107
+ if (spec.protocol === "workspace") return `workspace:${spec.range}`;
108
+ if (spec.protocol === "file") return spec.raw;
109
+ if (spec.protocol === "npm") return `npm:${spec.alias}@${spec.range}`;
110
+ return spec.range;
111
+ }
112
+ const packageLockSchema = z.object({
113
+ id: z.string(),
114
+ distTag: z.string().optional()
115
+ });
116
+ function npm({ client: defaultClient, onBreakPeerDep = "set", updateLockFile = true, bumpDep: getBumpDepType = ({ kind }) => {
117
+ switch (kind) {
118
+ case "dependencies":
119
+ case "optionalDependencies": return "patch";
120
+ case "devDependencies": return false;
121
+ case "peerDependencies":
122
+ if (onBreakPeerDep === "ignore") return false;
123
+ return "major";
124
+ }
125
+ } } = {}) {
126
+ let active = false;
127
+ let client;
128
+ return {
129
+ name: "npm",
130
+ enforce: "pre",
131
+ async init() {
132
+ if (defaultClient) client = defaultClient;
133
+ else client = (await detect({ cwd: this.cwd }))?.name ?? "npm";
134
+ this.npm = { client };
135
+ },
136
+ async resolve() {
137
+ await discoverNpmPackages(this.cwd, (pkg) => this.graph.add(pkg));
138
+ active = this.graph.getPackages().some((pkg) => pkg instanceof NpmPackage);
139
+ },
140
+ async publishPreflight({ pkg }) {
141
+ if (!(pkg instanceof NpmPackage)) return;
142
+ return { publish: pkg.manifest.private !== true && !await isPackagePublished(pkg) };
143
+ },
144
+ initPublishLock({ lock, draft }) {
145
+ for (const [id, pkg] of draft.getPackageDrafts()) {
146
+ if (!pkg.npm) continue;
147
+ lock.write("npm:packages", {
148
+ id,
149
+ distTag: pkg.npm.distTag
150
+ });
151
+ }
152
+ },
153
+ initPublishPlan({ lock, plan }) {
154
+ let data;
155
+ while (data = lock.read("npm:packages")) {
156
+ const parsed = packageLockSchema.safeParse(data).data;
157
+ if (!parsed) continue;
158
+ const packagePlan = plan.packages.get(parsed.id);
159
+ if (!packagePlan) continue;
160
+ packagePlan.npm = { distTag: parsed.distTag };
161
+ }
162
+ },
163
+ async publish({ pkg, plan }) {
164
+ if (!(pkg instanceof NpmPackage)) return;
165
+ return publish(client, pkg, plan.packages.get(pkg.id)?.npm?.distTag);
166
+ },
167
+ initDraft(plan) {
168
+ if (!active) return;
169
+ plan.addPolicy(depsPolicy(this, getBumpDepType));
170
+ },
171
+ async applyDraft(draft) {
172
+ if (!active) return;
173
+ const { graph } = this;
174
+ const writes = [];
175
+ for (const pkg of graph.getPackages()) {
176
+ if (!(pkg instanceof NpmPackage)) continue;
177
+ const plan = draft.getPackageDraft(pkg.id);
178
+ if (plan) pkg.manifest.version = plan.bumpVersion(pkg);
179
+ }
180
+ for (const pkg of graph.getPackages()) {
181
+ if (!(pkg instanceof NpmPackage)) continue;
182
+ for (const field of DEP_FIELDS) {
183
+ const dependencies = pkg.manifest[field];
184
+ if (!dependencies) continue;
185
+ for (const [k, v] of Object.entries(dependencies)) {
186
+ const spec = parseDependencySpec(this, pkg, k, v);
187
+ if (!spec?.linked || spec.protocol === "workspace" || spec.protocol === "file") continue;
188
+ if (!semver.validRange(spec.range)) continue;
189
+ if (semver.satisfies(spec.linked.version, spec.range)) continue;
190
+ let updatedRange;
191
+ const isPeer = field === "peerDependencies";
192
+ if (isPeer && onBreakPeerDep === "ignore") continue;
193
+ else if (isPeer && onBreakPeerDep === "set") updatedRange = spec.linked.version;
194
+ else if (isPeer && onBreakPeerDep === "error") throw new Error(`[Tegami] the version of "${spec.linked.name}" is beyond its peer dependency constraint "${v}" in package "${pkg.name}", please update the constraint to satisfy.`);
195
+ else if (spec.range.startsWith("^")) updatedRange = `^${spec.linked.version}`;
196
+ else if (spec.range.startsWith("~")) updatedRange = `~${spec.linked.version}`;
197
+ else updatedRange = spec.linked.version;
198
+ dependencies[k] = formatDependencySpec({
199
+ ...spec,
200
+ range: updatedRange
201
+ });
202
+ }
203
+ }
204
+ writes.push(pkg.write());
205
+ }
206
+ await Promise.all(writes);
207
+ },
208
+ cli: { async draftApplied() {
209
+ if (!active || !updateLockFile) return;
210
+ let args;
211
+ if (client === "npm") args = ["ci"];
212
+ else if (client === "yarn") args = ["install", "--immutable"];
213
+ else if (client === "bun") args = ["install", "--frozen-lockfile"];
214
+ else args = ["install", "--frozen-lockfile"];
215
+ const result = await x(client, args, { nodeOptions: { cwd: this.cwd } });
216
+ if (result.exitCode !== 0) throw execFailure("Failed to update lockfile.", result);
217
+ } }
218
+ };
219
+ }
220
+ function depsPolicy(context, getBumpDepType) {
221
+ const { graph } = context;
222
+ function needsUpdate(spec, target) {
223
+ if (spec.linked && spec.protocol === "workspace") switch (spec.range) {
224
+ case "":
225
+ case "*": return true;
226
+ case "^":
227
+ case "~": return !semver.satisfies(target, `${spec.range}${spec.linked.version}`);
228
+ }
229
+ if (spec.linked && spec.protocol === "file") return true;
230
+ if (spec.protocol === "file" || !semver.validRange(spec.range)) return false;
231
+ return !semver.satisfies(target, spec.range);
232
+ }
233
+ return {
234
+ id: "npm:deps",
235
+ onUpdate({ pkg, packageDraft: plan }) {
236
+ if (!(pkg instanceof NpmPackage)) return;
237
+ const group = graph.getPackageGroup(pkg.id);
238
+ for (const dependent of graph.getPackages()) {
239
+ if (!(dependent instanceof NpmPackage)) continue;
240
+ for (const field of DEP_FIELDS) {
241
+ const dependencies = dependent.manifest[field];
242
+ if (!dependencies) continue;
243
+ for (const [k, v] of Object.entries(dependencies)) {
244
+ const spec = parseDependencySpec(context, dependent, k, v);
245
+ if (!spec || spec.linked !== pkg) continue;
246
+ if (group?.options.syncBump && graph.getPackageGroup(dependent.id) === group) continue;
247
+ if (!needsUpdate(spec, plan.bumpVersion(pkg))) continue;
248
+ const bumpType = getBumpDepType({
249
+ kind: field,
250
+ dependent,
251
+ spec,
252
+ name: k
253
+ });
254
+ if (bumpType === false) continue;
255
+ this.bumpPackage(dependent, {
256
+ type: bumpType,
257
+ reason: `update dependency "${k}"`
258
+ });
259
+ }
260
+ }
261
+ }
262
+ }
263
+ };
264
+ }
265
+ async function publish(client, pkg, distTag) {
266
+ if (client === "bun") {
267
+ for (const script of [
268
+ "prepublishOnly",
269
+ "prepack",
270
+ "prepare"
271
+ ]) {
272
+ if (!pkg.manifest.scripts?.[script]) continue;
273
+ const result = await x("bun", ["run", script], { nodeOptions: { cwd: pkg.path } });
274
+ if (result.exitCode === 0) continue;
275
+ return {
276
+ type: "failed",
277
+ error: execFailure(`Failed to run ${script} script for ${pkg.name}@${pkg.version}.`, result).message
278
+ };
279
+ }
280
+ const tarballPath = path.resolve(pkg.path, "pkg.tgz");
281
+ const packResult = await x("bun", [
282
+ "pm",
283
+ "pack",
284
+ "--filename",
285
+ tarballPath
286
+ ], { nodeOptions: { cwd: pkg.path } });
287
+ if (packResult.exitCode !== 0) return {
288
+ type: "failed",
289
+ error: execFailure(`Failed to pack ${pkg.name}@${pkg.version}.`, packResult).message
290
+ };
291
+ const publishArgs = ["publish", tarballPath];
292
+ if (distTag) publishArgs.push("--tag", distTag);
293
+ const publishResult = await x("npm", publishArgs, { nodeOptions: { cwd: pkg.path } });
294
+ if (publishResult.exitCode !== 0) return {
295
+ type: "failed",
296
+ error: execFailure(`Failed to publish ${pkg.name}@${pkg.version}${distTag ? ` with dist-tag "${distTag}"` : ""}.`, publishResult).message
297
+ };
298
+ return { type: "published" };
299
+ }
300
+ let command;
301
+ const args = ["publish"];
302
+ if (distTag) args.push("--tag", distTag);
303
+ if (client === "pnpm") {
304
+ command = "pnpm";
305
+ args.push("--no-git-checks");
306
+ } else if (client === "yarn") command = "yarn";
307
+ else command = "npm";
308
+ const result = await x(command, args, { nodeOptions: { cwd: pkg.path } });
309
+ if (result.exitCode !== 0) return {
310
+ type: "failed",
311
+ error: execFailure(`Failed to publish ${pkg.name}@${pkg.version}${distTag ? ` with dist-tag "${distTag}"` : ""}.`, result).message
312
+ };
313
+ return { type: "published" };
314
+ }
315
+ async function isPackagePublished(pkg) {
316
+ const registry = pkg.manifest.publishConfig?.registry ?? "https://registry.npmjs.org";
317
+ const base = registry.replace(/\/$/, "");
318
+ const response = await fetch(`${base}/${pkg.name}/${pkg.version}`, { headers: { Accept: "application/json" } });
319
+ if (response.status === 404) return false;
320
+ if (!response.ok) throw new Error(`Unable to validate ${pkg.name}@${pkg.version} against the npm registry${registry ? ` "${registry}"` : ""}.`);
321
+ return true;
322
+ }
323
+ async function discoverNpmPackages(cwd, add) {
324
+ let patterns;
325
+ const rootManifest = await readManifest(cwd).catch(() => void 0);
326
+ const pnpmPatterns = await readFile(path.join(cwd, "pnpm-workspace.yaml"), "utf8").then((content) => pnpmWorkspaceSchema.parse(load(content) ?? {})).catch((error) => {
327
+ if (isNodeError(error) && error.code === "ENOENT") return void 0;
328
+ throw error;
329
+ });
330
+ if (pnpmPatterns) patterns = pnpmPatterns.packages ?? [];
331
+ else patterns = rootManifest?.workspaces ?? [];
332
+ const candidatePaths = await expandWorkspacePatterns(cwd, patterns);
333
+ const manifests = await Promise.all(candidatePaths.map((path) => readManifest(path).then((manifest) => ({
334
+ path,
335
+ manifest
336
+ })).catch(() => void 0)));
337
+ if (rootManifest?.name) add(new NpmPackage(cwd, rootManifest));
338
+ for (const entry of manifests) {
339
+ if (!entry) continue;
340
+ add(new NpmPackage(entry.path, entry.manifest));
341
+ }
342
+ }
343
+ async function expandWorkspacePatterns(cwd, patterns) {
344
+ if (patterns.length === 0) return [];
345
+ return (await glob(patterns, {
346
+ absolute: true,
347
+ cwd,
348
+ ignore: ["**/node_modules/**", "**/dist/**"],
349
+ onlyDirectories: true,
350
+ onlyFiles: false
351
+ })).map((item) => {
352
+ return item.endsWith(path.sep) ? item.slice(0, -1) : item;
353
+ });
354
+ }
355
+ async function readManifest(packagePath) {
356
+ const content = await readFile(path.join(packagePath, "package.json"), "utf8");
357
+ const parsed = JSON.parse(content);
358
+ packageManifestSchema.parse(parsed);
359
+ return parsed;
360
+ }
361
+ //#endregion
362
+ export { npm as n, NpmPackage as t };
@@ -1,4 +1,4 @@
1
- import { s as TegamiPlugin } from "../types-DEaKjB3O.js";
1
+ import { s as TegamiPlugin } from "../types-DnCUr2dB.js";
2
2
 
3
3
  //#region src/plugins/git.d.ts
4
4
  interface GitPluginOptions {
@@ -1,4 +1,4 @@
1
- import { D as WorkspacePackage, O as Draft, S as PublishPlan, s as TegamiPlugin, t as Awaitable, w as TegamiContext } from "../types-DEaKjB3O.js";
1
+ import { C as WorkspacePackage, b as TegamiContext, p as PublishPlan, s as TegamiPlugin, t as Awaitable, w as Draft } from "../types-DnCUr2dB.js";
2
2
  import { GitPluginOptions } from "./git.js";
3
3
 
4
4
  //#region src/plugins/github.d.ts
@@ -1,4 +1,4 @@
1
- import { i as formatPackageVersion, r as formatNpmDistTag } from "../semver-C4vJ4SK8.js";
1
+ import { i as formatPackageVersion, r as formatNpmDistTag } from "../semver-jcIUAvbl.js";
2
2
  import { a as isCI, n as execFailure } from "../error-DNy8R5ue.js";
3
3
  import { a as findOpenPullRequest, l as updatePullRequest, n as createPullRequest, r as createRelease, s as releaseExistsByTag } from "../api-D-jf_8xY.js";
4
4
  import { git } from "./git.js";
@@ -26,9 +26,7 @@ function github(options = {}) {
26
26
  if (!packageDraft) continue;
27
27
  const originalVersion = cliOriginalPackageVersions.get(pkg.id) ?? pkg.version;
28
28
  if (originalVersion === pkg.version) continue;
29
- let line = `- **${pkg.name}**: ${originalVersion} ${pkg.version}`;
30
- line += formatNpmDistTag(packageDraft.npm?.distTag);
31
- packageLines.push(line);
29
+ packageLines.push(`| \`${pkg.name}\` | \`${originalVersion}\` | \`${pkg.version}\`${formatNpmDistTag(packageDraft.npm?.distTag)} |`);
32
30
  }
33
31
  const changelogLines = [];
34
32
  for (const entry of draft.getChangelogs()) {
@@ -42,9 +40,9 @@ function github(options = {}) {
42
40
  "## Summary",
43
41
  "",
44
42
  "Merge this PR to publish the versioned packages.",
45
- "",
46
- ...packageLines
43
+ ""
47
44
  ];
45
+ if (packageLines.length > 0) sections.push("| Package | From | To |", "| --- | --- | --- |", ...packageLines);
48
46
  if (changelogLines.length > 0) sections.push("", "## Changelogs", ...changelogLines);
49
47
  sections.push("");
50
48
  return sections.join("\n");
@@ -0,0 +1,51 @@
1
+ import { C as WorkspacePackage, O as BumpType, s as TegamiPlugin } from "../types-DnCUr2dB.js";
2
+
3
+ //#region src/plugins/go.d.ts
4
+ interface GoModFile {
5
+ module: string;
6
+ requires: Map<string, string>;
7
+ replaces: Map<string, GoReplace>;
8
+ }
9
+ interface GoReplace {
10
+ module: string;
11
+ path?: string;
12
+ version?: string;
13
+ }
14
+ declare class GoPackage extends WorkspacePackage {
15
+ readonly path: string;
16
+ readonly mod: GoModFile;
17
+ readonly manager = "go";
18
+ private versionValue;
19
+ private pendingRequires;
20
+ constructor(path: string, mod: GoModFile, version: string);
21
+ get name(): string;
22
+ get version(): string;
23
+ setVersion(version: string): void;
24
+ setRequire(module: string, version: string): void;
25
+ write(): Promise<void>;
26
+ }
27
+ interface GoPluginOptions {
28
+ /**
29
+ * Run `go work sync` or `go mod tidy` after versioning.
30
+ *
31
+ * @default true
32
+ */
33
+ updateLockFile?: boolean;
34
+ bumpDep?: (opts: {
35
+ dependent: GoPackage;
36
+ name: string;
37
+ version: string;
38
+ }) => BumpType | false;
39
+ }
40
+ /**
41
+ * Experimental plugin for Golang, the release flow of Golang is pretty special, there's some exceptions for it:
42
+ *
43
+ * - Version is stored in lock file, normally, it should prefer to store versions in a file like `package.json` & `Cargo.toml`, but for Golang, there is no such file.
44
+ * - Publishing is handed to Git plugin, because Golang uses Git tag for publishing.
45
+ */
46
+ declare function go({
47
+ updateLockFile,
48
+ bumpDep: getBumpDepType
49
+ }?: GoPluginOptions): TegamiPlugin;
50
+ //#endregion
51
+ export { GoPackage, GoPluginOptions, go };