@skoor/create-custom-widget 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT No Attribution
2
+
3
+ Copyright (c) 2026 SKOOR GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
6
+ software and associated documentation files (the "Software"), to deal in the Software
7
+ without restriction, including without limitation the rights to use, copy, modify,
8
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
12
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
13
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
14
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
15
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
16
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # @skoor/create-custom-widget
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Creates a new custom widget project for the SKOOR dashboard.
4
+
5
+ ```shell
6
+ npm create @skoor/custom-widget@latest
7
+ ```
8
+
9
+ The command asks for the package name, which uses the scope assigned to your organisation (for example `@acme/my-widget`), the target directory, and optionally your SKOOR instance for the MCP configuration.
10
+
11
+ Non-interactive:
12
+
13
+ ```shell
14
+ npm create @skoor/custom-widget@latest my-widget -- --yes --name @acme/my-widget --instance skoor.example.com
15
+ ```
16
+
17
+ ## What you get
18
+
19
+ - Vite project with a minimal widget that uses [`@skoor/dashboard-bridge`](https://registry.skoor.com) for host theme, filters and time interval
20
+ - `.npmrc` for the SKOOR registry and `publishConfig` that publishes only to `https://registry.skoor.com`
21
+ - `.vscode/mcp.json` and `.mcp.json` for the SKOOR MCP server, without credentials
22
+ - `AGENTS.md` with the SKOOR rules for coding agents, plus `CLAUDE.md` that imports it
23
+
24
+ Then:
25
+
26
+ ```shell
27
+ cd my-widget
28
+ npm login --registry=https://registry.skoor.com # once per machine
29
+ npm install
30
+ npm run dev
31
+ ```
32
+
33
+ The full development workflow is in the README of `@skoor/dashboard-bridge`, section "Widget development workflow".
34
+
35
+ ## MCP server credentials
36
+
37
+ The SKOOR MCP server expects an `Authorization` header with Basic auth. Generate it instead of base64-encoding it by hand:
38
+
39
+ ```shell
40
+ npx @skoor/create-custom-widget@latest mcp-auth [--user <name>]
41
+ ```
42
+
43
+ The password is always asked for with hidden input and never stored or accepted as an argument. The command prints the value for the VS Code prompt and the `SKOOR_MCP_AUTHORIZATION` export for Claude Code (PowerShell syntax on Windows).
44
+
45
+ ## Updating AGENTS.md in existing projects
46
+
47
+ The rules in `AGENTS.md` sit between `<!-- skoor:managed vN -->` and `<!-- /skoor:managed -->`. Update them in place:
48
+
49
+ ```shell
50
+ npx @skoor/create-custom-widget@latest update-agents [directory]
51
+ ```
52
+
53
+ - Uses the newest block from the installed `@skoor/dashboard-bridge` README or from this package
54
+ - Changes only the content between the markers and never lowers the version
55
+ - `--check` reports whether an update is available (exit code 1), for example in CI
56
+ - `--force` inserts the block at the top of an `AGENTS.md` that has no markers
57
+
58
+ Coding agents do the same on their own: the bridge README tells them to replace an outdated block.
59
+
60
+ ## Maintainers
61
+
62
+ - The managed block exists twice: in `template/AGENTS.md` and in the bridge README ("Keeping the project's AGENTS.md up to date"). Change both together and increase `vN` in both.
63
+ - Only placeholders belong in `template/`: no instance URLs, credentials or customer data. The package is public.
64
+ - `npm test` runs the tests. `npm publish` goes to npmjs.org because of `publishConfig`; publishing requires 2FA on the `skoor` npm organisation.
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { stdin, stdout } from "node:process";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { parseArgs } from "node:util";
7
+
8
+ import { basicAuthorization, exportCommand, readHidden, validateUser } from "../lib/auth.js";
9
+ import { pickLatest, planUpdate } from "../lib/managed-block.js";
10
+ import {
11
+ DEFAULT_MCP_URL,
12
+ TEMPLATE_DIR,
13
+ isEmptyDir,
14
+ scaffold,
15
+ toMcpUrl,
16
+ validateMcpUrl,
17
+ validatePackageName,
18
+ } from "../lib/scaffold.js";
19
+
20
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
21
+
22
+ const HELP = `Usage:
23
+ npm create @skoor/custom-widget@latest [directory] -- [options]
24
+ npx @skoor/create-custom-widget@latest update-agents [directory] [options]
25
+ npx @skoor/create-custom-widget@latest mcp-auth [options]
26
+
27
+ Create a widget project:
28
+ --name <@scope/name> package name, using the scope assigned to you
29
+ --instance <url> SKOOR instance for the MCP config (optional)
30
+ -y, --yes do not prompt; requires --name
31
+ --force allow a non-empty target directory
32
+
33
+ Update the managed rules block in AGENTS.md (update-agents):
34
+ --check only report; exit code 1 if an update is available
35
+ --force insert the block if AGENTS.md has no markers
36
+
37
+ Print the Authorization header for the SKOOR MCP server (mcp-auth):
38
+ --user <name> SKOOR username (otherwise prompted)
39
+ The password is always prompted, hidden, and never stored.
40
+
41
+ -h, --help show this help
42
+ -v, --version show the version
43
+ `;
44
+
45
+ class UsageError extends Error {}
46
+
47
+ const readText = async (file) => {
48
+ try {
49
+ return await readFile(file, "utf8");
50
+ } catch (error) {
51
+ if (error.code === "ENOENT") return null;
52
+ throw error;
53
+ }
54
+ };
55
+
56
+ async function updateAgents(dir, { check, force }) {
57
+ const agentsPath = path.join(dir, "AGENTS.md");
58
+ const templateFile = await readFile(path.join(TEMPLATE_DIR, "AGENTS.md"), "utf8");
59
+ const bridgeReadme = path.join(dir, "node_modules", "@skoor", "dashboard-bridge", "README.md");
60
+
61
+ // The bridge README is authoritative; this package's template is the fallback.
62
+ const latest = pickLatest([
63
+ { origin: "installed @skoor/dashboard-bridge README", text: await readText(bridgeReadme) },
64
+ { origin: `${pkg.name}@${pkg.version}`, text: templateFile },
65
+ ]);
66
+ if (!latest) throw new Error("No managed block found in the available sources.");
67
+
68
+ const result = planUpdate(await readText(agentsPath), templateFile, latest, { force });
69
+
70
+ switch (result.status) {
71
+ case "up-to-date":
72
+ console.log(`AGENTS.md is up to date (managed block v${result.from}).`);
73
+ return 0;
74
+ case "no-markers":
75
+ console.error(
76
+ "AGENTS.md has no <!-- skoor:managed --> markers.\n" +
77
+ `Run again with --force to insert the v${result.to} block at the top; the existing content is kept below it.`,
78
+ );
79
+ return 1;
80
+ }
81
+
82
+ const description = {
83
+ created: `Create AGENTS.md with managed block v${result.to}`,
84
+ inserted: `Insert managed block v${result.to} at the top of AGENTS.md`,
85
+ updated: `Update managed block in AGENTS.md: v${result.from} -> v${result.to}`,
86
+ }[result.status];
87
+
88
+ if (check) {
89
+ console.log(`${description} (source: ${latest.origin}).`);
90
+ return 1;
91
+ }
92
+ await writeFile(agentsPath, result.content);
93
+ console.log(`${description} (source: ${latest.origin}). Content outside the markers is unchanged.`);
94
+ return 0;
95
+ }
96
+
97
+ async function ask(rl, question, { defaultValue, validate }) {
98
+ for (;;) {
99
+ const suffix = defaultValue ? ` (${defaultValue})` : "";
100
+ const answer = (await rl.question(`${question}${suffix}: `)).trim() || defaultValue || "";
101
+ const error = validate?.(answer);
102
+ if (!error) return answer;
103
+ console.error(` ${error}`);
104
+ }
105
+ }
106
+
107
+ async function mcpAuth({ user }) {
108
+ if (!stdin.isTTY) throw new UsageError("mcp-auth needs an interactive terminal to ask for the password.");
109
+ if (user) {
110
+ const error = validateUser(user);
111
+ if (error) throw new UsageError(`--user: ${error}`);
112
+ } else {
113
+ const rl = createInterface({ input: stdin, output: stdout });
114
+ try {
115
+ user = await ask(rl, "SKOOR username", { validate: validateUser });
116
+ } finally {
117
+ rl.close();
118
+ }
119
+ }
120
+
121
+ const password = await readHidden("SKOOR password (hidden): ");
122
+ const value = basicAuthorization(user, password);
123
+
124
+ console.log("\nAuthorization header for the SKOOR MCP server. Treat it like the password.\n");
125
+ console.log("VS Code (paste when .vscode/mcp.json asks for it):");
126
+ console.log(` ${value}\n`);
127
+ console.log("Claude Code (run in the shell you start claude from, or add to your shell profile):");
128
+ console.log(` ${exportCommand(value)}`);
129
+ return 0;
130
+ }
131
+
132
+ async function create(positional, { name, instance, yes, force }) {
133
+ const interactive = !yes && stdin.isTTY;
134
+ if (!interactive && !name) throw new UsageError("--name is required when not prompting.");
135
+
136
+ let dir = positional;
137
+ let packageName = name;
138
+ let mcpUrl = instance ? toMcpUrl(instance) : undefined;
139
+
140
+ if (packageName) {
141
+ const error = validatePackageName(packageName);
142
+ if (error) throw new UsageError(error);
143
+ }
144
+ if (mcpUrl) {
145
+ const error = validateMcpUrl(mcpUrl);
146
+ if (error) throw new UsageError(`--instance: ${error}`);
147
+ }
148
+
149
+ if (interactive) {
150
+ const rl = createInterface({ input: stdin, output: stdout });
151
+ try {
152
+ packageName ??= await ask(rl, "Package name, with the scope assigned to you (e.g. @acme/my-widget)", {
153
+ validate: validatePackageName,
154
+ });
155
+ dir ??= await ask(rl, "Directory", { defaultValue: packageName.split("/")[1] });
156
+ if (!instance) {
157
+ const answer = await ask(rl, "SKOOR instance for the MCP server, e.g. skoor.example.com (empty = fill in later)", {
158
+ validate: (value) => (value ? validateMcpUrl(toMcpUrl(value)) : null),
159
+ });
160
+ mcpUrl = answer ? toMcpUrl(answer) : undefined;
161
+ }
162
+ } finally {
163
+ rl.close();
164
+ }
165
+ }
166
+
167
+ dir ??= packageName.split("/")[1];
168
+ const target = path.resolve(dir);
169
+ if (!force && !(await isEmptyDir(target))) {
170
+ throw new UsageError(`${target} is not empty. Choose another directory or use --force.`);
171
+ }
172
+
173
+ await scaffold(target, { packageName, mcpUrl: mcpUrl ?? DEFAULT_MCP_URL });
174
+
175
+ const cd = path.relative(process.cwd(), target) || ".";
176
+ console.log(`\nCreated ${packageName} in ${target}\n`);
177
+ console.log("Next steps:");
178
+ if (cd !== ".") console.log(` cd ${cd}`);
179
+ console.log(" npm login --registry=https://registry.skoor.com # once per machine");
180
+ console.log(" npm install");
181
+ console.log(" npm run dev");
182
+ console.log("\nFor the SKOOR MCP server, generate the Authorization header with:");
183
+ console.log(" npx @skoor/create-custom-widget@latest mcp-auth");
184
+ if (!mcpUrl) console.log("\nSet your SKOOR instance URL in .vscode/mcp.json and .mcp.json.");
185
+ console.log("\nRead AGENTS.md and node_modules/@skoor/dashboard-bridge/README.md before you start.");
186
+ return 0;
187
+ }
188
+
189
+ async function main(argv) {
190
+ const { values, positionals } = parseArgs({
191
+ args: argv,
192
+ allowPositionals: true,
193
+ options: {
194
+ name: { type: "string" },
195
+ instance: { type: "string" },
196
+ user: { type: "string" },
197
+ yes: { type: "boolean", short: "y" },
198
+ force: { type: "boolean" },
199
+ check: { type: "boolean" },
200
+ help: { type: "boolean", short: "h" },
201
+ version: { type: "boolean", short: "v" },
202
+ },
203
+ });
204
+
205
+ if (values.help) {
206
+ console.log(HELP);
207
+ return 0;
208
+ }
209
+ if (values.version) {
210
+ console.log(pkg.version);
211
+ return 0;
212
+ }
213
+
214
+ if (positionals[0] === "update-agents") {
215
+ if (positionals.length > 2) throw new UsageError("update-agents takes at most one directory.");
216
+ return updateAgents(path.resolve(positionals[1] ?? "."), values);
217
+ }
218
+ if (positionals[0] === "mcp-auth") {
219
+ if (positionals.length > 1) throw new UsageError("mcp-auth takes no arguments.");
220
+ return mcpAuth(values);
221
+ }
222
+ if (positionals.length > 1) throw new UsageError("Expected at most one directory.");
223
+ return create(positionals[0], values);
224
+ }
225
+
226
+ try {
227
+ process.exitCode = await main(process.argv.slice(2));
228
+ } catch (error) {
229
+ if (error.code === "ABORT") {
230
+ console.error(error.message);
231
+ process.exitCode = 130;
232
+ } else if (error instanceof UsageError || error.code?.startsWith?.("ERR_PARSE_ARGS")) {
233
+ console.error(`${error.message}\n\n${HELP}`);
234
+ process.exitCode = 2;
235
+ } else {
236
+ console.error(error.message);
237
+ process.exitCode = 1;
238
+ }
239
+ }
package/lib/auth.js ADDED
@@ -0,0 +1,59 @@
1
+ // Builds the Authorization header for the SKOOR MCP server (HTTP Basic, RFC 7617).
2
+
3
+ /** Returns an error message, or null if `user` can be used for Basic auth. */
4
+ export function validateUser(user) {
5
+ if (!user) return "A username is required.";
6
+ if (user.includes(":")) return "The username must not contain ':'.";
7
+ return null;
8
+ }
9
+
10
+ /** "user", "pass" -> "Basic dXNlcjpwYXNz" */
11
+ export function basicAuthorization(user, password) {
12
+ const error = validateUser(user);
13
+ if (error) throw new Error(error);
14
+ return `Basic ${Buffer.from(`${user}:${password}`, "utf8").toString("base64")}`;
15
+ }
16
+
17
+ /** Shell command that sets the variable `.mcp.json` reads, for the current platform. */
18
+ export function exportCommand(value, platform = process.platform) {
19
+ return platform === "win32"
20
+ ? `$env:SKOOR_MCP_AUTHORIZATION = '${value}'`
21
+ : `export SKOOR_MCP_AUTHORIZATION='${value}'`;
22
+ }
23
+
24
+ // Bracketed-paste markers that some terminals wrap around pasted text.
25
+ const PASTE_MARKERS = /\x1b\[20[01]~/g;
26
+
27
+ /**
28
+ * Reads a line from a TTY without echoing it.
29
+ * Rejects with `{ code: "ABORT" }` on Ctrl+C.
30
+ */
31
+ export function readHidden(prompt, { input = process.stdin, output = process.stdout } = {}) {
32
+ return new Promise((resolve, reject) => {
33
+ let value = "";
34
+ output.write(prompt);
35
+ input.setRawMode(true);
36
+ input.setEncoding("utf8");
37
+ input.resume();
38
+
39
+ const finish = (error) => {
40
+ input.off("data", onData);
41
+ input.setRawMode(false);
42
+ input.pause();
43
+ output.write("\n");
44
+ if (error) reject(error);
45
+ else resolve(value);
46
+ };
47
+
48
+ const onData = (chunk) => {
49
+ for (const char of chunk.replace(PASTE_MARKERS, "")) {
50
+ if (char === "\r" || char === "\n" || char === "\u0004") return finish();
51
+ if (char === "\u0003") return finish(Object.assign(new Error("Cancelled."), { code: "ABORT" }));
52
+ if (char === "\u007f" || char === "\b") value = [...value].slice(0, -1).join("");
53
+ else if (char >= " ") value += char;
54
+ }
55
+ };
56
+
57
+ input.on("data", onData);
58
+ });
59
+ }
@@ -0,0 +1,75 @@
1
+ // Helpers for the managed rules block in a widget project's AGENTS.md:
2
+ //
3
+ // <!-- skoor:managed v1 -->
4
+ // ...rules...
5
+ // <!-- /skoor:managed -->
6
+ //
7
+ // Everything outside the markers belongs to the project and is never touched.
8
+
9
+ const BLOCK_RE = /<!-- skoor:managed v(\d+) -->[\s\S]*?<!-- \/skoor:managed -->/;
10
+
11
+ /**
12
+ * Finds the first managed block in `text`.
13
+ * @returns {{ version: number, block: string, index: number } | null}
14
+ */
15
+ export function findManagedBlock(text) {
16
+ const match = BLOCK_RE.exec(text);
17
+ if (!match) return null;
18
+ return { version: Number(match[1]), block: match[0], index: match.index };
19
+ }
20
+
21
+ /** Replaces the first managed block in `text` with `block`. */
22
+ export function replaceManagedBlock(text, block) {
23
+ const found = findManagedBlock(text);
24
+ if (!found) throw new Error("No managed block found");
25
+ return text.slice(0, found.index) + block + text.slice(found.index + found.block.length);
26
+ }
27
+
28
+ /**
29
+ * Computes the new AGENTS.md content.
30
+ * @param {string | null} current existing AGENTS.md content, or null if missing
31
+ * @param {string} templateFile full template AGENTS.md (used when the file is missing)
32
+ * @param {{ version: number, block: string }} latest newest available block
33
+ * @param {{ force?: boolean }} options
34
+ * @returns {{ status: "created" | "updated" | "inserted" | "up-to-date" | "no-markers", from?: number, to: number, content?: string }}
35
+ */
36
+ export function planUpdate(current, templateFile, latest, { force = false } = {}) {
37
+ if (current === null) {
38
+ const content = findManagedBlock(templateFile)
39
+ ? replaceManagedBlock(templateFile, latest.block)
40
+ : templateFile;
41
+ return { status: "created", to: latest.version, content };
42
+ }
43
+
44
+ const existing = findManagedBlock(current);
45
+ if (!existing) {
46
+ if (!force) return { status: "no-markers", to: latest.version };
47
+ const rest = current.replace(/^\s+/, "");
48
+ const content = `${latest.block}\n\n${rest}`;
49
+ return { status: "inserted", to: latest.version, content };
50
+ }
51
+
52
+ if (existing.version >= latest.version) {
53
+ return { status: "up-to-date", from: existing.version, to: existing.version };
54
+ }
55
+
56
+ return {
57
+ status: "updated",
58
+ from: existing.version,
59
+ to: latest.version,
60
+ content: replaceManagedBlock(current, latest.block),
61
+ };
62
+ }
63
+
64
+ /** Picks the source with the highest block version; earlier sources win ties. */
65
+ export function pickLatest(sources) {
66
+ let best = null;
67
+ for (const source of sources) {
68
+ if (!source.text) continue;
69
+ const found = findManagedBlock(source.text);
70
+ if (found && (!best || found.version > best.version)) {
71
+ best = { ...found, origin: source.origin };
72
+ }
73
+ }
74
+ return best;
75
+ }
@@ -0,0 +1,104 @@
1
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ export const TEMPLATE_DIR = fileURLToPath(new URL("../template/", import.meta.url));
6
+
7
+ export const DEFAULT_MCP_URL = "https://<your-skoor-instance>/skoor-webservice/mcp";
8
+
9
+ // npm strips these from published tarballs, so the template stores them under another name.
10
+ const RENAMES = { _gitignore: ".gitignore", _npmrc: ".npmrc" };
11
+
12
+ const TEXT_EXTENSIONS = new Set([".js", ".json", ".md", ".html", ".css", ".txt", ""]);
13
+
14
+ const NAME_RE = /^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/;
15
+
16
+ /** Returns an error message, or null if `name` is a valid scoped package name. */
17
+ export function validatePackageName(name) {
18
+ if (!name) return "A package name is required.";
19
+ if (name.length > 214) return "The package name is too long (max. 214 characters).";
20
+ if (!NAME_RE.test(name)) {
21
+ return "Use a scoped, lower-case package name with the scope assigned to you, e.g. @acme/my-widget.";
22
+ }
23
+ if (name.startsWith("@skoor/")) {
24
+ return "The @skoor scope is reserved for SKOOR packages. Use the scope assigned to your organisation.";
25
+ }
26
+ return null;
27
+ }
28
+
29
+ /** Returns an error message, or null if `url` is a usable http(s) URL. */
30
+ export function validateMcpUrl(url) {
31
+ try {
32
+ const parsed = new URL(url);
33
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return "Use an http(s) URL.";
34
+ if (parsed.username || parsed.password) return "Do not put credentials into the URL.";
35
+ return null;
36
+ } catch {
37
+ return "Not a valid URL.";
38
+ }
39
+ }
40
+
41
+ /** Builds the MCP endpoint from a bare instance URL or a full endpoint URL. */
42
+ export function toMcpUrl(input) {
43
+ const trimmed = input.trim().replace(/\/+$/, "");
44
+ if (/\/mcp$/.test(trimmed)) return trimmed;
45
+ const withProtocol = /^[a-z]+:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
46
+ return `${withProtocol}/skoor-webservice/mcp`;
47
+ }
48
+
49
+ /** "@acme/sales-overview" -> "Sales Overview" */
50
+ export function titleFromName(name) {
51
+ const base = name.split("/").pop() ?? name;
52
+ return base
53
+ .split(/[-_.]+/)
54
+ .filter(Boolean)
55
+ .map((part) => part[0].toUpperCase() + part.slice(1))
56
+ .join(" ");
57
+ }
58
+
59
+ export async function isEmptyDir(dir) {
60
+ try {
61
+ const entries = await readdir(dir);
62
+ return entries.filter((entry) => entry !== ".git").length === 0;
63
+ } catch (error) {
64
+ if (error.code === "ENOENT") return true;
65
+ throw error;
66
+ }
67
+ }
68
+
69
+ function substitute(text, values) {
70
+ return text.replace(/\{\{([A-Z_]+)\}\}/g, (token, key) =>
71
+ Object.hasOwn(values, key) ? values[key] : token,
72
+ );
73
+ }
74
+
75
+ /** Copies the template into `targetDir`, renaming dotfiles and filling in placeholders. */
76
+ export async function scaffold(targetDir, { packageName, mcpUrl }) {
77
+ const values = {
78
+ PACKAGE_NAME: packageName,
79
+ WIDGET_TITLE: titleFromName(packageName),
80
+ MCP_URL: mcpUrl,
81
+ };
82
+ const written = [];
83
+
84
+ const copyDir = async (from, to) => {
85
+ await mkdir(to, { recursive: true });
86
+ for (const entry of await readdir(from)) {
87
+ const source = path.join(from, entry);
88
+ const destination = path.join(to, RENAMES[entry] ?? entry);
89
+ if ((await stat(source)).isDirectory()) {
90
+ await copyDir(source, destination);
91
+ continue;
92
+ }
93
+ const content = await readFile(source);
94
+ const output = TEXT_EXTENSIONS.has(path.extname(entry))
95
+ ? substitute(content.toString("utf8"), values)
96
+ : content;
97
+ await writeFile(destination, output);
98
+ written.push(path.relative(targetDir, destination));
99
+ }
100
+ };
101
+
102
+ await copyDir(TEMPLATE_DIR, targetDir);
103
+ return written.sort();
104
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@skoor/create-custom-widget",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Scaffold a SKOOR dashboard custom widget: npm create @skoor/custom-widget",
5
+ "type": "module",
6
+ "bin": {
7
+ "create-custom-widget": "bin/create-custom-widget.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "template"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.17"
16
+ },
17
+ "scripts": {
18
+ "test": "node --test",
19
+ "check:pack": "npm pack --dry-run"
20
+ },
21
+ "keywords": [
22
+ "skoor",
23
+ "dashboard",
24
+ "widget",
25
+ "create",
26
+ "scaffold"
27
+ ],
28
+ "author": "SKOOR GmbH",
29
+ "license": "MIT-0",
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "registry": "https://registry.npmjs.org"
33
+ }
34
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "mcpServers": {
3
+ "skoor-mcp": {
4
+ "type": "http",
5
+ "url": "{{MCP_URL}}",
6
+ "headers": {
7
+ "Authorization": "${SKOOR_MCP_AUTHORIZATION}"
8
+ }
9
+ }
10
+ }
11
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "servers": {
3
+ "skoor-mcp": {
4
+ "type": "http",
5
+ "url": "{{MCP_URL}}",
6
+ "headers": {
7
+ "Authorization": "${input:skoor-mcp-authorization}"
8
+ }
9
+ }
10
+ },
11
+ "inputs": [
12
+ {
13
+ "type": "promptString",
14
+ "id": "skoor-mcp-authorization",
15
+ "description": "Authorization header for the SKOOR MCP server. Generate it with: npx @skoor/create-custom-widget@latest mcp-auth",
16
+ "password": true
17
+ }
18
+ ]
19
+ }
@@ -0,0 +1,18 @@
1
+ # AGENTS.md
2
+
3
+ <!-- skoor:managed v2 -->
4
+ ## SKOOR widget rules
5
+
6
+ This project is a SKOOR dashboard custom widget.
7
+
8
+ - Before starting work, building a release or publishing, run `npm install @skoor/dashboard-bridge@latest`.
9
+ - Then read `node_modules/@skoor/dashboard-bridge/README.md`, especially "Widget development workflow", before implementing anything. It is the authoritative guide. If it disagrees with this file, the README applies, including its instructions for updating this block.
10
+ - Communicate with SKOOR only through `@skoor/dashboard-bridge`. Never call SKOOR backend APIs directly from the widget.
11
+ - Never commit credentials, tokens or API keys, also not in `.vscode/mcp.json` or `.mcp.json`.
12
+ - If the SKOOR MCP server is not connected or rejects requests with 401, ask the user to run `npx @skoor/create-custom-widget@latest mcp-auth` in their own terminal and follow its output. Never ask for the SKOOR username or password in the chat, never run `mcp-auth` yourself, and never write the `Authorization` value into a file.
13
+ - Never hand-edit `data/data-queries.json`. Regenerate it with the MCP export tool.
14
+ <!-- /skoor:managed -->
15
+
16
+ ## Project-specific notes
17
+
18
+ <!-- Notes about this widget go here. Updates of the managed block above never change this section. -->
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,46 @@
1
+ # {{WIDGET_TITLE}}
2
+
3
+ SKOOR dashboard custom widget `{{PACKAGE_NAME}}`.
4
+
5
+ ## Getting started
6
+
7
+ ```shell
8
+ npm login --registry=https://registry.skoor.com # once per machine
9
+ npm install
10
+ npm run dev
11
+ ```
12
+
13
+ The widget needs a SKOOR dashboard as its host. In a plain browser it only shows a "not connected" message.
14
+
15
+ ## Development
16
+
17
+ Read `AGENTS.md` and the "Widget development workflow" section in `node_modules/@skoor/dashboard-bridge/README.md`. The README describes the MCP setup, the data query workflow, CSP and publishing.
18
+
19
+ - `npm run dev`: start the Vite dev server
20
+ - `npm run build`: build into `dist/`
21
+ - `npm publish`: build and publish to `https://registry.skoor.com`
22
+
23
+ ## MCP server
24
+
25
+ `.vscode/mcp.json` (VS Code) and `.mcp.json` (Claude Code) point to the SKOOR MCP server. Neither file contains credentials. Both need an `Authorization` header, which you generate with:
26
+
27
+ ```shell
28
+ npx @skoor/create-custom-widget@latest mcp-auth
29
+ ```
30
+
31
+ It asks for your SKOOR username and password (hidden), stores nothing and prints:
32
+
33
+ - the value to paste when VS Code asks for the `Authorization` header
34
+ - an `export SKOOR_MCP_AUTHORIZATION=...` command for Claude Code. Run it in the shell you start `claude` from, or add it to your shell profile.
35
+
36
+ The value contains your password in reversible form. Do not commit it or put it into project files.
37
+
38
+ ## Updating AGENTS.md
39
+
40
+ The rules between the `skoor:managed` markers in `AGENTS.md` are maintained by SKOOR. Update them with:
41
+
42
+ ```shell
43
+ npx @skoor/create-custom-widget@latest update-agents
44
+ ```
45
+
46
+ Content outside the markers, such as "Project-specific notes", stays unchanged.
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ *.tgz
4
+ *.log
5
+ .env
6
+ .env.*
7
+ .DS_Store
@@ -0,0 +1 @@
1
+ registry=https://registry.skoor.com
@@ -0,0 +1,81 @@
1
+ import {
2
+ getFilters,
3
+ getHostContext,
4
+ getTimeInterval,
5
+ onFiltersChanged,
6
+ onHostContextChanged,
7
+ onTimeIntervalChanged,
8
+ setup,
9
+ } from "@skoor/dashboard-bridge";
10
+
11
+ // See node_modules/@skoor/dashboard-bridge/README.md for the full API,
12
+ // e.g. dataQuerySelect({ dataQueryName: "my-query", ... }) to load data.
13
+
14
+ const statusEl = document.getElementById("status");
15
+ const contextEl = document.getElementById("context");
16
+
17
+ const state = { hostContext: null, filters: {}, timeInterval: null };
18
+
19
+ const render = () => {
20
+ const rows = [
21
+ ["Theme", state.hostContext?.theme ?? "–"],
22
+ ["Language", state.hostContext?.language ?? "–"],
23
+ ["Time interval", state.timeInterval ? `${state.timeInterval.begin} – ${state.timeInterval.end}` : "–"],
24
+ ["Filters", Object.keys(state.filters ?? {}).length ? JSON.stringify(state.filters) : "none"],
25
+ ];
26
+
27
+ // textContent instead of innerHTML: never insert unescaped data into HTML.
28
+ contextEl.replaceChildren(
29
+ ...rows.flatMap(([label, value]) => {
30
+ const dt = document.createElement("dt");
31
+ const dd = document.createElement("dd");
32
+ dt.textContent = label;
33
+ dd.textContent = value;
34
+ return [dt, dd];
35
+ }),
36
+ );
37
+ };
38
+
39
+ const showError = (message, error) => {
40
+ console.error(message, error);
41
+ statusEl.textContent = message;
42
+ statusEl.classList.add("widget__status--error");
43
+ };
44
+
45
+ const init = async () => {
46
+ try {
47
+ // Applies host theme, colors, font and language, and reports the content height.
48
+ const cleanup = await setup();
49
+ window.addEventListener("pagehide", cleanup, { once: true });
50
+ } catch (error) {
51
+ showError("Not connected to a SKOOR dashboard. Open the widget inside a dashboard.", error);
52
+ return;
53
+ }
54
+
55
+ try {
56
+ [state.hostContext, state.filters, state.timeInterval] = await Promise.all([
57
+ getHostContext(),
58
+ getFilters(),
59
+ getTimeInterval(),
60
+ ]);
61
+ statusEl.textContent = "Connected to the dashboard.";
62
+ render();
63
+ } catch (error) {
64
+ showError("Failed to read the dashboard state.", error);
65
+ }
66
+
67
+ onHostContextChanged((hostContext) => {
68
+ state.hostContext = hostContext;
69
+ render();
70
+ });
71
+ onFiltersChanged((filters) => {
72
+ state.filters = filters;
73
+ render();
74
+ });
75
+ onTimeIntervalChanged((timeInterval) => {
76
+ state.timeInterval = timeInterval;
77
+ render();
78
+ });
79
+ };
80
+
81
+ void init();
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>{{WIDGET_TITLE}}</title>
7
+ <link rel="stylesheet" href="./styles.css" />
8
+ </head>
9
+ <body>
10
+ <main class="widget">
11
+ <h1 class="widget__title">{{WIDGET_TITLE}}</h1>
12
+ <p id="status" class="widget__status">Loading…</p>
13
+ <dl id="context" class="widget__context"></dl>
14
+ </main>
15
+ <script type="module" src="./app.js"></script>
16
+ </body>
17
+ </html>
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "{{PACKAGE_NAME}}",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "files": [
6
+ "dist",
7
+ "data"
8
+ ],
9
+ "main": "dist/index.html",
10
+ "scripts": {
11
+ "dev": "vite",
12
+ "build": "vite build --base=./",
13
+ "prepublishOnly": "npm run build"
14
+ },
15
+ "dependencies": {
16
+ "@skoor/dashboard-bridge": "latest"
17
+ },
18
+ "devDependencies": {
19
+ "vite": "^5.4.0"
20
+ },
21
+ "publishConfig": {
22
+ "registry": "https://registry.skoor.com"
23
+ }
24
+ }
@@ -0,0 +1,48 @@
1
+ /* Colors and font come from the dashboard via setup() (--host-* variables). */
2
+ * {
3
+ box-sizing: border-box;
4
+ }
5
+
6
+ body {
7
+ margin: 0;
8
+ }
9
+
10
+ .widget {
11
+ padding: 16px;
12
+ }
13
+
14
+ .widget__title {
15
+ margin: 0 0 8px;
16
+ font-size: 1.25rem;
17
+ font-weight: 600;
18
+ color: var(--host-accent-1, currentColor);
19
+ }
20
+
21
+ .widget__status {
22
+ margin: 0 0 12px;
23
+ color: var(--host-text-dim, inherit);
24
+ }
25
+
26
+ .widget__status--error {
27
+ color: var(--host-major, #c00);
28
+ }
29
+
30
+ .widget__context {
31
+ display: grid;
32
+ grid-template-columns: max-content 1fr;
33
+ gap: 4px 12px;
34
+ margin: 0;
35
+ padding: 12px;
36
+ border: 1px solid var(--host-line, currentColor);
37
+ border-radius: 4px;
38
+ background: var(--host-area, transparent);
39
+ }
40
+
41
+ .widget__context dt {
42
+ color: var(--host-text-dim, inherit);
43
+ }
44
+
45
+ .widget__context dd {
46
+ margin: 0;
47
+ overflow-wrap: anywhere;
48
+ }