@livespace/plugin-cli 0.1.1 → 0.3.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.
@@ -1,15 +1,29 @@
1
- /** `keys init`, `keys rotate`, `keys retire` and `keys jwks`. Never prints key material. */
2
- import { mkdir, writeFile } from "node:fs/promises";
1
+ /**
2
+ * `keys init`, `keys rotate`, `keys retire` and `keys jwks`. Never prints key material.
3
+ *
4
+ * Where the public halves live depends on how the plugin reaches an account
5
+ * (docs/adr/0005-tenancy-and-distribution-decide-keys.md):
6
+ *
7
+ * - a catalog plugin has a `plugin-manifest.json`, and its `publicKeys` are the key set. Livespace
8
+ * never reads a `jwks.json` for it;
9
+ * - a plugin added by URL has no manifest, and the `jwks.json` it publishes is the key set. These
10
+ * commands then edit that file directly.
11
+ */
12
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
3
13
  import { dirname, join, relative } from "node:path";
4
14
  import { KEYS_DIR, ensureGitignored, writePrivateKey } from "../keys/files.js";
5
15
  import { generateKeyPair } from "../keys/generate.js";
6
16
  import { addKey, keysOfUse, nextKid, retireKey } from "../keys/keyset.js";
7
17
  import { checkManifest } from "../manifest/check.js";
8
- import { serializeManifest, writeManifest } from "../manifest/file.js";
18
+ import { readManifestText, serializeManifest, writeManifest, } from "../manifest/file.js";
9
19
  import { KEY_USES, MANIFEST_FILE, MIN_RSA_BITS, } from "../manifest/schema.js";
10
20
  import { UsageError } from "./context.js";
11
21
  import { loadManifest } from "./load.js";
