@stacksjs/buddy 0.70.180 → 0.70.182

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.
@@ -33,6 +33,8 @@ export * from './migrate-project';
33
33
  export * from './outdated';
34
34
  export * from './phone';
35
35
  export * from './ports';
36
+ export * from './link';
37
+ export * from './user';
36
38
  export * from './prepublish';
37
39
  export * from './projects';
38
40
  export * from './protocol';
@@ -33,6 +33,8 @@ export * from "./migrate-project";
33
33
  export * from "./outdated";
34
34
  export * from "./phone";
35
35
  export * from "./ports";
36
+ export * from "./link";
37
+ export * from "./user";
36
38
  export * from "./prepublish";
37
39
  export * from "./projects";
38
40
  export * from "./protocol";
@@ -0,0 +1,2 @@
1
+ import type { CLI } from '@stacksjs/types';
2
+ export declare function link(buddy: CLI): void;
@@ -0,0 +1,147 @@
1
+ import { existsSync, lstatSync, readdirSync, realpathSync } from "node:fs";
2
+ import fs from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import process from "node:process";
6
+ import { italic, log } from "@stacksjs/cli";
7
+ import { ExitCode } from "@stacksjs/types";
8
+ function recordPath() {
9
+ return join(process.cwd(), "storage/framework/runtime/linked-core.json");
10
+ }
11
+ function readRecord() {
12
+ try {
13
+ return JSON.parse(fs.readFileSync(recordPath(), "utf-8"));
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ function writeRecord(record) {
19
+ fs.mkdirSync(join(process.cwd(), "storage/framework/runtime"), { recursive: !0 });
20
+ fs.writeFileSync(recordPath(), `${JSON.stringify(record, null, 2)}
21
+ `);
22
+ }
23
+ function resolveFrameworkPath(explicit) {
24
+ const candidates = [
25
+ explicit,
26
+ process.env.STACKS_FRAMEWORK_PATH,
27
+ resolve(process.cwd(), "../stacks"),
28
+ join(homedir(), "Code/stacks")
29
+ ].filter(Boolean);
30
+ for (const candidate of candidates) {
31
+ const full = resolve(candidate);
32
+ if (existsSync(join(full, "storage/framework/core")))
33
+ return full;
34
+ }
35
+ return null;
36
+ }
37
+ function corePackages(framework) {
38
+ const coreDir = join(framework, "storage/framework/core"), found = new Map;
39
+ for (const entry of readdirSync(coreDir, { withFileTypes: !0 })) {
40
+ if (!entry.isDirectory())
41
+ continue;
42
+ const dir = join(coreDir, entry.name), manifest = join(dir, "package.json");
43
+ if (!existsSync(manifest))
44
+ continue;
45
+ try {
46
+ const { name } = JSON.parse(fs.readFileSync(manifest, "utf-8"));
47
+ if (name?.startsWith("@stacksjs/"))
48
+ found.set(name, dir);
49
+ } catch {}
50
+ }
51
+ return found;
52
+ }
53
+ function normalize(name) {
54
+ return `@stacksjs/${name.replace(/^@stacksjs\//, "").replace(/^core\//, "")}`;
55
+ }
56
+ function isSymlink(path) {
57
+ try {
58
+ return lstatSync(path).isSymbolicLink();
59
+ } catch {
60
+ return !1;
61
+ }
62
+ }
63
+ export function link(buddy) {
64
+ buddy.command("link:core [...packages]", "Point this app's @stacksjs/* at a local framework checkout").option("--path <path>", "Framework checkout to link against").option("--all", "Link every core package the app has installed", { default: !1 }).example("buddy link:core auth router").example("buddy link:core --all --path ../stacks").action(async (packages, options) => {
65
+ const framework = resolveFrameworkPath(options?.path);
66
+ if (!framework) {
67
+ log.error("No framework checkout found.");
68
+ log.info("Pass one with `--path <dir>` or set STACKS_FRAMEWORK_PATH.");
69
+ process.exit(ExitCode.FatalError);
70
+ }
71
+ const available = corePackages(framework), modulesDir = join(process.cwd(), "node_modules"), wanted = (packages?.length ?? 0) > 0 ? packages.map(normalize) : [...available.keys()].filter((name) => existsSync(join(modulesDir, name)) || options?.all);
72
+ if (wanted.length === 0) {
73
+ log.info("Nothing to link: no installed @stacksjs/* packages found in this project.");
74
+ await log.flush();
75
+ process.exit(ExitCode.Success);
76
+ }
77
+ const linked = [], unbuilt = [];
78
+ for (const name of wanted) {
79
+ const source = available.get(name);
80
+ if (!source) {
81
+ log.warn(`${name} is not in ${italic(framework)} \u2014 skipped.`);
82
+ continue;
83
+ }
84
+ const target = join(modulesDir, name);
85
+ if (isSymlink(target) && realpathSync(target) === realpathSync(source)) {
86
+ linked.push(name);
87
+ continue;
88
+ }
89
+ fs.rmSync(target, { recursive: !0, force: !0 });
90
+ fs.mkdirSync(join(target, ".."), { recursive: !0 });
91
+ fs.symlinkSync(source, target, "dir");
92
+ linked.push(name);
93
+ if (!existsSync(join(source, "dist")))
94
+ unbuilt.push(name);
95
+ }
96
+ writeRecord({ framework, packages: linked });
97
+ log.success(`Linked ${linked.length} package${linked.length === 1 ? "" : "s"} to ${italic(framework)}`);
98
+ if (unbuilt.length > 0) {
99
+ log.warn(`Not built yet: ${unbuilt.join(", ")}`);
100
+ log.info("An app imports the build output, so each linked package needs `bun build.ts` in its directory.");
101
+ }
102
+ log.info("Undo with `buddy unlink:core`.");
103
+ await log.flush();
104
+ process.exit(ExitCode.Success);
105
+ });
106
+ buddy.command("unlink:core [...packages]", "Go back to the installed @stacksjs/* packages").option("--all", "Unlink everything that was linked", { default: !1 }).example("buddy unlink:core").action(async (packages, _options) => {
107
+ const record = readRecord(), modulesDir = join(process.cwd(), "node_modules"), wanted = (packages?.length ?? 0) > 0 ? packages.map(normalize) : record?.packages ?? readdirSync(join(modulesDir, "@stacksjs"), { withFileTypes: !0 }).filter((entry) => entry.isSymbolicLink()).map((entry) => `@stacksjs/${entry.name}`);
108
+ let removed = 0;
109
+ const unlinked = new Set;
110
+ for (const name of wanted) {
111
+ const target = join(modulesDir, name);
112
+ if (!isSymlink(target))
113
+ continue;
114
+ fs.rmSync(target, { force: !0 });
115
+ unlinked.add(name);
116
+ removed++;
117
+ }
118
+ const survivors = (record?.packages ?? []).filter((name) => !unlinked.has(name));
119
+ if (survivors.length > 0)
120
+ writeRecord({ framework: record.framework, packages: survivors });
121
+ else
122
+ fs.rmSync(recordPath(), { force: !0 });
123
+ if (removed === 0) {
124
+ log.info("Nothing was linked.");
125
+ await log.flush();
126
+ process.exit(ExitCode.Success);
127
+ }
128
+ log.info(`Unlinked ${removed} package${removed === 1 ? "" : "s"}; reinstalling the published copies...`);
129
+ if (await Bun.spawn(["bun", "install", "--force"], { cwd: process.cwd(), stdout: "inherit", stderr: "inherit" }).exited !== 0) {
130
+ log.error("`bun install` failed. The links are gone; re-run the install once the failure is resolved.");
131
+ process.exit(ExitCode.FatalError);
132
+ }
133
+ for (const name of survivors) {
134
+ const source = join(record.framework, "storage/framework/core", name.replace("@stacksjs/", "")), target = join(modulesDir, name);
135
+ if (!existsSync(source))
136
+ continue;
137
+ fs.rmSync(target, { recursive: !0, force: !0 });
138
+ fs.symlinkSync(source, target, "dir");
139
+ }
140
+ if (survivors.length > 0)
141
+ log.success(`Unlinked ${removed}; ${survivors.length} package${survivors.length === 1 ? "" : "s"} still linked.`);
142
+ else
143
+ log.success("This project is back on the published packages.");
144
+ await log.flush();
145
+ process.exit(ExitCode.Success);
146
+ });
147
+ }
@@ -274,10 +274,24 @@ async function unvendorFramework(force) {
274
274
  await fs.promises.writeFile(bunfigPath, next);
275
275
  }
276
276
  await fs.promises.rm(coreDir, { recursive: !0, force: !0 });
277
+ const scopedDir = resolve(process.cwd(), "node_modules/@stacksjs");
278
+ let danglingRemoved = 0;
279
+ if (existsSync(scopedDir))
280
+ for (const entry of await readdir(scopedDir, { withFileTypes: !0 })) {
281
+ if (!entry.isSymbolicLink())
282
+ continue;
283
+ const link = resolve(scopedDir, entry.name);
284
+ if (existsSync(link))
285
+ continue;
286
+ await fs.promises.rm(link, { force: !0 });
287
+ danglingRemoved++;
288
+ }
277
289
  log.success(`Removed ${italic(rel(coreDir))}`);
278
290
  log.info(`package.json now depends on ${depName}@${range}`);
279
291
  if (repointed > 0)
280
292
  log.info(`Repointed ${repointed} workspace: range${repointed === 1 ? "" : "s"} to ${range}`);
293
+ if (danglingRemoved > 0)
294
+ log.info(`Removed ${danglingRemoved} node_modules symlink${danglingRemoved === 1 ? "" : "s"} left pointing into it`);
281
295
  if (rewrittenScripts > 0)
282
296
  log.info(`Repointed ${rewrittenScripts} package.json script${rewrittenScripts === 1 ? "" : "s"} to ./buddy`);
283
297
  if (rewrittenPreloads > 0)
@@ -0,0 +1,2 @@
1
+ import type { CLI } from '@stacksjs/types';
2
+ export declare function user(buddy: CLI): void;
@@ -0,0 +1,84 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import process from "node:process";
3
+ import { log } from "@stacksjs/cli";
4
+ import { ExitCode } from "@stacksjs/types";
5
+ function generatePassword() {
6
+ return randomBytes(18).toString("base64url");
7
+ }
8
+ async function loadUserModel() {
9
+ const { existsSync } = await import("node:fs"), { join } = await import("node:path"), candidates = [
10
+ join(process.cwd(), "app/Models/User.ts"),
11
+ join(process.cwd(), "storage/framework/defaults/app/Models/User.ts"),
12
+ join(process.cwd(), "node_modules/@stacksjs/defaults/app/Models/User.ts")
13
+ ];
14
+ for (const candidate of candidates) {
15
+ if (!existsSync(candidate))
16
+ continue;
17
+ const loaded = (await import(candidate)).default;
18
+ if (loaded?.where)
19
+ return loaded;
20
+ }
21
+ const { User } = await import("@stacksjs/orm");
22
+ if (User?.where)
23
+ return User;
24
+ log.error("Could not find a User model. Looked in app/Models, the framework defaults and @stacksjs/orm.");
25
+ process.exit(ExitCode.FatalError);
26
+ }
27
+ export function user(buddy) {
28
+ buddy.command("user:add <email>", "Create a user account (optionally an admin)").option("--name <name>", "Display name. Defaults to the local part of the email.").option("--password <password>", "Password. Generated and printed once if omitted.").option("--role <role>", "Role to assign, e.g. admin. Seeds the default roles if the table is empty.").option("--update", "If the account already exists, reset its password and ensure the role", { default: !1 }).example("buddy user:add chris@example.com --role admin").example("buddy user:add support@example.com --name Support --password s3cret").action(async (email, options) => {
29
+ const address = String(email || "").trim().toLowerCase();
30
+ if (!address.includes("@")) {
31
+ log.error(`\`${email}\` is not an email address.`);
32
+ process.exit(ExitCode.FatalError);
33
+ }
34
+ const password = options.password || generatePassword(), generated = !options.password, name = options.name || address.split("@")[0], User = await loadUserModel();
35
+ let account = await User.where("email", address).first();
36
+ if (account && !options.update) {
37
+ log.error(`${address} already exists. Pass --update to reset its password and role.`);
38
+ process.exit(ExitCode.FatalError);
39
+ }
40
+ if (account) {
41
+ await User.where("email", address).update({ password });
42
+ log.success(`Updated ${address}`);
43
+ } else {
44
+ await User.create({ email: address, name, password });
45
+ account = await User.where("email", address).first();
46
+ log.success(`Created ${address}`);
47
+ }
48
+ if (options.role) {
49
+ const { createBqbRbacStore, Rbac, seedDefaultRoles } = await import("@stacksjs/auth");
50
+ try {
51
+ Rbac.setStore(createBqbRbacStore());
52
+ await seedDefaultRoles();
53
+ await Rbac.assignRole(account, options.role);
54
+ log.success(`Assigned the ${options.role} role`);
55
+ } catch (error) {
56
+ log.error(`Could not assign the ${options.role} role: ${error instanceof Error ? error.message : String(error)}`);
57
+ log.info("The account exists; assign the role once the roles tables are migrated.");
58
+ }
59
+ }
60
+ if (generated) {
61
+ process.stdout.write(`
62
+ ${address}
63
+ ${password}
64
+
65
+ `);
66
+ log.info("That password is shown once. Store it in a password manager now.");
67
+ }
68
+ await log.flush();
69
+ process.exit(ExitCode.Success);
70
+ });
71
+ buddy.command("user:list", "List the accounts that can sign in").option("--limit <limit>", "How many to show", { default: "25" }).action(async (options) => {
72
+ const User = await loadUserModel(), limit = Number(options.limit) || 25, rows = await User.orderBy("id").limit(limit).get();
73
+ if (rows.length === 0) {
74
+ log.info("No accounts yet. Create one with `buddy user:add <email> --role admin`.");
75
+ await log.flush();
76
+ process.exit(ExitCode.Success);
77
+ }
78
+ for (const row of rows)
79
+ process.stdout.write(` ${String(row.id).padStart(4)} ${String(row.email).padEnd(34)} ${row.name ?? ""}
80
+ `);
81
+ await log.flush();
82
+ process.exit(ExitCode.Success);
83
+ });
84
+ }
@@ -77,6 +77,10 @@ const commandRegistry = {
77
77
  package: { path: "./commands/package.js", exportName: "packageCommands" },
78
78
  phone: { path: "./commands/phone.js", exportName: "phone" },
79
79
  ports: { path: "./commands/ports.js", exportName: "ports" },
80
+ "link:core": { path: "./commands/link.js", exportName: "link" },
81
+ "user:add": { path: "./commands/user.js", exportName: "user" },
82
+ "user:list": { path: "./commands/user.js", exportName: "user" },
83
+ "unlink:core": { path: "./commands/link.js", exportName: "link" },
80
84
  prepublish: { path: "./commands/prepublish.js", exportName: "prepublish" },
81
85
  projects: { path: "./commands/projects.js", exportName: "projects" },
82
86
  publish: { path: "./commands/publish.js", exportName: "publish" },
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.180",
5
+ "version": "0.70.182",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [