@livespace/plugin-studio 0.2.0 → 0.3.0-beta.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.
package/README.md CHANGED
@@ -11,6 +11,9 @@ Projects that [`@livespace/plugin-cli create`](https://www.npmjs.com/package/@li
11
11
  makes already have it, with a `studio` script. Outside a project, `npx @livespace/plugin-studio`
12
12
  runs it for any plugin page, a deployed one included.
13
13
 
14
+ It runs on Node 20.12 or later, or on Bun: `bunx --bun @livespace/plugin-studio`, where `--bun`
15
+ keeps it on Bun when an older Node is also installed.
16
+
14
17
  The studio uses the project's own `@livespace/plugin-sdk` (a peer dependency, `^1`), so it speaks
15
18
  the same protocol version as the plugin.
16
19
 
@@ -81,6 +84,20 @@ studio, and `--client-id` sets the starting client id (default: the manifest's `
81
84
  `plugin:dev`). The sidebar, the address and the layout are kept in your browser; what you save on
82
85
  the settings page lives in the studio's memory, so a restart starts that afresh.
83
86
 
87
+ ## A plugin that's plain files
88
+
89
+ A plugin with no build has no dev server. `--serve` serves its folder instead, usually `public/`:
90
+
91
+ ```sh
92
+ npx @livespace/plugin-studio --serve public
93
+ ```
94
+
95
+ The folder gets the port after the studio's (5191 by default), so the plugin has an origin of its
96
+ own, as in Livespace. Every file is sent with `Access-Control-Allow-Origin: *` and no caching, so
97
+ a published `jwks.json` is read as Livespace reads it. There's no live reload: after changing a
98
+ file, reload the studio's page. The manifest is read from `--dir` (default: the current
99
+ directory), so run it from the plugin's folder.
100
+
84
101
  ## Setting up a state from the address
85
102
 
86
103
  The address can set up a state in one go, which is quicker for a coding agent than clicking
@@ -116,6 +133,7 @@ http://localhost:5190/#settings?preferences=en-US&width=320
116
133
  | Flag | What it does |
117
134
  |---|---|
118
135
  | `--url <page>` | The plugin's page to start with. The page can change it. |
136
+ | `--serve <folder>` | A plugin that's plain files: the studio serves the folder and embeds its `index.html` ([below](#a-plugin-thats-plain-files)). Not with `--url`. |
119
137
  | `--port <n>` | Where the studio listens (default: 5190). |
120
138
  | `--client-id <id>` | The starting client id. The page can change it. |
121
139
  | `--dir <path>` | The plugin project, for its manifest and template (default: the current directory). |
package/dist/cli.js CHANGED
@@ -6,24 +6,29 @@
6
6
  import { readFileSync } from "node:fs";
7
7
  import { resolve } from "node:path";
8
8
  import { parseArgs } from "node:util";
9
+ import { serveStatic } from "./serve.js";
9
10
  import { startStudio } from "./server.js";
10
11
  import { STUDIO_PORT, UsageError, start, untilSignal } from "./start.js";
11
12
  const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
12
13
  const HELP = `livespace-plugin-studio ${version}: try a Livespace plugin locally
13
14
 
14
- Usage: livespace-plugin-studio [--url <plugin page>] [--port <n>] [--client-id <id>]
15
- [--dir <path>]
15
+ Usage: livespace-plugin-studio [--url <plugin page> | --serve <folder>] [--port <n>]
16
+ [--client-id <id>] [--dir <path>]
16
17
 
17
18
  Serves Plugin Studio at http://localhost:${STUDIO_PORT}. It embeds your plugin's page the way
18
19
  Livespace does, renders its settings form, logs every message, and acts as the account your
19
20
  backend calls (it prints the env values). Start your dev server first; the studio doesn't start it.
21
+ A plugin that's plain files needs none: --serve its folder.
20
22
 
21
23
  --url <page> The plugin's page (default: Vite's or Bun's dev server, from the
22
24
  project's template; otherwise the page asks). The page can change it.
25
+ --serve <folder> A plugin that's plain files, with no build (its public/): the studio
26
+ serves the folder on the next port, its own origin, and embeds its
27
+ index.html. After a change, reload the studio's page.
23
28
  --port <n> Where the studio listens (default: ${STUDIO_PORT}).
24
29
  --client-id <id> The plugin's client id (default: plugin:<id> from the project's
25
30
  plugin-manifest.json, else plugin:dev). The page can change it.
26
- --dir <path> The plugin project (default: the current directory).
31
+ --dir <path> The plugin project, for its manifest (default: the current directory).
27
32
  --help, -h This text.
28
33
  --version, -v The version.
29
34
  `;
@@ -35,6 +40,7 @@ async function main(argv) {
35
40
  port: { type: "string" },
36
41
  "client-id": { type: "string" },
37
42
  dir: { type: "string" },
43
+ serve: { type: "string" },
38
44
  help: { type: "boolean", short: "h" },
39
45
  version: { type: "boolean", short: "v" },
40
46
  },