12
- const JWKS_PATH = ".well-known/livespace/jwks.json";
22
+ /** Where Livespace fetches a plugin's key set from, on the plugin's origin. */
23
+ export const JWKS_PATH = ".well-known/livespace/jwks.json";
24
+ /** Where a project with a `public/` directory keeps it, so its build serves it at `JWKS_PATH`. */
25
+ const PUBLIC_JWKS_PATH = `public/${JWKS_PATH}`;
26
+ const HOSTING_RULES = 'Serve it at /.well-known/livespace/jwks.json on the plugin\'s origin, as application/json, no redirect, under 16 KiB, with Access-Control-Allow-Origin: * on any request header (browsers send priority and cache-control). On S3, that\'s a CORS rule with "AllowedHeaders": ["*"].';
13
27
  const bitsOf = (ctx) => {
14
28
  const raw = ctx.flags.bits;
15
29
  if (raw === undefined) {
@@ -22,16 +36,16 @@ const bitsOf = (ctx) => {
22
36
  return bits;
23
37
  };
24
38
  /**
25
- * New key pairs for `uses`, added to the manifest's `publicKeys` (in memory). Nothing is written:
26
- * the caller saves the private halves with `saveKeys`, then the manifest.
39
+ * New key pairs for `uses`, added to `holder.publicKeys` (in memory): a manifest, or a bare key
40
+ * set. Nothing is written: the caller saves the private halves with `saveKeys`, then the holder.
27
41
  */
28
- export async function createKeys(ctx, manifest, uses) {
42
+ export async function createKeys(ctx, holder, uses) {
29
43
  const bits = bitsOf(ctx);
30
44
  const pairs = [];
31
45
  for (const use of uses) {
32
- const kids = (manifest.publicKeys?.keys ?? []).map((k) => k.kid);
46
+ const kids = (holder.publicKeys?.keys ?? []).map((k) => k.kid);
33
47
  const pair = await generateKeyPair(use, nextKid(use, ctx.now, kids), bits);
34
- manifest.publicKeys = addKey(manifest.publicKeys, pair.publicJwk);
48
+ holder.publicKeys = addKey(holder.publicKeys, pair.publicJwk);
35
49
  pairs.push(pair);
36
50
  }
37
51
  return pairs;
@@ -50,19 +64,110 @@ export async function saveKeys(ctx, pairs) {
50
64
  }
51
65
  ctx.out.warn(`Move the private keys into your backend's secret storage, and back up the encryption key: if it's lost, every customer has to re-enter their secrets. Never commit ${KEYS_DIR}/.`);
52
66
  }
67
+ const exists = (path) => stat(path).then(() => true, () => false);
68
+ /**
69
+ * Without a manifest: `--out`, else whichever jwks.json is already there, else `public/…` when the
70
+ * project has a `public/` directory (a created project does), else the project root.
71
+ */
72
+ async function jwksPathFor(ctx) {
73
+ if (typeof ctx.flags.out === "string") {
74
+ return ctx.flags.out;
75
+ }
76
+ for (const candidate of [PUBLIC_JWKS_PATH, JWKS_PATH]) {
77
+ if (await exists(join(ctx.dir, candidate))) {
78
+ return candidate;
79
+ }
80
+ }
81
+ return (await exists(join(ctx.dir, "public"))) ? PUBLIC_JWKS_PATH : JWKS_PATH;
82
+ }
83
+ async function readJwks(path, label) {
84
+ let text;
85
+ try {
86
+ text = await readFile(path, "utf8");
87
+ }
88
+ catch (error) {
89
+ if (error.code === "ENOENT") {
90
+ return undefined;
91
+ }
92
+ throw error;
93
+ }
94
+ let value;
95
+ try {
96
+ value = JSON.parse(text);
97
+ }
98
+ catch (error) {
99
+ throw new UsageError(`${label} is not valid JSON (${error.message})`);
100
+ }
101
+ if (typeof value !== "object" ||
102
+ value === null ||
103
+ !Array.isArray(value.keys)) {
104
+ throw new UsageError(`${label} must be a key set, { "keys": [ … ] }`);
105
+ }
106
+ return value;
107
+ }
108
+ /**
109
+ * The manifest when there is one. Otherwise the jwks.json: `create` allows a new one (for `keys
110
+ * init`); the other commands need one to be there.
111
+ */
112
+ async function loadKeyHome(ctx, { create }) {
113
+ if ((await readManifestText(ctx.dir)) !== undefined) {
114
+ const manifest = await loadManifest(ctx);
115
+ return {
116
+ label: MANIFEST_FILE,
117
+ manifest,
118
+ holder: manifest,
119
+ save: () => saveManifest(ctx, manifest),
120
+ afterChange: () => { },
121
+ };
122
+ }
123
+ const label = await jwksPathFor(ctx);
124
+ const path = join(ctx.dir, label);
125
+ const set = await readJwks(path, label);
126
+ if (set === undefined && !create) {
127
+ throw new UsageError(`no ${MANIFEST_FILE} and no ${label} here — create the keys with \`keys init\``);
128
+ }
129
+ const holder = { publicKeys: set };
130
+ return {
131
+ label,
132
+ manifest: undefined,
133
+ holder,
134
+ save: async () => {
135
+ await mkdir(dirname(path), { recursive: true });
136
+ const keys = holder.publicKeys?.keys ?? [];
137
+ await writeFile(path, `${JSON.stringify({ keys }, null, 2)}\n`);
138
+ },
139
+ afterChange: () => {
140
+ if (set === undefined) {
141
+ ctx.out.info(`No ${MANIFEST_FILE} here, so the key set is ${label}: for a plugin added by URL. (A catalog plugin's keys go in its manifest instead.)`);
142
+ }
143
+ ctx.out.info(`Publish ${label} for the change to take effect. ${HOSTING_RULES}`);
144
+ },
145
+ };
146
+ }
53
147
  /** After a key change: what still fails the checker is reported, but doesn't block the change. */
54
148
  async function saveManifest(ctx, manifest) {
149
+ if (manifest.publicKeys?.keys.length === 0) {
150
+ manifest.publicKeys = undefined;
151
+ }
55
152
  await writeManifest(ctx.dir, manifest, { create: false });
56
153
  const { failures } = checkManifest(serializeManifest(manifest));
57
154
  for (const failure of failures) {
58
155
  ctx.out.warn(`${MANIFEST_FILE} still fails: ${failure}`);
59
156
  }
60
157
  }
61
- /** `--use sig|enc|both`; by default a signing key, plus an encryption key if there are secrets. */
62
- function usesFor(ctx, manifest) {
158
+ /**
159
+ * `--use sig|enc|both`. By default a signing key, plus an encryption key if the manifest has
160
+ * secrets; with no manifest to look at, both: a plugin added by URL only needs keys for secrets.
161
+ */
162
+ function usesFor(ctx, home) {
63
163
  const requested = ctx.flags.use;
64
164
  if (requested === undefined) {
65
- return (manifest.secretKeys?.length ?? 0) > 0 ? ["sig", "enc"] : ["sig"];
165
+ if (home.manifest === undefined) {
166
+ return ["sig", "enc"];
167
+ }
168
+ return (home.manifest.secretKeys?.length ?? 0) > 0
169
+ ? ["sig", "enc"]
170
+ : ["sig"];
66
171
  }
67
172
  if (requested === "both") {
68
173
  return ["sig", "enc"];
@@ -73,21 +178,25 @@ function usesFor(ctx, manifest) {
73
178
  throw new UsageError("--use is sig, enc or both");
74
179
  }
75
180
  export async function keysInit(ctx) {
76
- const manifest = await loadManifest(ctx);
77
- const uses = usesFor(ctx, manifest);
181
+ const home = await loadKeyHome(ctx, { create: true });
182
+ const uses = usesFor(ctx, home);
78
183
  for (const use of uses) {
79
- if (keysOfUse(manifest.publicKeys, use).length > 0) {
80
- throw new UsageError(`the manifest already has a "${use}" key — add another with \`keys rotate --use ${use}\``);
184
+ if (keysOfUse(home.holder.publicKeys, use).length > 0) {
185
+ throw new UsageError(`${home.label} already has a "${use}" key — add another with \`keys rotate --use ${use}\``);
81
186
  }
82
187
  }
83
- const pairs = await createKeys(ctx, manifest, uses);
188
+ const pairs = await createKeys(ctx, home.holder, uses);
84
189
  await saveKeys(ctx, pairs);
85
- await saveManifest(ctx, manifest);
86
- ctx.out.end(`Added ${pairs.map((p) => p.publicJwk.kid).join(" and ")} to ${MANIFEST_FILE}.`);
87
- ctx.out.result({ added: pairs.map((p) => p.publicJwk.kid) });
190
+ await home.save();
191
+ home.afterChange();
192
+ ctx.out.end(`Added ${pairs.map((p) => p.publicJwk.kid).join(" and ")} to ${home.label}.`);
193
+ ctx.out.result({
194
+ added: pairs.map((p) => p.publicJwk.kid),
195
+ keySet: home.label,
196
+ });
88
197
  }
89
198
  export async function keysRotate(ctx) {
90
- const manifest = await loadManifest(ctx);
199
+ const home = await loadKeyHome(ctx, { create: false });
91
200
  const use = await ctx.prompter.select({
92
201
  name: "use",
93
202
  message: "Which key?",
@@ -106,37 +215,46 @@ export async function keysRotate(ctx) {
106
215
  });
107
216
  ctx.prompter.assertComplete();
108
217
  // Fails here, before anything is written, if the use already holds two keys.
109
- const pairs = await createKeys(ctx, manifest, [use]);
218
+ const pairs = await createKeys(ctx, home.holder, [use]);
110
219
  await saveKeys(ctx, pairs);
111
- await saveManifest(ctx, manifest);
220
+ await home.save();
221
+ home.afterChange();
112
222
  const kid = pairs[0]?.publicJwk.kid;
113
223
  ctx.out.end(use === "enc"
114
- ? `${kid} is now the first encryption key: secrets saved from the next release on use it. Keep both private keys, and pick by each secret's kid.`
224
+ ? `${kid} is now the first encryption key: secrets saved once ${home.label} is published use it. Keep both private keys, and pick by each secret's kid.`
115
225
  : `${kid} is listed beside the current signing key. Switch your backend to sign with it, then \`keys retire\` the old one.`);
116
- ctx.out.result({ added: kid });
226
+ ctx.out.result({ added: kid, keySet: home.label });
117
227
  }
118
228
  export async function keysRetire(ctx, kid) {
119
229
  if (kid === undefined) {
120
- throw new UsageError('keys retire <kid> — the kids are in the manifest\'s "publicKeys"');
230
+ throw new UsageError('keys retire <kid> — the kids are in the key set: the manifest\'s "publicKeys", or the jwks.json');
121
231
  }
122
- const manifest = await loadManifest(ctx);
232
+ const home = await loadKeyHome(ctx, { create: false });
123
233
  const { set, retired } = (() => {
124
234
  try {
125
- return retireKey(manifest.publicKeys, kid);
235
+ return retireKey(home.holder.publicKeys, kid);
126
236
  }
127
237
  catch (error) {
128
238
  throw new UsageError(error.message);
129
239
  }
130
240
  })();
131
- manifest.publicKeys = set.keys.length > 0 ? set : undefined;
132
- await saveManifest(ctx, manifest);
241
+ home.holder.publicKeys = set;
242
+ await home.save();
243
+ home.afterChange();
133
244
  ctx.out.warn(retired.use === "enc"
134
245
  ? `Secrets stored under ${kid} will ask their admins to re-enter them. Destroy ${KEYS_DIR}/${kid}.pem only after that's done.`
135
246
  : `Make sure your backend no longer signs with ${kid}. Then destroy ${KEYS_DIR}/${kid}.pem.`);
136
- ctx.out.end(`Removed ${kid} from ${MANIFEST_FILE}.`);
137
- ctx.out.result({ retired: kid });
247
+ ctx.out.end(`Removed ${kid} from ${home.label}.`);
248
+ ctx.out.result({ retired: kid, keySet: home.label });
138
249
  }
250
+ /**
251
+ * A jwks.json from the manifest's keys, for the rare catalog plugin that is also added by URL.
252
+ * Without a manifest there's nothing to derive: the jwks.json already is the key set.
253
+ */
139
254
  export async function keysJwks(ctx) {
255
+ if ((await readManifestText(ctx.dir)) === undefined) {
256
+ throw new UsageError(`no ${MANIFEST_FILE} here, so the jwks.json is the key set itself — \`keys init\`, \`keys rotate\` and \`keys retire\` edit it directly`);
257
+ }
140
258
  const manifest = await loadManifest(ctx);
141
259
  const keys = manifest.publicKeys?.keys ?? [];
142
260
  if (keys.length === 0) {
@@ -147,6 +265,6 @@ export async function keysJwks(ctx) {
147
265
  await mkdir(dirname(path), { recursive: true });
148
266
  await writeFile(path, `${JSON.stringify({ keys }, null, 2)}\n`);
149
267
  ctx.out.success(`Wrote ${out}.`);
150
- ctx.out.end('For a plugin also installed by URL: serve it at /.well-known/livespace/jwks.json on the plugin\'s origin, as application/json, no redirect, under 16 KiB, with Access-Control-Allow-Origin: * on any request header (browsers send priority and cache-control). On S3, that\'s a CORS rule with "AllowedHeaders": ["*"].');
268
+ ctx.out.end(`Only needed if this plugin is also added by URL: Livespace never reads it for a catalog plugin, whose keys come from ${MANIFEST_FILE}. ${HOSTING_RULES}`);
151
269
  ctx.out.result({ jwks: out, keys: keys.map((k) => k.kid) });
152
270
  }
@@ -3,7 +3,7 @@ import { checkManifest } from "../manifest/check.js";
3
3
  import { readManifestText, readPackageJson, serializeManifest, writeManifest, } from "../manifest/file.js";
4
4
  import { prefillFrom } from "../manifest/package-json.js";
5
5
  import { CATEGORIES, EXPECTED_LOCALES, LOCALES, MANIFEST_FILE, OBJECT_TYPES, REQUIRED_LOCALE, clientIdOf, } from "../manifest/schema.js";
6
- import { isHexColor, isHttpsOrigin, isHttpsUrl, isId, isKeyList, isSemver, isSvgUrl, splitList, } from "../ui/validators.js";
6
+ import { isHexColor, isHttpsOrigin, isHttpsUrl, isId, isImageUrl, isKeyList, isSemver, splitList, } from "../ui/validators.js";
7
7
  import { UsageError } from "./context.js";
8
8
  import { createKeys, saveKeys } from "./keys.js";
9
9
  import { loadManifest } from "./load.js";
@@ -14,7 +14,6 @@ const OBJECT_TYPE_LABELS = {
14
14
  company: "Company",
15
15
  person: "Person",
16
16
  space: "Space",
17
- dashboard: "Dashboard (the start screen)",
18
17
  };
19
18
  const LOCALE_LABELS = {
20
19
  en: "English",
@@ -28,7 +27,7 @@ const objectTypeChoices = [
28
27
  {
29
28
  value: ANY,
30
29
  label: "Any type",
31
- hint: "no requirements, the apps menu included",
30
+ hint: "every type, and the apps menu with no record; alone",
32
31
  },
33
32
  ...OBJECT_TYPES.map((type) => ({
34
33
  value: type,
@@ -39,9 +38,12 @@ const objectTypeChoices = [
39
38
  const toObjectTypes = (answer) => answer.includes(ANY) ? null : answer;
40
39
  const askObjectTypes = async (p, initial) => toObjectTypes(await p.multiselect({
41
40
  name: "object-types",
42
- message: "Where may it go? (one or more, or Any type)",
41
+ message: "Where may it go? (one or more types, or Any type alone)",
43
42
  options: objectTypeChoices,
44
43
  initial,
44
+ validate: (values) => values.includes(ANY) && values.length > 1
45
+ ? "Any type already covers every type: pick it alone, or only the types"
46
+ : undefined,
45
47
  }));
46
48
  /**
47
49
  * Which languages to write texts in. Asked in a terminal; from flags, it's whatever languages the
@@ -161,15 +163,15 @@ export async function manifestInit(ctx) {
161
163
  const categories = await askCategories(p);
162
164
  const iconUrl = await p.text({
163
165
  name: "icon-url",
164
- message: "Icon URL (.svg, optional)?",
166
+ message: "Icon URL (.svg or .png, optional)?",
165
167
  optional: true,
166
- validate: isSvgUrl,
168
+ validate: isImageUrl,
167
169
  });
168
170
  const illustrationUrl = await p.text({
169
171
  name: "illustration-url",
170
- message: "Illustration URL (.svg, optional)?",
172
+ message: "Illustration URL (.svg or .png, optional)?",
171
173
  optional: true,
172
- validate: isSvgUrl,
174
+ validate: isImageUrl,
173
175
  });
174
176
  const accentColor = await p.text({
175
177
  name: "accent-color",
@@ -268,7 +270,7 @@ const SETTERS = {
268
270
  message: "Icon URL?",
269
271
  initial: m.iconUrl,
270
272
  optional: true,
271
- validate: isSvgUrl,
273
+ validate: isImageUrl,
272
274
  });
273
275
  },
274
276
  "illustration-url": async (p, m) => {
@@ -277,7 +279,7 @@ const SETTERS = {
277
279
  message: "Illustration URL?",
278
280
  initial: m.illustrationUrl,
279
281
  optional: true,
280
- validate: isSvgUrl,
282
+ validate: isImageUrl,
281
283
  });
282
284
  },
283
285
  "accent-color": async (p, m) => {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `skill install` copies the livespace-plugin skill into the plugin project, into the skill
3
+ * targets the chosen harnesses read (docs/adr/0002-skill-installs-as-copies-in-two-dirs.md).
4
+ * It always writes this CLI's skill, replacing a copy that's there: the CLI bootstraps a project,
5
+ * and running it again is how a project takes a newer skill (docs/adr/0003).
6
+ */
7
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ import { addToGitignore } from "../project/gitignore.js";
10
+ import { SDK_LLMS_TXT_CDN_URL, SUPPORTED_SDK_RANGE, isSupportedSdkVersion, } from "../sdk/range.js";
11
+ import { CLI_VERSION, HARNESSES, SKILL_FILE, SKILL_NAME, readSkillSource, readStamp, renderSkill, targetsFor, } from "../skill/source.js";
12
+ const exists = (path) => access(path).then(() => true, () => false);
13
+ /** The installed SDK's version, or undefined when it isn't in node_modules. */
14
+ async function installedSdkVersion(dir) {
15
+ try {
16
+ const text = await readFile(join(dir, "node_modules/@livespace/plugin-sdk/package.json"), "utf8");
17
+ return JSON.parse(text).version;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ export async function skillInstall(ctx) {
24
+ ctx.out.start(`Install the ${SKILL_NAME} skill`);
25
+ const harnesses = await ctx.prompter.multiselect({
26
+ name: "harness",
27
+ message: "Which coding agents should see it?",
28
+ options: Object.entries(HARNESSES).map(([value, { label, reads }]) => ({
29
+ value: value,
30
+ label,
31
+ hint: reads.join(", "),
32
+ })),
33
+ initial: ["claude-code"],
34
+ });
35
+ const gitignore = await ctx.prompter.confirm({
36
+ name: "gitignore",
37
+ message: "Keep it out of git? (No commits it, so everyone on the project gets it.)",
38
+ initial: false,
39
+ });
40
+ ctx.prompter.assertComplete();
41
+ const sdkVersion = await installedSdkVersion(ctx.dir);
42
+ const supported = sdkVersion === undefined ? undefined : isSupportedSdkVersion(sdkVersion);
43
+ if (sdkVersion === undefined) {
44
+ ctx.out.info(`@livespace/plugin-sdk isn't in node_modules, so the skill will read ${SDK_LLMS_TXT_CDN_URL}.`);
45
+ }
46
+ else if (!supported) {
47
+ ctx.out.warn(`The project has @livespace/plugin-sdk ${sdkVersion}, but this CLI's skill is written for ${SUPPORTED_SDK_RANGE}. Its workflow may not match the SDK; llms.txt is still the installed one.`);
48
+ }
49
+ const copy = renderSkill(readSkillSource());
50
+ const targets = [];
51
+ for (const target of targetsFor(harnesses)) {
52
+ const skillDir = `${target}/${SKILL_NAME}`;
53
+ const path = join(ctx.dir, skillDir, SKILL_FILE);
54
+ const before = await readFile(path, "utf8").catch(() => undefined);
55
+ await mkdir(join(ctx.dir, skillDir), { recursive: true });
56
+ await writeFile(path, copy);
57
+ if (before === undefined) {
58
+ ctx.out.success(`Wrote ${skillDir}/${SKILL_FILE}`);
59
+ targets.push({ dir: skillDir, status: "written" });
60
+ }
61
+ else {
62
+ const stamp = readStamp(before);
63
+ ctx.out.success(`Replaced ${skillDir}/${SKILL_FILE} (${stamp ? `from CLI ${stamp.cliVersion}` : "unstamped"}) with this CLI's (${CLI_VERSION})`);
64
+ targets.push({
65
+ dir: skillDir,
66
+ status: "replaced",
67
+ replaced: stamp ?? null,
68
+ });
69
+ }
70
+ }
71
+ const ignored = [];
72
+ if (gitignore) {
73
+ for (const { dir } of targets) {
74
+ if (await addToGitignore(ctx.dir, dir)) {
75
+ ignored.push(dir);
76
+ }
77
+ }
78
+ if (ignored.length > 0) {
79
+ ctx.out.info(`Added ${ignored.join(", ")} to .gitignore.`);
80
+ }
81
+ }
82
+ const shadowed = ctx.home !== undefined &&
83
+ targets.some(({ dir }) => dir.startsWith(".claude/")) &&
84
+ (await exists(join(ctx.home, ".claude/skills", SKILL_NAME)));
85
+ if (shadowed) {
86
+ ctx.out.warn(`~/.claude/skills/${SKILL_NAME} exists, and Claude Code prefers it to the project's copy. Remove it to use this one.`);
87
+ }
88
+ ctx.out.end("Done. Ask your agent to build the plugin; the skill reads the SDK's llms.txt first.");
89
+ ctx.out.result({
90
+ skill: SKILL_NAME,
91
+ stamp: { cliVersion: CLI_VERSION, sdkRange: SUPPORTED_SDK_RANGE },
92
+ targets,
93
+ gitignored: ignored,
94
+ sdk: { version: sdkVersion ?? null, supported: supported ?? null },
95
+ shadowedByUserSkill: shadowed,
96
+ });
97
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The project templates `create` copies (docs/adr/0004-template-follows-invoker-no-framework.md):
3
+ * `templates/shared/` for every project, then one overlay for its build tool.
4
+ */
5
+ import { cp, mkdir, readFile, readdir, rename, writeFile, } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { STUDIO_RANGE, SUPPORTED_SDK_MAJOR, SUPPORTED_SDK_RANGE, } from "../sdk/range.js";
9
+ export const TEMPLATES = ["vite", "bun"];
10
+ /** The same from `src/create/` and `dist/create/`. */
11
+ const TEMPLATES_DIR = fileURLToPath(new URL("../../templates/", import.meta.url));
12
+ /** npm drops `.gitignore` from a published package, so the template keeps it under this name. */
13
+ const GITIGNORE = "gitignore";
14
+ /** Every file below `dir`, relative to it. */
15
+ async function filesIn(dir) {
16
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
17
+ return entries
18
+ .filter((entry) => entry.isFile())
19
+ .map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1));
20
+ }
21
+ /**
22
+ * Writes a template into `dir`, which `create` has already checked is empty: the shared files,
23
+ * the overlay, `{{placeholders}}` filled in, `.gitignore` restored, and an empty `public/`.
24
+ */
25
+ export async function writeTemplate(dir, template, values) {
26
+ const sources = [join(TEMPLATES_DIR, "shared"), join(TEMPLATES_DIR, template)];
27
+ const written = new Set();
28
+ for (const source of sources) {
29
+ await cp(source, dir, { recursive: true });
30
+ for (const file of await filesIn(source)) {
31
+ written.add(file);
32
+ }
33
+ }
34
+ const fill = {
35
+ name: values.name,
36
+ run: values.run,
37
+ sdkRange: SUPPORTED_SDK_RANGE,
38
+ sdkMajor: String(SUPPORTED_SDK_MAJOR),
39
+ studioRange: STUDIO_RANGE,
40
+ };
41
+ for (const file of written) {
42
+ const path = join(dir, file);
43
+ const text = await readFile(path, "utf8");
44
+ const filled = text.replace(/\{\{(\w+)\}\}/g, (match, key) => fill[key] ?? match);
45
+ if (filled !== text) {
46
+ await writeFile(path, filled);
47
+ }
48
+ }
49
+ await rename(join(dir, GITIGNORE), join(dir, ".gitignore"));
50
+ written.delete(GITIGNORE);
51
+ written.add(".gitignore");
52
+ await mkdir(join(dir, "public"), { recursive: true });
53
+ return [...written].sort();
54
+ }
@@ -2,8 +2,9 @@
2
2
  * Where private keys go: `keys/<kid>.pem` in the project, the directory 0700, each file 0600,
3
3
  * never overwritten, and `keys/` in `.gitignore`. Nothing here prints a key.
4
4
  */
5
- import { mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { mkdir, writeFile } from "node:fs/promises";
6
6
  import { join } from "node:path";
7
+ import { addToGitignore } from "../project/gitignore.js";
7
8
  export const KEYS_DIR = "keys";
8
9
  const SAFE_KID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
9
10
  export async function writePrivateKey(dir, kid, pem) {
@@ -24,25 +25,4 @@ export async function writePrivateKey(dir, kid, pem) {
24
25
  return path;
25
26
  }
26
27
  /** Adds `keys/` to the project's `.gitignore`. True if it had to. */
27
- export async function ensureGitignored(dir) {
28
- const path = join(dir, ".gitignore");
29
- let text = "";
30
- try {
31
- text = await readFile(path, "utf8");
32
- }
33
- catch (error) {
34
- if (error.code !== "ENOENT") {
35
- throw error;
36
- }
37
- }
38
- const covered = text
39
- .split(/\r?\n/)
40
- .map((line) => line.trim().replace(/^\//, "").replace(/\/$/, ""))
41
- .includes(KEYS_DIR);
42
- if (covered) {
43
- return false;
44
- }
45
- const separator = text === "" || text.endsWith("\n") ? "" : "\n";
46
- await writeFile(path, `${text}${separator}${KEYS_DIR}/\n`);
47
- return true;
48
- }
28
+ export const ensureGitignored = (dir) => addToGitignore(dir, KEYS_DIR);
@@ -9,7 +9,7 @@
9
9
  import { CATEGORIES, EXPECTED_LOCALES, FIELDS, ID_PATTERN, KEY_ALG, KEY_USES, MAX_KEYS_PER_USE, MIN_RSA_BITS, OBJECT_TYPES, REQUIRED_LOCALE, } from "./schema.js";
10
10
  const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
11
11
  const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
12
- const SVG = /\.svg(?:[?#].*)?$/i;
12
+ const IMAGE = /\.(?:svg|png)(?:[?#].*)?$/i;
13
13
  const RAW_HTML = /<\/?[a-zA-Z][^>]*>/;
14
14
  const LINK = /\[[^\]]*\]\([^)]*\)|<https?:\/\/[^>]*>|https?:\/\/\S+/;
15
15
  /** JWK members that only a private key has. One in a manifest is a leaked key. */
@@ -185,8 +185,8 @@ function checkAssets(m, failures, warnings) {
185
185
  continue;
186
186
  }
187
187
  if ((key === "iconUrl" || key === "illustrationUrl") &&
188
- !SVG.test(url.pathname)) {
189
- failures.push(`"${key}" must be an .svg`);
188
+ !IMAGE.test(url.pathname)) {
189
+ failures.push(`"${key}" must be an .svg or .png`);
190
190
  }
191
191
  if (origin !== undefined && url.origin !== origin) {
192
192
  warnings.push(`"${key}" is served from another origin than the plugin (${url.origin}) — fine if intended`);
@@ -13,13 +13,7 @@ export const MANIFEST_FILE = "plugin-manifest.json";
13
13
  * Where a catalog plugin may go. `null` in a manifest means any of them, the context-free `none`
14
14
  * included; a list never names `none` and is never empty (the registry skips such an entry).
15
15
  */
16
- export const OBJECT_TYPES = [
17
- "deal",
18
- "company",
19
- "person",
20
- "space",
21
- "dashboard",
22
- ];
16
+ export const OBJECT_TYPES = ["deal", "company", "person", "space"];
23
17
  /** Livespace's languages, the ones the catalog texts are worth writing in. `en` is the fallback. */
24
18
  export const LOCALES = ["en", "pl", "ro", "cs", "es", "sk"];
25
19
  export const REQUIRED_LOCALE = "en";
@@ -0,0 +1,26 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ /** `/a/b/`, `a/b` and `a/b/` all ignore the same directory. */
4
+ const normalise = (line) => line.trim().replace(/^\//, "").replace(/\/$/, "");
5
+ /**
6
+ * Adds a directory to the project's `.gitignore`, as `<entry>/`, unless a line already covers it.
7
+ * True if it had to.
8
+ */
9
+ export async function addToGitignore(dir, entry) {
10
+ const path = join(dir, ".gitignore");
11
+ let text = "";
12
+ try {
13
+ text = await readFile(path, "utf8");
14
+ }
15
+ catch (error) {
16
+ if (error.code !== "ENOENT") {
17
+ throw error;
18
+ }
19
+ }
20
+ if (text.split(/\r?\n/).map(normalise).includes(normalise(entry))) {
21
+ return false;
22
+ }
23
+ const separator = text === "" || text.endsWith("\n") ? "" : "\n";
24
+ await writeFile(path, `${text}${separator}${normalise(entry)}/\n`);
25
+ return true;
26
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The one range of `@livespace/plugin-sdk` versions this CLI release targets
3
+ * (docs/adr/0003-cli-pins-a-supported-sdk-range.md).
4
+ *
5
+ * `create` installs it, the skill's stamp records it, and the skill's fallback
6
+ * `llms.txt` URL uses its major. The skill's wording assumes this major; what
7
+ * changes within it reaches the skill through `llms.txt`. A test keeps it in
8
+ * step with `packages/sdk`, so bump it when the SDK's major moves.
9
+ */
10
+ export const SUPPORTED_SDK_MAJOR = 1;
11
+ /** As an npm range, for `npm install @livespace/plugin-sdk@<range>`. */
12
+ export const SUPPORTED_SDK_RANGE = `^${SUPPORTED_SDK_MAJOR}`;
13
+ /**
14
+ * Whether an installed SDK version (exact, as in its package.json) is one this
15
+ * CLI supports. A prerelease of the supported major counts; anything that
16
+ * isn't a version doesn't.
17
+ */
18
+ export const isSupportedSdkVersion = (version) => {
19
+ const match = /^(\d+)\.\d+\.\d+(?:[-+].*)?$/.exec(version.trim());
20
+ return match !== null && Number(match[1]) === SUPPORTED_SDK_MAJOR;
21
+ };
22
+ /** `llms.txt` on jsDelivr, for a project without the SDK in `node_modules`. */
23
+ export const SDK_LLMS_TXT_CDN_URL = `https://cdn.jsdelivr.net/npm/@livespace/plugin-sdk@${SUPPORTED_SDK_MAJOR}/dist/llms.txt`;
24
+ /**
25
+ * The `@livespace/plugin-studio` range `create`'s templates list as a dev dependency. The studio
26
+ * takes the project's SDK as a peer, so it isn't tied to the SDK's major. A test keeps it in step
27
+ * with `packages/studio`.
28
+ */
29
+ export const STUDIO_RANGE = "^0.1";