@b-apm/integration-claude 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sdju
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @b-apm/integration-claude
2
+
3
+ > **UNSTABLE:** Early public release. APIs and on-disk layouts may change without a major bump. Not production-ready.
4
+
5
+ Claude Code **runtime** host for bapm, plus Anthropic **marketplace pack** mapper in the same package.
6
+
7
+ ## Dual surface
8
+
9
+ | Capability | Export | When |
10
+ | ------------------------- | ------------------------------------------------------- | ------------------------------------ |
11
+ | Runtime install / compile | `createClaudeIntegration` / `createIntegration` | `targets.claude` / `--target claude` |
12
+ | Marketplace pack | `claudeMarketplaceIntegration` / `mapClaudeMarketplace` | `bapm pack --marketplace claude` |
13
+
14
+ Marketplace mapping stays available without activating the runtime factory.
15
+
16
+ ## Detection vs forced target
17
+
18
+ | Mode | When active | Creates roots? |
19
+ | ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------------------- |
20
+ | **Auto-detect** | `.claude/` **directory** **or** project-root `CLAUDE.md` | Only when materialize / configureMcp runs after a positive detect |
21
+ | **Forced** (`--target claude`) | Explicit forced target id, even if detect is false | MAY `mkdir` `.claude/` as needed |
22
+
23
+ Auto-detect without force MUST NOT create `.claude/` solely for MCP opt-in.
24
+
25
+ ## Deploy roots
26
+
27
+ - `.claude` — skills, rules, agents, commands, hooks settings/scripts, ownership sidecar
28
+ - `.` — project `.mcp.json` and compile `CLAUDE.md` only (basename allowlist in writers)
29
+
30
+ ## Materialize routing
31
+
32
+ | Primitive type | Destination |
33
+ | -------------- | ------------------------------------------------------------------------------------------ |
34
+ | skill | `.claude/skills/<name>/SKILL.md` (never `.agents/skills/`) |
35
+ | instruction | `.claude/rules/<name>.md` (`applyTo` → `paths:`) |
36
+ | agent | `.claude/agents/<name>.md` |
37
+ | command | `.claude/commands/<name>.md` (shared frontmatter subset) |
38
+ | hook | merge `.claude/settings.json` + scripts under `.claude/hooks/` + `.claude/bapm-hooks.json` |
39
+
40
+ MCP is **not** written by materialize — only via `configureMcp` → project `.mcp.json` when `.claude/` exists.
41
+
42
+ ## Compile
43
+
44
+ `compile` defaults to `CLAUDE.md`, omits instruction primitives (they live under `.claude/rules/`), and honors `write` for preview vs durable emit.
45
+
46
+ ## Dependencies
47
+
48
+ Depends only on `@b-apm/integration-api` among bapm packages — not `@b-apm/core`.
49
+ Register via `createIntegrationRegistry().register(createClaudeIntegration())` or object-map `targets.claude: "@b-apm/integration-claude"`.
@@ -0,0 +1,28 @@
1
+ import { BapmIntegration, MarketplaceOutputIntegration } from "@b-apm/integration-api";
2
+ //#region src/createClaudeIntegration.d.ts
3
+ /**
4
+ * Create the Claude Code target.
5
+ * Detect: `.claude/` directory **or** project-root `CLAUDE.md`.
6
+ * Materialize: skills → `.claude/skills/<name>/SKILL.md` (never `.agents/skills/`),
7
+ * instructions → `.claude/rules/<name>.md` (`applyTo` → `paths`),
8
+ * agents → `.claude/agents/<name>.md`,
9
+ * commands → `.claude/commands/<name>.md`,
10
+ * hooks → merge `.claude/settings.json` (+ scripts under `.claude/hooks/`, ownership sidecar).
11
+ * MCP: optional `configureMcp` writes project `.mcp.json` when `.claude/` exists.
12
+ * Compile: default `CLAUDE.md`, omitting instruction primitives.
13
+ */
14
+ declare function createClaudeIntegration(options?: {
15
+ id?: string;
16
+ deployRoots?: string[];
17
+ }): BapmIntegration;
18
+ /**
19
+ * Convert portable `applyTo` frontmatter to Claude `paths:` (omit when unconditional).
20
+ */
21
+ declare function transformClaudeRulesMarkdown(source: string): string;
22
+ //#endregion
23
+ //#region src/index.d.ts
24
+ /** Maps resolved packages into Anthropic's marketplace document. */
25
+ declare function mapClaudeMarketplace(config: unknown, resolved: unknown[]): Record<string, unknown>;
26
+ declare const claudeMarketplaceIntegration: MarketplaceOutputIntegration;
27
+ //#endregion
28
+ export { claudeMarketplaceIntegration, createClaudeIntegration, createClaudeIntegration as createIntegration, mapClaudeMarketplace, transformClaudeRulesMarkdown };
package/dist/index.mjs ADDED
@@ -0,0 +1,502 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { SHARED_COMMAND_FRONTMATTER_KEYS, assertUnderDeployRoots, compileMarkdownReport, copyHookScript, filterFrontmatterKeys, materializeSkill, primitivesList, primitivesMaterialize, readHookOwnershipSidecar, readPrimitiveContent, renderPrimitivesMarkdown, sanitizeName, stripOwnedHookCommands, writeDeployedFile, writeHookOwnershipSidecar } from "@b-apm/integration-api";
4
+ //#region src/createClaudeIntegration.ts
5
+ const DEFAULT_DEPLOY_ROOTS = [".claude", "."];
6
+ const MCP_JSON_REL = ".mcp.json";
7
+ const SETTINGS_JSON_REL = ".claude/settings.json";
8
+ const HOOKS_OWNERSHIP_REL = ".claude/bapm-hooks.json";
9
+ /**
10
+ * Create the Claude Code target.
11
+ * Detect: `.claude/` directory **or** project-root `CLAUDE.md`.
12
+ * Materialize: skills → `.claude/skills/<name>/SKILL.md` (never `.agents/skills/`),
13
+ * instructions → `.claude/rules/<name>.md` (`applyTo` → `paths`),
14
+ * agents → `.claude/agents/<name>.md`,
15
+ * commands → `.claude/commands/<name>.md`,
16
+ * hooks → merge `.claude/settings.json` (+ scripts under `.claude/hooks/`, ownership sidecar).
17
+ * MCP: optional `configureMcp` writes project `.mcp.json` when `.claude/` exists.
18
+ * Compile: default `CLAUDE.md`, omitting instruction primitives.
19
+ */
20
+ function createClaudeIntegration(options) {
21
+ const id = options?.id ?? "claude";
22
+ const deployRoots = [...options?.deployRoots ?? DEFAULT_DEPLOY_ROOTS];
23
+ return {
24
+ id,
25
+ deployRoots,
26
+ detect: ({ cwd }) => {
27
+ const claudeDir = join(cwd, ".claude");
28
+ if (existsSync(claudeDir) && statSync(claudeDir).isDirectory()) return true;
29
+ const claudeMd = join(cwd, "CLAUDE.md");
30
+ return existsSync(claudeMd) && statSync(claudeMd).isFile();
31
+ },
32
+ getDeployRoots: () => [...deployRoots],
33
+ async compile(primitives, context) {
34
+ const content = renderPrimitivesMarkdown({
35
+ primitives: primitivesList(primitives),
36
+ title: "# CLAUDE.md",
37
+ filter: (p) => !/instruction/i.test(String(p.type ?? ""))
38
+ });
39
+ return compileMarkdownReport({
40
+ cwd: context.cwd,
41
+ outputFile: context.outputFile ?? "CLAUDE.md",
42
+ write: context.write,
43
+ content,
44
+ outsideCwdMessage: "Claude compile output must be a cwd-relative file path"
45
+ });
46
+ },
47
+ async materialize(primitives, ctx) {
48
+ const cwd = resolve(ctx?.cwd ?? process.cwd());
49
+ const roots = ctx?.deployRoots?.length ? [...ctx.deployRoots] : deployRoots;
50
+ if (!roots.some((r) => r === ".claude" || r.startsWith(".claude"))) throw new Error("claude target missing .claude deploy root");
51
+ const deployedFiles = [];
52
+ const diagnostics = [];
53
+ const hookPrimitives = [];
54
+ await primitivesMaterialize(primitives, {
55
+ skill(p, { name }) {
56
+ deployedFiles.push(...materializeSkill({
57
+ primitive: p,
58
+ cwd,
59
+ deployRoots: roots,
60
+ destDir: join(".claude", "skills", name)
61
+ }));
62
+ },
63
+ instruction(p, { name }) {
64
+ deployedFiles.push(writeDeployedFile({
65
+ cwd,
66
+ deployRoots: roots,
67
+ destRel: join(".claude", "rules", `${name}.md`),
68
+ content: transformClaudeRulesMarkdown(readPrimitiveContent(p)),
69
+ primitive: {
70
+ name: String(p.name),
71
+ packageName: p.packageName
72
+ }
73
+ }));
74
+ },
75
+ agent(p, { name }) {
76
+ deployedFiles.push(writeDeployedFile({
77
+ cwd,
78
+ deployRoots: roots,
79
+ destRel: join(".claude", "agents", `${name}.md`),
80
+ content: readPrimitiveContent(p),
81
+ primitive: {
82
+ name: String(p.name),
83
+ packageName: p.packageName
84
+ }
85
+ }));
86
+ },
87
+ command(p, { name }) {
88
+ const { content, droppedKeys } = filterFrontmatterKeys(readPrimitiveContent(p), SHARED_COMMAND_FRONTMATTER_KEYS);
89
+ deployedFiles.push(writeDeployedFile({
90
+ cwd,
91
+ deployRoots: roots,
92
+ destRel: join(".claude", "commands", `${name}.md`),
93
+ content,
94
+ primitive: {
95
+ name: String(p.name),
96
+ packageName: p.packageName
97
+ }
98
+ }));
99
+ if (droppedKeys.length > 0) diagnostics.push({
100
+ code: "CLAUDE_COMMAND_FRONTMATTER_DROPPED",
101
+ message: `Dropped non-preserved command frontmatter keys for "${p.name}": ${droppedKeys.join(", ")}`,
102
+ primitive: String(p.name),
103
+ droppedKeys
104
+ });
105
+ },
106
+ hook(p) {
107
+ hookPrimitives.push(p);
108
+ }
109
+ });
110
+ if (hookPrimitives.length > 0) {
111
+ const hookDeployed = materializeClaudeHooks({
112
+ cwd,
113
+ roots,
114
+ hooks: hookPrimitives
115
+ });
116
+ deployedFiles.push(...hookDeployed.deployedFiles);
117
+ diagnostics.push(...hookDeployed.diagnostics);
118
+ }
119
+ return {
120
+ targetId: id,
121
+ deployedFiles,
122
+ ...diagnostics.length > 0 ? { diagnostics } : {}
123
+ };
124
+ },
125
+ async configureMcp(servers, ctx) {
126
+ return writeClaudeMcpConfig(servers, {
127
+ cwd: resolve(ctx?.cwd ?? process.cwd()),
128
+ deployRoots: ctx?.deployRoots?.length ? [...ctx.deployRoots] : deployRoots,
129
+ targetId: ctx?.targetId ?? id
130
+ });
131
+ }
132
+ };
133
+ }
134
+ function writeClaudeMcpConfig(servers, ctx) {
135
+ const { cwd, deployRoots } = ctx;
136
+ const claudeDir = join(cwd, ".claude");
137
+ if (!existsSync(claudeDir) || !statSync(claudeDir).isDirectory()) return {
138
+ targetId: ctx.targetId,
139
+ configPath: MCP_JSON_REL,
140
+ servers: [],
141
+ deployedFiles: [],
142
+ diagnostics: [{
143
+ code: "CLAUDE_MCP_SKIP_NO_CLAUDE_DIR",
144
+ message: "Skipping project MCP write: .claude/ directory is absent (Claude project-scope MCP is opt-in)"
145
+ }]
146
+ };
147
+ if (!deployRoots.some((r) => r === "." || r === "./")) throw new Error("claude configureMcp requires a registered '.' deploy root for .mcp.json");
148
+ const destFile = join(cwd, MCP_JSON_REL);
149
+ assertUnderDeployRoots(cwd, destFile, deployRoots);
150
+ if (basename(destFile) !== ".mcp.json") throw new Error("claude configureMcp refuses non-.mcp.json root writes");
151
+ const existingDoc = readExistingMcpDoc(destFile);
152
+ const existingServers = existingDoc.mcpServers && typeof existingDoc.mcpServers === "object" ? { ...existingDoc.mcpServers } : {};
153
+ const { entries: incoming, diagnostics } = normalizeServerEntries(servers);
154
+ const nextServers = { ...existingServers };
155
+ const writtenNames = [];
156
+ for (const [name, entry] of Object.entries(incoming)) {
157
+ const prior = existingServers[name];
158
+ nextServers[name] = prior && typeof prior === "object" ? {
159
+ ...prior,
160
+ ...entry
161
+ } : { ...entry };
162
+ delete nextServers[name].format;
163
+ delete nextServers[name].packageName;
164
+ delete nextServers[name].registry;
165
+ writtenNames.push(name);
166
+ }
167
+ const doc = {
168
+ ...existingDoc,
169
+ mcpServers: nextServers
170
+ };
171
+ writeFileSync(destFile, `${JSON.stringify(doc, null, 2)}\n`, "utf8");
172
+ return {
173
+ targetId: ctx.targetId,
174
+ configPath: MCP_JSON_REL,
175
+ servers: writtenNames,
176
+ deployedFiles: [{ path: MCP_JSON_REL }],
177
+ diagnostics
178
+ };
179
+ }
180
+ function readExistingMcpDoc(path) {
181
+ if (!existsSync(path)) return {};
182
+ try {
183
+ const raw = JSON.parse(readFileSync(path, "utf8"));
184
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? { ...raw } : {};
185
+ } catch {
186
+ return {};
187
+ }
188
+ }
189
+ function normalizeServerEntries(servers) {
190
+ const out = {};
191
+ const diagnostics = [];
192
+ const list = Array.isArray(servers) ? servers : Object.entries(servers).map(([name, value]) => ({
193
+ ...value,
194
+ name: value.name ?? name
195
+ }));
196
+ for (const server of list) {
197
+ const name = String(server.name ?? "").trim();
198
+ if (!name) continue;
199
+ const entry = toClaudeServerEntry(server);
200
+ if (!entry) {
201
+ diagnostics.push({
202
+ code: "CLAUDE_PORTABLE_MCP_UNSUPPORTED",
203
+ message: `Claude cannot faithfully represent MCP server "${name}"`,
204
+ server: name
205
+ });
206
+ continue;
207
+ }
208
+ out[name] = entry;
209
+ }
210
+ return {
211
+ entries: out,
212
+ diagnostics
213
+ };
214
+ }
215
+ function rewriteSkillLauncherCommand(command) {
216
+ if (command.startsWith(".agents/skills/")) return `.claude/skills/${command.slice(15)}`;
217
+ if (command.startsWith("./.agents/skills/")) return `./.claude/skills/${command.slice(17)}`;
218
+ return command;
219
+ }
220
+ function toClaudeServerEntry(server) {
221
+ const transport = String(server.transport ?? server.type ?? "").toLowerCase();
222
+ const entry = {};
223
+ if (server.format === "agent-plugin") {
224
+ if (transport === "stdio") {
225
+ if (typeof server.command !== "string") return void 0;
226
+ entry.command = rewriteSkillLauncherCommand(server.command);
227
+ if (Array.isArray(server.args)) entry.args = server.args;
228
+ if (typeof server.cwd === "string") entry.cwd = server.cwd;
229
+ entry.type = "stdio";
230
+ } else if (transport === "streamable-http" || transport === "sse" || transport === "http") {
231
+ if (typeof server.url !== "string") return void 0;
232
+ entry.url = server.url;
233
+ entry.type = transport === "sse" ? "sse" : "http";
234
+ } else return;
235
+ if (server.env && typeof server.env === "object") entry.env = server.env;
236
+ return entry;
237
+ }
238
+ if (transport === "http" || transport === "sse" || typeof server.url === "string") {
239
+ if (server.url) entry.url = server.url;
240
+ if (transport) entry.type = transport === "sse" ? "sse" : "http";
241
+ } else {
242
+ if (server.command) entry.command = rewriteSkillLauncherCommand(String(server.command));
243
+ if (Array.isArray(server.args)) entry.args = server.args;
244
+ entry.type = "stdio";
245
+ }
246
+ if (server.env && typeof server.env === "object") entry.env = server.env;
247
+ for (const [key, value] of Object.entries(server)) {
248
+ if ([
249
+ "name",
250
+ "transport",
251
+ "type",
252
+ "command",
253
+ "args",
254
+ "url",
255
+ "env",
256
+ "packageName",
257
+ "registry",
258
+ "format",
259
+ "cwd"
260
+ ].includes(key)) continue;
261
+ if (value !== void 0) entry[key] = value;
262
+ }
263
+ return entry;
264
+ }
265
+ /**
266
+ * Convert portable `applyTo` frontmatter to Claude `paths:` (omit when unconditional).
267
+ */
268
+ function transformClaudeRulesMarkdown(source) {
269
+ const match = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
270
+ if (!match) return source;
271
+ const rawFm = match[1] ?? "";
272
+ const body = match[2] ?? "";
273
+ const lines = rawFm.split(/\r?\n/);
274
+ const kept = [];
275
+ const paths = [];
276
+ let i = 0;
277
+ while (i < lines.length) {
278
+ const line = lines[i];
279
+ const keyMatch = line.match(/^([A-Za-z0-9_-]+)\s*:(.*)$/);
280
+ if (!keyMatch) {
281
+ if (line.trim()) kept.push(line);
282
+ i += 1;
283
+ continue;
284
+ }
285
+ const key = keyMatch[1];
286
+ const rest = keyMatch[2] ?? "";
287
+ if (key === "applyTo" || key === "paths") {
288
+ const inline = rest.trim();
289
+ if (inline.startsWith("[") && inline.endsWith("]")) {
290
+ for (const part of inline.slice(1, -1).split(",")) {
291
+ const v = part.trim().replace(/^["']|["']$/g, "");
292
+ if (v) paths.push(v);
293
+ }
294
+ i += 1;
295
+ continue;
296
+ }
297
+ if (inline && inline !== "|" && inline !== ">") {
298
+ paths.push(inline.replace(/^["']|["']$/g, ""));
299
+ i += 1;
300
+ continue;
301
+ }
302
+ i += 1;
303
+ while (i < lines.length) {
304
+ const listMatch = lines[i].match(/^[ \t]*-[ \t]*(.+)$/);
305
+ if (!listMatch) break;
306
+ paths.push(listMatch[1].trim().replace(/^["']|["']$/g, ""));
307
+ i += 1;
308
+ }
309
+ continue;
310
+ }
311
+ kept.push(line);
312
+ i += 1;
313
+ }
314
+ const fmLines = [...kept];
315
+ if (paths.length > 0) {
316
+ fmLines.push("paths:");
317
+ for (const p of paths) fmLines.push(` - ${JSON.stringify(p)}`);
318
+ }
319
+ if (fmLines.length === 0) return body.replace(/\s+$/, "\n") || body;
320
+ return `---\n${fmLines.join("\n")}\n---\n${body}`.replace(/\s+$/, "\n");
321
+ }
322
+ function materializeClaudeHooks(args) {
323
+ const { cwd, roots, hooks } = args;
324
+ const deployedFiles = [];
325
+ const diagnostics = [];
326
+ const settingsPath = join(cwd, SETTINGS_JSON_REL);
327
+ const ownershipPath = join(cwd, HOOKS_OWNERSHIP_REL);
328
+ assertUnderDeployRoots(cwd, settingsPath, roots);
329
+ assertUnderDeployRoots(cwd, ownershipPath, roots);
330
+ mkdirSync(join(cwd, ".claude"), { recursive: true });
331
+ const doc = readSettingsDoc(settingsPath);
332
+ const ownership = readHookOwnershipSidecar(ownershipPath);
333
+ if (doc.hooks && typeof doc.hooks === "object") stripOwnedHookCommands(doc.hooks, ownership);
334
+ const nextOwned = {};
335
+ for (const p of hooks) {
336
+ const name = sanitizeName(String(p.name));
337
+ const srcPath = p.path ? resolve(p.path) : void 0;
338
+ if (!srcPath || !existsSync(srcPath) || !statSync(srcPath).isFile()) {
339
+ diagnostics.push({
340
+ code: "CLAUDE_HOOK_SOURCE_MISSING",
341
+ message: `Hook primitive "${p.name}" has no readable source JSON`,
342
+ primitive: String(p.name)
343
+ });
344
+ continue;
345
+ }
346
+ let parsed;
347
+ try {
348
+ parsed = JSON.parse(readFileSync(srcPath, "utf8"));
349
+ } catch (cause) {
350
+ diagnostics.push({
351
+ code: "CLAUDE_HOOK_JSON_INVALID",
352
+ message: `Hook "${p.name}" JSON is invalid: ${cause instanceof Error ? cause.message : String(cause)}`,
353
+ primitive: String(p.name)
354
+ });
355
+ continue;
356
+ }
357
+ const sourceHooks = parsed.hooks && typeof parsed.hooks === "object" ? parsed.hooks : {};
358
+ const ownedEntries = [];
359
+ const scripts = [];
360
+ if (!doc.hooks || typeof doc.hooks !== "object") doc.hooks = {};
361
+ for (const [event, entries] of Object.entries(sourceHooks)) {
362
+ if (!Array.isArray(entries)) continue;
363
+ const destList = Array.isArray(doc.hooks[event]) ? [...doc.hooks[event]] : [];
364
+ for (const entry of entries) {
365
+ if (!entry || typeof entry !== "object") continue;
366
+ const command = typeof entry.command === "string" ? entry.command.trim() : "";
367
+ if (!command) {
368
+ const { _apm_source: _drop, ...clean } = entry;
369
+ destList.push({ ...clean });
370
+ continue;
371
+ }
372
+ const rewritten = copyHookScript({
373
+ cwd,
374
+ deployRoots: roots,
375
+ hookFile: srcPath,
376
+ command,
377
+ alreadyDeployedNeedle: ".claude/",
378
+ destRel: `.claude/hooks/${name}/${basename(command.replace(/^\.\//, ""))}`,
379
+ commandAsDotSlash: true
380
+ });
381
+ const { _apm_source: _drop, ...clean } = entry;
382
+ const nextEntry = {
383
+ ...clean,
384
+ command: rewritten.commandRel
385
+ };
386
+ destList.push(nextEntry);
387
+ ownedEntries.push({
388
+ event,
389
+ command: rewritten.commandRel
390
+ });
391
+ if (rewritten.scriptRel) {
392
+ scripts.push(rewritten.scriptRel);
393
+ deployedFiles.push({
394
+ path: rewritten.scriptRel,
395
+ primitive: {
396
+ name: String(p.name),
397
+ packageName: p.packageName
398
+ }
399
+ });
400
+ }
401
+ }
402
+ doc.hooks[event] = destList;
403
+ }
404
+ nextOwned[name] = {
405
+ ...p.packageName ? { packageName: p.packageName } : {},
406
+ entries: ownedEntries,
407
+ scripts
408
+ };
409
+ }
410
+ writeFileSync(settingsPath, `${JSON.stringify(doc, null, 2)}\n`, "utf8");
411
+ writeHookOwnershipSidecar(ownershipPath, { owned: nextOwned });
412
+ deployedFiles.push({
413
+ path: SETTINGS_JSON_REL,
414
+ ...hooks[0] ? { primitive: {
415
+ name: String(hooks[0].name),
416
+ packageName: hooks[0].packageName
417
+ } } : {}
418
+ });
419
+ deployedFiles.push({
420
+ path: HOOKS_OWNERSHIP_REL,
421
+ ...hooks[0] ? { primitive: {
422
+ name: String(hooks[0].name),
423
+ packageName: hooks[0].packageName
424
+ } } : {}
425
+ });
426
+ return {
427
+ deployedFiles,
428
+ diagnostics
429
+ };
430
+ }
431
+ function readSettingsDoc(path) {
432
+ if (!existsSync(path)) return { hooks: {} };
433
+ try {
434
+ const raw = JSON.parse(readFileSync(path, "utf8"));
435
+ if (!raw || typeof raw !== "object") return { hooks: {} };
436
+ if (!raw.hooks || typeof raw.hooks !== "object") raw.hooks = {};
437
+ return raw;
438
+ } catch {
439
+ return { hooks: {} };
440
+ }
441
+ }
442
+ //#endregion
443
+ //#region src/index.ts
444
+ function ownerObject(config) {
445
+ const owner = config.owner;
446
+ if (!owner) return { name: "unknown" };
447
+ if (typeof owner === "string") return { name: owner };
448
+ const value = owner;
449
+ return {
450
+ name: value.name,
451
+ ...value.email ? { email: value.email } : {},
452
+ ...value.url ? { url: value.url } : {}
453
+ };
454
+ }
455
+ /** Maps resolved packages into Anthropic's marketplace document. */
456
+ function mapClaudeMarketplace(config, resolved) {
457
+ const cfg = config;
458
+ const plugins = resolved.map((pkg) => {
459
+ const entry = pkg.entry;
460
+ const plugin = { name: pkg.name };
461
+ for (const key of [
462
+ "description",
463
+ "author",
464
+ "license",
465
+ "repository",
466
+ "category"
467
+ ]) if (entry[key]) plugin[key] = entry[key];
468
+ if (typeof entry.version === "string" && !/[\^~><=* ]/.test(entry.version)) plugin.version = entry.version;
469
+ if (Array.isArray(pkg.tags) && pkg.tags.length) plugin.tags = pkg.tags;
470
+ if (pkg.isLocal) plugin.source = pkg.source;
471
+ else if (pkg.subdir) plugin.source = {
472
+ source: "git-subdir",
473
+ url: pkg.sourceUrl ?? pkg.sourceRepo,
474
+ path: pkg.subdir,
475
+ ...pkg.ref ? { ref: pkg.ref } : {},
476
+ ...pkg.sha ? { sha: pkg.sha } : {}
477
+ };
478
+ else plugin.source = {
479
+ source: "url",
480
+ url: pkg.sourceUrl ?? pkg.sourceRepo
481
+ };
482
+ return plugin;
483
+ });
484
+ return {
485
+ name: cfg.name ?? "marketplace",
486
+ ...cfg.description ? { description: cfg.description } : {},
487
+ ...cfg.version ? { version: cfg.version } : {},
488
+ owner: ownerObject(cfg),
489
+ ...cfg.metadata ? { metadata: cfg.metadata } : {},
490
+ plugins
491
+ };
492
+ }
493
+ const claudeMarketplaceIntegration = {
494
+ id: "claude",
495
+ marketplaceOutput: {
496
+ format: "claude",
497
+ defaultOutput: ".claude-plugin/marketplace.json",
498
+ map: mapClaudeMarketplace
499
+ }
500
+ };
501
+ //#endregion
502
+ export { claudeMarketplaceIntegration, createClaudeIntegration, createClaudeIntegration as createIntegration, mapClaudeMarketplace, transformClaudeRulesMarkdown };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@b-apm/integration-claude",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code runtime + marketplace-output integration for bapm",
5
+ "license": "MIT",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "type": "module",
10
+ "exports": {
11
+ ".": "./dist/index.mjs",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "dependencies": {
18
+ "@b-apm/integration-api": "0.1.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^26.1.2",
22
+ "typescript": "^7.0.2",
23
+ "vite": "npm:@voidzero-dev/vite-plus-core@latest",
24
+ "vite-plus": "latest"
25
+ },
26
+ "engines": {
27
+ "node": ">=22.12.0"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/Sdju/bapm.git",
32
+ "directory": "packages/integration-claude"
33
+ },
34
+ "homepage": "https://github.com/Sdju/bapm#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/Sdju/bapm/issues"
37
+ },
38
+ "keywords": [
39
+ "unstable",
40
+ "bapm",
41
+ "b-apm"
42
+ ],
43
+ "scripts": {
44
+ "build": "vp pack",
45
+ "dev": "vp pack --watch",
46
+ "test": "vp test",
47
+ "check": "vp check"
48
+ }
49
+ }