@intentius/chant 0.0.22 → 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.
Files changed (34) hide show
  1. package/package.json +1 -1
  2. package/src/cli/commands/init-lexicon/templates/codegen.ts +188 -0
  3. package/src/cli/commands/init-lexicon/templates/docs.ts +81 -0
  4. package/src/cli/commands/init-lexicon/templates/examples.ts +35 -0
  5. package/src/cli/commands/init-lexicon/templates/lint.ts +30 -0
  6. package/src/cli/commands/init-lexicon/templates/lsp.ts +39 -0
  7. package/src/cli/commands/init-lexicon/templates/plugin.ts +110 -0
  8. package/src/cli/commands/init-lexicon/templates/project.ts +182 -0
  9. package/src/cli/commands/init-lexicon/templates/spec.ts +57 -0
  10. package/src/cli/commands/init-lexicon/templates/tests.ts +70 -0
  11. package/src/cli/commands/init-lexicon.ts +12 -774
  12. package/src/cli/conflict-check.test.ts +43 -0
  13. package/src/cli/main.ts +1 -1
  14. package/src/cli/mcp/resource-handlers.ts +227 -0
  15. package/src/cli/mcp/server.ts +20 -409
  16. package/src/cli/mcp/state-tools.ts +138 -0
  17. package/src/cli/mcp/types.ts +45 -0
  18. package/src/codegen/docs-file-markers.ts +69 -0
  19. package/src/codegen/docs-rule-scanning.ts +159 -0
  20. package/src/codegen/docs-sections.ts +159 -0
  21. package/src/codegen/docs-sidebar.ts +56 -0
  22. package/src/codegen/docs-types.ts +79 -0
  23. package/src/codegen/docs.ts +9 -495
  24. package/src/codegen/typecheck.ts +13 -0
  25. package/src/composite.test.ts +75 -0
  26. package/src/composite.ts +37 -0
  27. package/src/discovery/collect.test.ts +34 -0
  28. package/src/discovery/collect.ts +25 -0
  29. package/src/lexicon-plugin-helpers.ts +130 -0
  30. package/src/toml-emit.ts +182 -0
  31. package/src/toml-parse.ts +370 -0
  32. package/src/toml-utils.ts +60 -0
  33. package/src/toml.ts +5 -602
  34. package/src/yaml.ts +7 -2
@@ -54,6 +54,40 @@ describe("collectEntities", () => {
54
54
  expect(result.get("entity3")).toBe(entity3);
55
55
  });
56
56
 