@@ -50,9 +56,15 @@ async function main(argv) {
50
56
  await start({
51
57
  dir: resolve(values.dir ?? process.cwd()),
52
58
  url: values.url,
59
+ serve: values.serve === undefined ? undefined : resolve(values.serve),
53
60
  port: values.port,
54
61
  clientId: values["client-id"],
55
- }, { start: startStudio, untilStopped: untilSignal, print: console.log });
62
+ }, {
63
+ start: startStudio,
64
+ serve: serveStatic,
65
+ untilStopped: untilSignal,
66
+ print: console.log,
67
+ });
56
68
  return 0;
57
69
  }
58
70
  main(process.argv.slice(2)).then((code) => {
package/dist/serve.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * `--serve <dir>`: a plugin that's plain files, served as a host would, so the studio can embed it
3
+ * with no dev server (backlog 039). It listens on a port of its own, so the plugin has an origin
4
+ * of its own, as Livespace requires. Every response allows any origin, as a host serving
5
+ * `jwks.json` must: Livespace reads it from another origin, and so does the studio's page.
6
+ */
7
+ import { readFile, stat } from "node:fs/promises";
8
+ import { createServer } from "node:http";
9
+ import { extname, join, resolve, sep } from "node:path";
10
+ import { PortInUse } from "./server.js";
11
+ const TYPES = {
12
+ ".html": "text/html; charset=utf-8",
13
+ ".css": "text/css; charset=utf-8",
14
+ ".js": "text/javascript; charset=utf-8",
15
+ ".mjs": "text/javascript; charset=utf-8",
16
+ ".json": "application/json; charset=utf-8",
17
+ ".svg": "image/svg+xml",
18
+ ".png": "image/png",
19
+ ".jpg": "image/jpeg",
20
+ ".jpeg": "image/jpeg",
21
+ ".gif": "image/gif",
22
+ ".webp": "image/webp",
23
+ ".ico": "image/x-icon",
24
+ ".woff2": "font/woff2",
25
+ ".txt": "text/plain; charset=utf-8",
26
+ ".md": "text/markdown; charset=utf-8",
27
+ };
28
+ const isFile = (path) => stat(path).then((s) => s.isFile(), () => false);
29
+ /**
30
+ * The file a request path names under `root`, or undefined when there's none or it would leave
31
+ * `root`. A directory gives its `index.html`.
32
+ */
33
+ export async function fileUnder(root, pathname) {
34
+ let decoded;
35
+ try {
36
+ decoded = decodeURIComponent(pathname);
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ if (decoded.includes("\0")) {
42
+ return undefined;
43
+ }
44
+ const base = resolve(root);
45
+ const path = resolve(join(base, decoded));
46
+ if (path !== base && !path.startsWith(base + sep)) {
47
+ return undefined;
48
+ }
49
+ if (await isFile(path)) {
50
+ return path;
51
+ }
52
+ const index = join(path, "index.html");
53
+ return (await isFile(index)) ? index : undefined;
54
+ }
55
+ /** Serves `dir` at http://localhost:<port>, until closed. */
56
+ export async function serveStatic(options) {
57
+ const server = createServer(async (request, response) => {
58
+ const headers = {
59
+ "Access-Control-Allow-Origin": "*",
60
+ "Cache-Control": "no-store",
61
+ };
62
+ if (request.method === "OPTIONS") {
63
+ response
64
+ .writeHead(204, {
65
+ ...headers,
66
+ "Access-Control-Allow-Headers": "*",
67
+ "Access-Control-Allow-Methods": "GET, HEAD",
68
+ })
69
+ .end();
70
+ return;
71
+ }
72
+ if (request.method !== "GET" && request.method !== "HEAD") {
73
+ response.writeHead(405, headers).end();
74
+ return;
75
+ }
76
+ const { pathname } = new URL(request.url ?? "/", "http://localhost");
77
+ const file = await fileUnder(options.dir, pathname);
78
+ if (file === undefined) {
79
+ response.writeHead(404, headers).end();
80
+ return;
81
+ }
82
+ try {
83
+ const body = await readFile(file);
84
+ response
85
+ .writeHead(200, {
86
+ ...headers,
87
+ "Content-Type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream",
88
+ })
89
+ .end(request.method === "HEAD" ? undefined : body);
90
+ }
91
+ catch {
92
+ response.writeHead(404, headers).end();
93
+ }
94
+ });
95
+ await new Promise((resolve, reject) => {
96
+ server.once("error", (error) => {
97
+ reject(error.code === "EADDRINUSE" ? new PortInUse(options.port) : error);
98
+ });
99
+ server.listen(options.port, "localhost", () => resolve());
100
+ });
101
+ const address = server.address();
102
+ const port = typeof address === "object" && address !== null
103
+ ? address.port
104
+ : options.port;
105
+ return {
106
+ url: `http://localhost:${port}/`,
107
+ close: () => new Promise((resolve) => {
108
+ server.closeAllConnections();
109
+ server.close(() => resolve());
110
+ }),
111
+ };
112
+ }
package/dist/start.js CHANGED
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Starting the studio, a local stand-in for Livespace that embeds the plugin's page
3
3
  * (docs/adr/0007-studio-is-its-own-package.md). It embeds a page the author's own dev server
4
- * serves, and never starts one.
4
+ * serves, and never starts one. With `--serve`, a plugin that's plain files has no dev server, so
5
+ * the studio serves it, on the next port (docs/adr/0009-a-no-build-lane.md).
5
6
  */
6
- import { access } from "node:fs/promises";
7
- import { join } from "node:path";
7
+ import { access, stat } from "node:fs/promises";
8
+ import { join, relative } from "node:path";
8
9
  import { clientIdOf } from "./keys.js";
9
10
  import { readManifestText } from "./manifest.js";
10
11
  import { PortInUse } from "./server.js";
@@ -73,15 +74,44 @@ async function clientIdFor(options) {
73
74
  }
74
75
  return DEFAULT_CLIENT_ID;
75
76
  }
77
+ /** Serves `--serve`'s folder on the port after the studio's, or undefined without the flag. */
78
+ async function siteFor(options, port, deps) {
79
+ const folder = options.serve;
80
+ if (folder === undefined) {
81
+ return undefined;
82
+ }
83
+ if (options.url !== undefined) {
84
+ throw new UsageError("--serve and --url both say what to embed: give one of them.");
85
+ }
86
+ const isDir = await stat(folder).then((s) => s.isDirectory(), () => false);
87
+ if (!isDir) {
88
+ throw new UsageError(`--serve takes a folder, and ${folder} isn't one.`);
89
+ }
90
+ if (!(await exists(join(folder, "index.html")))) {
91
+ throw new UsageError(`--serve's folder has no index.html, the plugin's page: ${folder}`);
92
+ }
93
+ const sitePort = port === 65535 ? port - 1 : port + 1;
94
+ try {
95
+ return await deps.serve({ dir: folder, port: sitePort });
96
+ }
97
+ catch (error) {
98
+ if (error instanceof PortInUse) {
99
+ throw new UsageError(`Port ${sitePort}, where --serve serves the plugin, is in use. Move the studio with --port (the plugin takes the next port), or stop what's using it.`);
100
+ }
101
+ throw error;
102
+ }
103
+ }
76
104
  export async function start(options, deps) {
77
- const pluginUrl = await pluginUrlFor(options);
78
105
  const port = portFor(options);
106
+ const site = await siteFor(options, port, deps);
107
+ const pluginUrl = site?.url ?? (await pluginUrlFor(options));
79
108
  const clientId = await clientIdFor(options);
80
109
  let studio;
81
110
  try {
82
111
  studio = await deps.start({ port, pluginUrl, clientId, dir: options.dir });
83
112
  }
84
113
  catch (error) {
114
+ await site?.close();
85
115
  if (error instanceof PortInUse) {
86
116
  throw new UsageError(`Port ${port} is in use. Pick another with --port, or stop what's using it.`);
87
117
  }
@@ -89,9 +119,15 @@ export async function start(options, deps) {
89
119
  }
90
120
  const { print } = deps;
91
121
  print(`Plugin Studio: open ${studio.url}`);
92
- print(pluginUrl === null
93
- ? "Enter your plugin's address at the top of the page: any http or https page, a deployed one included."
94
- : `It embeds ${pluginUrl}; change the address at the top of the page. Start your dev server first, if it isn't running.`);
122
+ if (site !== undefined) {
123
+ const shown = relative(process.cwd(), options.serve ?? "") || ".";
124
+ print(`It serves ${shown} at ${site.url} and embeds it. After you change a file, reload the studio's page.`);
125
+ }
126
+ else {
127
+ print(pluginUrl === null
128
+ ? "Enter your plugin's address at the top of the page: any http or https page, a deployed one included."
129
+ : `It embeds ${pluginUrl}; change the address at the top of the page. Start your dev server first, if it isn't running.`);
130
+ }
95
131
  const env = {
96
132
  LIVESPACE_KEYS_URL: studio.keysUrl,
97
133
  LIVESPACE_AUTH_URL: studio.authUrl,
@@ -104,5 +140,6 @@ export async function start(options, deps) {
104
140
  print("Ctrl-C to stop.");
105
141
  await deps.untilStopped();
106
142
  await studio.close();
143
+ await site?.close();
107
144
  print("Stopped.");
108
145
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livespace/plugin-studio",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-beta.1",
4
4
  "description": "Plugin Studio: try and debug a Livespace plugin locally, embedded as Livespace embeds it.",
5
5
  "author": "LS FE team",
6
6
  "license": "MIT",