57
+ test("collects arrays of declarable entities with indexed names", () => {
58
+ const e0 = createMockEntity("type");
59
+ const e1 = createMockEntity("type");
60
+ const e2 = createMockEntity("type");
61
+
62
+ const modules = [
63
+ {
64
+ file: "test.ts",
65
+ exports: { myResources: [e0, e1, e2] },
66
+ },
67
+ ];
68
+
69
+ const result = collectEntities(modules);
70
+ expect(result.size).toBe(3);
71
+ expect(result.get("myResources_0")).toBe(e0);
72
+ expect(result.get("myResources_1")).toBe(e1);
73
+ expect(result.get("myResources_2")).toBe(e2);
74
+ });
75
+
76
+ test("ignores non-declarable items within arrays", () => {
77
+ const e0 = createMockEntity("type");
78
+
79
+ const modules = [
80
+ {
81
+ file: "test.ts",
82
+ exports: { mixed: [e0, "string", 42, null] },
83
+ },
84
+ ];
85
+
86
+ const result = collectEntities(modules);
87
+ expect(result.size).toBe(1);
88
+ expect(result.get("mixed_0")).toBe(e0);
89
+ });
90
+
57
91
  test("ignores non-declarable exports", () => {
58
92
  const entity = createMockEntity("test");
59
93
 
@@ -34,6 +34,31 @@ export function collectEntities(
34
34
  } else {
35
35
  entities.set(name, value);
36
36
  }
37
+ } else if (Array.isArray(value)) {
38
+ // Arrays of Declarables or CompositeInstances — each element gets an indexed name: exportName_0, ...
39
+ for (let i = 0; i < value.length; i++) {
40
+ const item = value[i];
41
+ if (isDeclarable(item)) {
42
+ const indexedName = `${name}_${i}`;
43
+ if (entities.has(indexedName) && entities.get(indexedName) !== item) {
44
+ throw new DiscoveryError(file, `Duplicate entity name "${indexedName}"`, "resolution");
45
+ }
46
+ entities.set(indexedName, item);
47
+ } else if (isCompositeInstance(item)) {
48
+ const indexedName = `${name}_${i}`;
49
+ const expanded = expandComposite(indexedName, item);
50
+ for (const [expandedName, entity] of expanded) {
51
+ if (entities.has(expandedName)) {
52
+ throw new DiscoveryError(
53
+ file,
54
+ `Duplicate entity name "${expandedName}" from composite expansion of "${indexedName}"`,
55
+ "resolution",
56
+ );
57
+ }
58
+ entities.set(expandedName, entity);
59
+ }
60
+ }
61
+ }
37
62
  } else if (isCompositeInstance(value)) {
38
63
  const expanded = expandComposite(name, value);
39
64
  for (const [expandedName, entity] of expanded) {
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Shared helpers for lexicon plugin implementations.
3
+ *
4
+ * Eliminates boilerplate across the 8 lexicon plugins by providing
5
+ * factory functions for common plugin methods: skills loading,
6
+ * MCP diff tool, and MCP catalog resource.
7
+ */
8
+
9
+ import { readFileSync } from "fs";
10
+ import { join, dirname } from "path";
11
+ import { fileURLToPath } from "url";
12
+ import type { SkillDefinition } from "./lexicon";
13
+ import type { McpToolContribution, McpResourceContribution } from "./mcp/types";
14
+ import type { Serializer } from "./serializer";
15
+
16
+ // ── Skills Loader ─────────────────────────────────────────────────
17
+
18
+ /**
19
+ * Metadata for a skill file on disk. Spread into the resulting SkillDefinition
20
+ * after the file content is read.
21
+ */
22
+ export type SkillFileSpec = Omit<SkillDefinition, "content"> & {
23
+ /** Filename relative to the skills directory (e.g. "chant-aws.md") */
24
+ file: string;
25
+ };
26
+
27
+ /**
28
+ * Create a skills loader that reads .md files from a lexicon's skills directory.
29
+ *
30
+ * Usage in a plugin:
31
+ * ```ts
32
+ * import { createSkillsLoader } from "@intentius/chant/lexicon-plugin-helpers";
33
+ *
34
+ * const loadSkills = createSkillsLoader(import.meta.url, [
35
+ * { file: "chant-aws.md", name: "chant-aws", description: "..." },
36
+ * ]);
37
+ *
38
+ * // In plugin:
39
+ * skills() { return loadSkills(); }
40
+ * ```
41
+ */
42
+ export function createSkillsLoader(
43
+ importMetaUrl: string,
44
+ specs: SkillFileSpec[],
45
+ ): () => SkillDefinition[] {
46
+ return () => {
47
+ const skillsDir = join(dirname(fileURLToPath(importMetaUrl)), "skills");
48
+ return specs.map(({ file, ...meta }) => {
49
+ try {
50
+ const content = readFileSync(join(skillsDir, file), "utf-8");
51
+ return { ...meta, content };
52
+ } catch {
53
+ return { ...meta, content: "" };
54
+ }
55
+ });
56
+ };
57
+ }
58
+
59
+ // ── MCP Diff Tool ─────────────────────────────────────────────────
60
+
61
+ /**
62
+ * Create an MCP diff tool contribution for a lexicon.
63
+ *
64
+ * All lexicons (except Azure) expose an identical "diff" tool that compares
65
+ * current build output against previous output using the lexicon's serializer.
66
+ */
67
+ export function createDiffTool(
68
+ serializer: Serializer,
69
+ description: string,
70
+ ): McpToolContribution {
71
+ return {
72
+ name: "diff",
73
+ description,
74
+ inputSchema: {
75
+ type: "object" as const,
76
+ properties: {
77
+ path: {
78
+ type: "string",
79
+ description: "Path to the infrastructure project directory",
80
+ },
81
+ },
82
+ },
83
+ async handler(params: Record<string, unknown>): Promise<unknown> {
84
+ const { diffCommand } = await import("./cli/commands/diff");
85
+ const result = await diffCommand({
86
+ path: (params.path as string) ?? ".",
87
+ serializers: [serializer],
88
+ });
89
+ return result;
90
+ },
91
+ };
92
+ }
93
+
94
+ // ── MCP Catalog Resource ──────────────────────────────────────────
95
+
96
+ /**
97
+ * Create an MCP resource that serves the lexicon's meta.json as a catalog.
98
+ *
99
+ * Most lexicons expose a "resource-catalog" resource with identical structure.
100
+ *
101
+ * @param importMetaUrl — The plugin's import.meta.url (used to locate generated JSON)
102
+ * @param name — Display name (e.g. "AWS Resource Catalog")
103
+ * @param description — Resource description
104
+ * @param lexiconJsonFile — Filename of the generated lexicon JSON (e.g. "lexicon-aws.json")
105
+ */
106
+ export function createCatalogResource(
107
+ importMetaUrl: string,
108
+ name: string,
109
+ description: string,
110
+ lexiconJsonFile: string,
111
+ ): McpResourceContribution {
112
+ return {
113
+ uri: "resource-catalog",
114
+ name,
115
+ description,
116
+ mimeType: "application/json",
117
+ async handler(): Promise<string> {
118
+ const dir = dirname(fileURLToPath(importMetaUrl));
119
+ const lexicon = JSON.parse(
120
+ readFileSync(join(dir, "generated", lexiconJsonFile), "utf-8"),
121
+ ) as Record<string, { resourceType: string; kind: string }>;
122
+ const entries = Object.entries(lexicon).map(([className, entry]) => ({
123
+ className,
124
+ resourceType: entry.resourceType,
125
+ kind: entry.kind,
126
+ }));
127
+ return JSON.stringify(entries);
128
+ },
129
+ };
130
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * TOML emitter.
3
+ *
4
+ * Converts JavaScript objects to TOML document strings.
5
+ * Handles scalars, tables, arrays, array of tables, and inline tables.
6
+ */
7
+
8
+ import { escapeKey, sortKeys } from "./toml-utils";
9
+
10
+ export interface EmitTOMLOptions {
11
+ /** Comment to prepend at the top of the document. */
12
+ header?: string;
13
+ /** Key ordering hint: keys matching earlier entries appear first. */
14
+ keyOrder?: string[];
15
+ }
16
+
17
+ /**
18
+ * Emit a JavaScript object as a TOML document string.
19
+ *
20
+ * - Top-level scalars, arrays of scalars → bare key-value pairs.
21
+ * - Nested objects → `[section]` tables.
22
+ * - Arrays of objects → `[[section]]` array of tables.
23
+ * - Deeply nested objects → `[parent.child]` dotted sections.
24
+ */
25
+ export function emitTOML(value: unknown, options?: EmitTOMLOptions): string {
26
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
27
+ throw new Error("emitTOML expects a plain object at the top level");
28
+ }
29
+
30
+ const lines: string[] = [];
31
+
32
+ if (options?.header) {
33
+ for (const line of options.header.split("\n")) {
34
+ lines.push(`# ${line}`);
35
+ }
36
+ lines.push("");
37
+ }
38
+
39
+ const obj = value as Record<string, unknown>;
40
+ emitTable(obj, [], lines, options?.keyOrder);
41
+
42
+ // Trim trailing blank lines, ensure single trailing newline
43
+ while (lines.length > 0 && lines[lines.length - 1] === "") {
44
+ lines.pop();
45
+ }
46
+ return lines.join("\n") + "\n";
47
+ }
48
+
49
+ /**
50
+ * Emit a TOML table (recursively handles nested tables and array of tables).
51
+ */
52
+ function emitTable(
53
+ obj: Record<string, unknown>,
54
+ path: string[],
55
+ lines: string[],
56
+ keyOrder?: string[],
57
+ ): void {
58
+ const keys = sortKeys(Object.keys(obj), keyOrder);
59
+
60
+ // First pass: emit all scalar / inline values
61
+ for (const key of keys) {
62
+ const val = obj[key];
63
+ if (val === undefined) continue;
64
+ if (isTableValue(val)) continue; // handled in second pass
65
+ if (isArrayOfTables(val)) continue; // handled in second pass
66
+
67
+ lines.push(`${escapeKey(key)} = ${emitValue(val)}`);
68
+ }
69
+
70
+ // Second pass: emit nested tables
71
+ for (const key of keys) {
72
+ const val = obj[key];
73
+ if (val === undefined) continue;
74
+
75
+ if (isArrayOfTables(val)) {
76
+ const arr = val as Record<string, unknown>[];
77
+ for (const item of arr) {
78
+ lines.push("");
79
+ const sectionPath = [...path, key];
80
+ lines.push(`[[${sectionPath.map(escapeKey).join(".")}]]`);
81
+ emitTable(item, sectionPath, lines, keyOrder);
82
+ }
83
+ } else if (isTableValue(val)) {
84
+ lines.push("");
85
+ const sectionPath = [...path, key];
86
+ lines.push(`[${sectionPath.map(escapeKey).join(".")}]`);
87
+ emitTable(val as Record<string, unknown>, sectionPath, lines, keyOrder);
88
+ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Check if a value should be emitted as a `[table]` section.
94
+ */
95
+ function isTableValue(val: unknown): val is Record<string, unknown> {
96
+ return (
97
+ typeof val === "object" &&
98
+ val !== null &&
99
+ !Array.isArray(val) &&
100
+ !(val instanceof Date)
101
+ );
102
+ }
103
+
104
+ /**
105
+ * Check if a value is an array of tables (`[[section]]`).
106
+ */
107
+ function isArrayOfTables(val: unknown): boolean {
108
+ if (!Array.isArray(val) || val.length === 0) return false;
109
+ return val.every(
110
+ (item) => typeof item === "object" && item !== null && !Array.isArray(item) && !(item instanceof Date),
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Emit a TOML value (scalar, array of scalars, inline table).
116
+ */
117
+ function emitValue(val: unknown): string {
118
+ if (val === null || val === undefined) {
119
+ return '""'; // TOML has no null — emit empty string
120
+ }
121
+
122
+ if (typeof val === "boolean") {
123
+ return val ? "true" : "false";
124
+ }
125
+
126
+ if (typeof val === "number") {
127
+ if (Number.isInteger(val)) return String(val);
128
+ return String(val);
129
+ }
130
+
131
+ if (typeof val === "string") {
132
+ return emitString(val);
133
+ }
134
+
135
+ if (val instanceof Date) {
136
+ return val.toISOString();
137
+ }
138
+
139
+ if (Array.isArray(val)) {
140
+ if (val.length === 0) return "[]";
141
+ // Array of scalars → inline array
142
+ const items = val.map((item) => emitValue(item));
143
+ const inline = `[${items.join(", ")}]`;
144
+ if (inline.length <= 80) return inline;
145
+ // Multi-line array for long content
146
+ const multiLines = val.map((item) => ` ${emitValue(item)},`);
147
+ return "[\n" + multiLines.join("\n") + "\n]";
148
+ }
149
+
150
+ // Inline table for non-table contexts (shouldn't normally reach here
151
+ // because isTableValue is checked first, but handles edge cases)
152
+ if (typeof val === "object") {
153
+ const entries = Object.entries(val as Record<string, unknown>);
154
+ if (entries.length === 0) return "{}";
155
+ const pairs = entries.map(([k, v]) => `${escapeKey(k)} = ${emitValue(v)}`);
156
+ return `{ ${pairs.join(", ")} }`;
157
+ }
158
+
159
+ return String(val);
160
+ }
161
+
162
+ /**
163
+ * Emit a TOML string with proper quoting.
164
+ */
165
+ function emitString(val: string): string {
166
+ // Use basic strings with escaping for most values
167
+ if (val.includes("\n") || val.includes("\r")) {
168
+ // Multi-line basic string
169
+ const escaped = val
170
+ .replace(/\\/g, "\\\\")
171
+ .replace(/"""/g, '\\"""');
172
+ return `"""\n${escaped}"""`;
173
+ }
174
+
175
+ // Regular basic string
176
+ const escaped = val
177
+ .replace(/\\/g, "\\\\")
178
+ .replace(/"/g, '\\"')
179
+ .replace(/\t/g, "\\t")
180
+ .replace(/\r/g, "\\r");
181
+ return `"${escaped}"`;
182
+ }