@mapomodule/mcp 0.0.0-stage → 1.0.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.
Files changed (153) hide show
  1. package/README.md +479 -2
  2. package/bin/mapo-mcp.mjs +3 -0
  3. package/dist/build.d.mts +18 -0
  4. package/dist/build.d.ts +18 -0
  5. package/dist/build.mjs +351 -0
  6. package/dist/cli.d.mts +7 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.mjs +263 -0
  9. package/dist/index.d.mts +68 -0
  10. package/dist/index.d.ts +68 -0
  11. package/dist/index.mjs +1 -0
  12. package/dist/knowledge/api.json +1 -0
  13. package/dist/knowledge/docs.json +1 -0
  14. package/dist/module.d.mts +16 -0
  15. package/dist/module.d.ts +16 -0
  16. package/dist/module.json +9 -0
  17. package/dist/module.mjs +121 -0
  18. package/dist/runtime/core/doctor.d.ts +0 -0
  19. package/dist/runtime/core/doctor.js +128 -0
  20. package/dist/runtime/core/indexer.d.ts +0 -0
  21. package/dist/runtime/core/indexer.js +193 -0
  22. package/dist/runtime/core/knowledge.d.ts +0 -0
  23. package/dist/runtime/core/knowledge.js +76 -0
  24. package/dist/runtime/core/openapi.d.ts +0 -0
  25. package/dist/runtime/core/openapi.js +229 -0
  26. package/dist/runtime/core/prompts.d.ts +0 -0
  27. package/dist/runtime/core/prompts.js +108 -0
  28. package/dist/runtime/core/recipes.d.ts +0 -0
  29. package/dist/runtime/core/recipes.js +297 -0
  30. package/dist/runtime/core/resources.d.ts +0 -0
  31. package/dist/runtime/core/resources.js +88 -0
  32. package/dist/runtime/core/scaffold/fields.d.ts +0 -0
  33. package/dist/runtime/core/scaffold/fields.js +64 -0
  34. package/dist/runtime/core/scaffold/index.d.ts +0 -0
  35. package/dist/runtime/core/scaffold/index.js +74 -0
  36. package/dist/runtime/core/scaffold/templates.d.ts +0 -0
  37. package/dist/runtime/core/scaffold/templates.js +349 -0
  38. package/dist/runtime/core/schema-source.d.ts +0 -0
  39. package/dist/runtime/core/schema-source.js +70 -0
  40. package/dist/runtime/core/search.d.ts +0 -0
  41. package/dist/runtime/core/search.js +173 -0
  42. package/dist/runtime/core/tokenize.d.ts +0 -0
  43. package/dist/runtime/core/tokenize.js +96 -0
  44. package/dist/runtime/core/tool-spec.d.ts +0 -0
  45. package/dist/runtime/core/tool-spec.js +3 -0
  46. package/dist/runtime/core/tools/api.d.ts +0 -0
  47. package/dist/runtime/core/tools/api.js +192 -0
  48. package/dist/runtime/core/tools/app.d.ts +0 -0
  49. package/dist/runtime/core/tools/app.js +141 -0
  50. package/dist/runtime/core/tools/backend.d.ts +0 -0
  51. package/dist/runtime/core/tools/backend.js +143 -0
  52. package/dist/runtime/core/tools/docs.d.ts +0 -0
  53. package/dist/runtime/core/tools/docs.js +150 -0
  54. package/dist/runtime/core/tools/scaffold.d.ts +0 -0
  55. package/dist/runtime/core/tools/scaffold.js +127 -0
  56. package/dist/runtime/core/types.d.ts +0 -0
  57. package/dist/runtime/core/types.js +0 -0
  58. package/dist/runtime/core/write.d.ts +0 -0
  59. package/dist/runtime/core/write.js +53 -0
  60. package/dist/runtime/mcp/handlers/mapo/index.js +13 -0
  61. package/dist/runtime/mcp/handlers/mapo/prompts/crud-page.js +3 -0
  62. package/dist/runtime/mcp/handlers/mapo/prompts/custom-field.js +3 -0
  63. package/dist/runtime/mcp/handlers/mapo/prompts/debug-form.js +3 -0
  64. package/dist/runtime/mcp/handlers/mapo/prompts/migrate-v1.js +3 -0
  65. package/dist/runtime/mcp/handlers/mapo/prompts/theme.js +3 -0
  66. package/dist/runtime/mcp/handlers/mapo/resources/app-manifest.js +19 -0
  67. package/dist/runtime/mcp/handlers/mapo/resources/docs.js +34 -0
  68. package/dist/runtime/mcp/handlers/mapo/resources/fields.js +34 -0
  69. package/dist/runtime/mcp/handlers/mapo/resources/knowledge-index.js +22 -0
  70. package/dist/runtime/mcp/handlers/mapo/tools/backend-schema.js +3 -0
  71. package/dist/runtime/mcp/handlers/mapo/tools/component-api.js +3 -0
  72. package/dist/runtime/mcp/handlers/mapo/tools/composable-api.js +3 -0
  73. package/dist/runtime/mcp/handlers/mapo/tools/doctor.js +3 -0
  74. package/dist/runtime/mcp/handlers/mapo/tools/get-doc.js +3 -0
  75. package/dist/runtime/mcp/handlers/mapo/tools/inspect-app.js +3 -0
  76. package/dist/runtime/mcp/handlers/mapo/tools/list-field-types.js +3 -0
  77. package/dist/runtime/mcp/handlers/mapo/tools/list-recipes.js +3 -0
  78. package/dist/runtime/mcp/handlers/mapo/tools/scaffold.js +3 -0
  79. package/dist/runtime/mcp/handlers/mapo/tools/search-docs.js +3 -0
  80. package/dist/runtime/nitro/context.d.ts +0 -0
  81. package/dist/runtime/nitro/context.js +21 -0
  82. package/dist/runtime/nitro/to-mcp-prompt.d.ts +0 -0
  83. package/dist/runtime/nitro/to-mcp-prompt.js +23 -0
  84. package/dist/runtime/nitro/to-mcp-tool.d.ts +0 -0
  85. package/dist/runtime/nitro/to-mcp-tool.js +28 -0
  86. package/dist/runtime/types/virtual-modules.d.ts +6 -0
  87. package/dist/types.d.mts +9 -0
  88. package/package.json +73 -4
  89. package/src/__tests__/cli.test.ts +121 -0
  90. package/src/__tests__/doctor.test.ts +145 -0
  91. package/src/__tests__/fixtures/drf-schema.json +142 -0
  92. package/src/__tests__/fixtures.ts +198 -0
  93. package/src/__tests__/indexer.test.ts +114 -0
  94. package/src/__tests__/knowledge.test.ts +209 -0
  95. package/src/__tests__/openapi.test.ts +256 -0
  96. package/src/__tests__/recipes.test.ts +44 -0
  97. package/src/__tests__/resources.test.ts +69 -0
  98. package/src/__tests__/scaffold.test.ts +153 -0
  99. package/src/__tests__/search.test.ts +105 -0
  100. package/src/__tests__/tools.test.ts +226 -0
  101. package/src/__tests__/write.test.ts +134 -0
  102. package/src/build/extract-components.ts +135 -0
  103. package/src/build/extract-composables.ts +125 -0
  104. package/src/build/extract-fields.ts +250 -0
  105. package/src/build/index.ts +103 -0
  106. package/src/cli.ts +364 -0
  107. package/src/index.ts +65 -0
  108. package/src/module.ts +214 -0
  109. package/src/runtime/core/doctor.ts +204 -0
  110. package/src/runtime/core/indexer.ts +279 -0
  111. package/src/runtime/core/knowledge.ts +121 -0
  112. package/src/runtime/core/openapi.ts +417 -0
  113. package/src/runtime/core/prompts.ts +150 -0
  114. package/src/runtime/core/recipes.ts +361 -0
  115. package/src/runtime/core/resources.ts +144 -0
  116. package/src/runtime/core/scaffold/fields.ts +127 -0
  117. package/src/runtime/core/scaffold/index.ts +120 -0
  118. package/src/runtime/core/scaffold/templates.ts +394 -0
  119. package/src/runtime/core/schema-source.ts +123 -0
  120. package/src/runtime/core/search.ts +282 -0
  121. package/src/runtime/core/tokenize.ts +146 -0
  122. package/src/runtime/core/tool-spec.ts +74 -0
  123. package/src/runtime/core/tools/api.ts +300 -0
  124. package/src/runtime/core/tools/app.ts +200 -0
  125. package/src/runtime/core/tools/backend.ts +197 -0
  126. package/src/runtime/core/tools/docs.ts +215 -0
  127. package/src/runtime/core/tools/scaffold.ts +176 -0
  128. package/src/runtime/core/types.ts +133 -0
  129. package/src/runtime/core/write.ts +119 -0
  130. package/src/runtime/mcp/handlers/mapo/index.ts +22 -0
  131. package/src/runtime/mcp/handlers/mapo/prompts/crud-page.ts +4 -0
  132. package/src/runtime/mcp/handlers/mapo/prompts/custom-field.ts +4 -0
  133. package/src/runtime/mcp/handlers/mapo/prompts/debug-form.ts +4 -0
  134. package/src/runtime/mcp/handlers/mapo/prompts/migrate-v1.ts +4 -0
  135. package/src/runtime/mcp/handlers/mapo/prompts/theme.ts +4 -0
  136. package/src/runtime/mcp/handlers/mapo/resources/app-manifest.ts +28 -0
  137. package/src/runtime/mcp/handlers/mapo/resources/docs.ts +41 -0
  138. package/src/runtime/mcp/handlers/mapo/resources/fields.ts +37 -0
  139. package/src/runtime/mcp/handlers/mapo/resources/knowledge-index.ts +24 -0
  140. package/src/runtime/mcp/handlers/mapo/tools/backend-schema.ts +4 -0
  141. package/src/runtime/mcp/handlers/mapo/tools/component-api.ts +4 -0
  142. package/src/runtime/mcp/handlers/mapo/tools/composable-api.ts +4 -0
  143. package/src/runtime/mcp/handlers/mapo/tools/doctor.ts +4 -0
  144. package/src/runtime/mcp/handlers/mapo/tools/get-doc.ts +4 -0
  145. package/src/runtime/mcp/handlers/mapo/tools/inspect-app.ts +4 -0
  146. package/src/runtime/mcp/handlers/mapo/tools/list-field-types.ts +4 -0
  147. package/src/runtime/mcp/handlers/mapo/tools/list-recipes.ts +4 -0
  148. package/src/runtime/mcp/handlers/mapo/tools/scaffold.ts +4 -0
  149. package/src/runtime/mcp/handlers/mapo/tools/search-docs.ts +4 -0
  150. package/src/runtime/nitro/context.ts +41 -0
  151. package/src/runtime/nitro/to-mcp-prompt.ts +30 -0
  152. package/src/runtime/nitro/to-mcp-tool.ts +35 -0
  153. package/src/runtime/types/virtual-modules.d.ts +6 -0
@@ -0,0 +1,88 @@
1
+ import { RECIPES } from "./recipes.js";
2
+ import { getDoc, listDocs } from "./search.js";
3
+ export const DOCS_URI_PREFIX = "mapo://docs/";
4
+ export const FIELD_URI_PREFIX = "mapo://fields/";
5
+ export const INDEX_URI = "mapo://knowledge/index";
6
+ export const MANIFEST_URI = "mapo://app/manifest";
7
+ export function renderKnowledgeIndex(knowledge, api) {
8
+ const pages = listDocs(knowledge).map(
9
+ (doc) => `- \`${doc.path}\` \u2014 ${doc.title} (${doc.headings.length} sections)`
10
+ ).join("\n");
11
+ const recipes = RECIPES.map(
12
+ (recipe) => `- ${recipe.task} \u2192 \`${recipe.doc}\``
13
+ ).join("\n");
14
+ const components = api.components.map((component) => component.name).join(", ");
15
+ const fields = api.fieldTypes.map((field) => field.type).join(", ");
16
+ const composables = api.composables.map((composable) => composable.name).join(", ");
17
+ return [
18
+ "# Mapo knowledge base",
19
+ "",
20
+ `Generated ${knowledge.generatedAt}.`,
21
+ "",
22
+ "## Recipes",
23
+ recipes,
24
+ "",
25
+ "## Documentation pages",
26
+ pages,
27
+ "",
28
+ "## Components",
29
+ components,
30
+ "",
31
+ "## Field types",
32
+ fields,
33
+ "",
34
+ "## Auto-imported composables",
35
+ composables
36
+ ].join("\n");
37
+ }
38
+ export function renderDocResource(knowledge, path) {
39
+ const doc = getDoc(knowledge, path, { maxChars: 1e5 });
40
+ if (!doc) return null;
41
+ return `# ${doc.title}
42
+
43
+ source: \`${doc.path}\`
44
+
45
+ ${doc.content}`;
46
+ }
47
+ export function renderFieldResource(api, type) {
48
+ const field = api.fieldTypes.find((entry) => entry.type === type);
49
+ if (!field) return null;
50
+ const attrs = field.attrs.length ? field.attrs.map(
51
+ (attr) => `- \`${attr.name}\`${attr.type ? `: ${attr.type}` : ""}${attr.required ? " (required)" : ""}${attr.description ? ` \u2014 ${attr.description}` : ""}`
52
+ ).join("\n") : "_none_";
53
+ const common = api.fieldCommon.map((member) => `\`${member.name}\``).join(", ");
54
+ return [
55
+ `# Field type \`${field.type}\``,
56
+ "",
57
+ field.description ?? "",
58
+ "",
59
+ `- component: ${field.component ?? "(unmapped)"}`,
60
+ `- descriptor: ${field.descriptor ?? "(none)"}`,
61
+ field.defaultAttrs ? `- registry default attrs: \`${JSON.stringify(field.defaultAttrs)}\`` : "",
62
+ "",
63
+ "## attrs",
64
+ attrs,
65
+ "",
66
+ "## Shared descriptor properties",
67
+ common,
68
+ "",
69
+ field.docs.length ? `## Docs
70
+ ${field.docs.map((doc) => `- \`${doc}\``).join("\n")}` : ""
71
+ ].filter(Boolean).join("\n");
72
+ }
73
+ export function docResourceList(knowledge) {
74
+ return listDocs(knowledge).map((doc) => ({
75
+ uri: `${DOCS_URI_PREFIX}${doc.path}`,
76
+ name: doc.title,
77
+ description: `${doc.section} \xB7 ${doc.headings.slice(0, 5).join(", ")}`,
78
+ mimeType: "text/markdown"
79
+ }));
80
+ }
81
+ export function fieldResourceList(api) {
82
+ return api.fieldTypes.map((field) => ({
83
+ uri: `${FIELD_URI_PREFIX}${field.type}`,
84
+ name: `Field type: ${field.type}`,
85
+ description: field.description ?? `Rendered by ${field.component ?? "a custom component"}`,
86
+ mimeType: "text/markdown"
87
+ }));
88
+ }
File without changes
@@ -0,0 +1,64 @@
1
+ export class UnknownFieldTypeError extends Error {
2
+ constructor(type, available) {
3
+ super(
4
+ `Unknown field type "${type}". Registered types: ${available.join(", ")}. Custom types are added with defineFormField() \u2014 see uikit/form/registry.md.`
5
+ );
6
+ this.type = type;
7
+ this.available = available;
8
+ this.name = "UnknownFieldTypeError";
9
+ }
10
+ }
11
+ export function humanise(key) {
12
+ return key.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/\s+/g, " ").trim().toLowerCase().replace(/^./, (char) => char.toUpperCase());
13
+ }
14
+ export function parseFields(specs, api) {
15
+ const known = api ? new Set(api.fieldTypes.map((field) => field.type)) : null;
16
+ return specs.map((spec) => {
17
+ const [key = "", type = "text", ...rest] = spec.split(":");
18
+ if (!key.trim()) throw new Error(`Empty field key in "${spec}".`);
19
+ if (known && !known.has(type)) {
20
+ throw new UnknownFieldTypeError(type, [...known].sort());
21
+ }
22
+ return {
23
+ key: key.trim(),
24
+ type: type.trim(),
25
+ label: rest.join(":").trim() || humanise(key.trim())
26
+ };
27
+ });
28
+ }
29
+ function requiredAttrs(type, api) {
30
+ const field = api?.fieldTypes.find((entry) => entry.type === type);
31
+ return (field?.attrs ?? []).filter((attr) => attr.required).map((attr) => attr.name);
32
+ }
33
+ export function renderDescriptors(fields, api, indent = " ") {
34
+ return fields.map((field) => {
35
+ const attrs = requiredAttrs(field.type, api);
36
+ const attrsLine = attrs.length ? `
37
+ ${indent} attrs: { ${attrs.map((name) => `${name}: undefined /* TODO */`).join(", ")} },` : "";
38
+ return `${indent}{
39
+ ${indent} key: "${field.key}",
40
+ ${indent} type: "${field.type}",
41
+ ${indent} label: "${field.label}",${attrsLine}
42
+ ${indent}},`;
43
+ }).join("\n");
44
+ }
45
+ export function renderModel(fields) {
46
+ const tsType = (type) => {
47
+ if (["number", "slider"].includes(type)) return "number";
48
+ if (["boolean", "switch"].includes(type)) return "boolean";
49
+ if ([
50
+ "fks",
51
+ "m2m",
52
+ "media",
53
+ "media-m2m",
54
+ "enhanced-media",
55
+ "repeater",
56
+ "seo",
57
+ "map"
58
+ ].includes(type)) {
59
+ return "unknown";
60
+ }
61
+ return "string";
62
+ };
63
+ return fields.map((field) => ` ${field.key}: ${tsType(field.type)};`).join("\n");
64
+ }
File without changes
@@ -0,0 +1,74 @@
1
+ import { parseFields } from "./fields.js";
2
+ import * as templates from "./templates.js";
3
+ export const SCAFFOLD_KINDS = [
4
+ "list-page",
5
+ "detail-page",
6
+ "standalone-form",
7
+ "custom-field",
8
+ "login-page",
9
+ "theme-override",
10
+ "backend-proxy",
11
+ "menu-page",
12
+ "media-page"
13
+ ];
14
+ export const SCAFFOLD_DESCRIPTIONS = {
15
+ "list-page": "MapoList page with typed columns",
16
+ "detail-page": "MapoDetail page with field descriptors",
17
+ "standalone-form": "MapoForm driven by useCrud and your own submit handler",
18
+ "custom-field": "field component plus the plugin registering its type",
19
+ "login-page": "MapoLogin page wired to the configured auth endpoints",
20
+ "theme-override": "CSS token file plus the nuxt.config fragment that loads it",
21
+ "backend-proxy": "Nitro middleware proxying /api/* to a backend",
22
+ "menu-page": "MapoMenuManager page for a navigation tree",
23
+ "media-page": "MapoMediaManager page"
24
+ };
25
+ const RESOURCE_KINDS = /* @__PURE__ */ new Set([
26
+ "list-page",
27
+ "detail-page",
28
+ "standalone-form"
29
+ ]);
30
+ function toModelName(name) {
31
+ const pascal = name.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
32
+ if (/ies$/.test(pascal)) return `${pascal.slice(0, -3)}y`;
33
+ if (/(ses|xes|zes|ches|shes)$/.test(pascal)) return pascal.slice(0, -2);
34
+ if (/[^s]s$/.test(pascal)) return pascal.slice(0, -1);
35
+ return pascal;
36
+ }
37
+ export function scaffold(options) {
38
+ const name = (options.name ?? "items").trim().replace(/^\/+|\/+$/g, "");
39
+ const route = (options.route ?? `/${name}`).replace(/\/+$/, "");
40
+ const endpoint = (options.endpoint ?? `/api/${name}`).replace(/\/+$/, "");
41
+ const fields = RESOURCE_KINDS.has(options.kind) ? parseFields(
42
+ options.fields?.length ? options.fields : ["title:text"],
43
+ options.api
44
+ ) : [];
45
+ const input = {
46
+ name,
47
+ model: toModelName(name),
48
+ endpoint,
49
+ route,
50
+ fields,
51
+ ...options.api ? { api: options.api } : {}
52
+ };
53
+ switch (options.kind) {
54
+ case "list-page":
55
+ return templates.listPage(input);
56
+ case "detail-page":
57
+ return templates.detailPage(input);
58
+ case "standalone-form":
59
+ return templates.standaloneForm(input);
60
+ case "custom-field":
61
+ return templates.customField(input);
62
+ case "login-page":
63
+ return templates.loginPage();
64
+ case "theme-override":
65
+ return templates.themeOverride();
66
+ case "backend-proxy":
67
+ return templates.backendProxy(input);
68
+ case "menu-page":
69
+ return templates.menuPage(input);
70
+ case "media-page":
71
+ return templates.mediaPage(input);
72
+ }
73
+ }
74
+ export { UnknownFieldTypeError } from "./fields.js";
File without changes
@@ -0,0 +1,349 @@
1
+ import { renderDescriptors, renderModel } from "./fields.js";
2
+ const PAGE_META = (label, icon) => `definePageMeta({
3
+ layout: "mapo-default",
4
+ middleware: ["auth"],
5
+ label: "${label}",
6
+ icon: "${icon}",
7
+ });`;
8
+ export function listPage(input) {
9
+ const columns = input.fields.map(
10
+ (field) => ` { key: "${field.key}", label: "${field.label}", sortable: true },`
11
+ ).join("\n");
12
+ return {
13
+ files: [
14
+ {
15
+ path: `app/pages${input.route}/index.vue`,
16
+ content: `<script setup lang="ts">
17
+ import type { ListColumn } from "mapomodule/types";
18
+
19
+ ${PAGE_META(input.model + "s", "i-lucide-list")}
20
+
21
+ interface ${input.model} {
22
+ id: number;
23
+ ${renderModel(input.fields)}
24
+ }
25
+
26
+ const columns: ListColumn<${input.model}>[] = [
27
+ { key: "id", label: "ID", class: "w-14 font-mono text-xs text-muted" },
28
+ ${columns}
29
+ ];
30
+ <\/script>
31
+
32
+ <template>
33
+ <MapoList
34
+ endpoint="${input.endpoint}"
35
+ detail-base="${input.route}"
36
+ :columns="columns"
37
+ model-name="${input.model}"
38
+ />
39
+ </template>
40
+ `
41
+ }
42
+ ],
43
+ notes: [
44
+ `The list calls \`${input.endpoint}\` with \`?page=&search=&ordering=\` \u2014 the backend must paginate.`,
45
+ `Row clicks navigate to \`${input.route}/<id>\`; scaffold the detail page next.`
46
+ ],
47
+ docs: ["howto/crud-list.md", "uikit/list.md"]
48
+ };
49
+ }
50
+ export function detailPage(input) {
51
+ return {
52
+ files: [
53
+ {
54
+ path: `app/pages${input.route}/[id].vue`,
55
+ content: `<script setup lang="ts">
56
+ import type { FieldDescriptor } from "mapomodule/types";
57
+
58
+ ${PAGE_META(input.model, "i-lucide-file-pen")}
59
+
60
+ interface ${input.model} {
61
+ id: number;
62
+ ${renderModel(input.fields)}
63
+ }
64
+
65
+ const route = useRoute();
66
+ const id = computed(() => route.params.id as string);
67
+
68
+ const fields: FieldDescriptor<${input.model}>[] = [
69
+ ${renderDescriptors(input.fields, input.api)}
70
+ ];
71
+ <\/script>
72
+
73
+ <template>
74
+ <MapoDetail
75
+ :endpoint="'${input.endpoint}'"
76
+ :id="id"
77
+ :fields="fields"
78
+ model-name="${input.model}"
79
+ @saved="navigateTo('${input.route}')"
80
+ />
81
+ </template>
82
+ `
83
+ }
84
+ ],
85
+ notes: [
86
+ "`id` is `'new'` when creating: MapoDetail switches to POST on its own.",
87
+ "Move fields to `sidebarFields` to render them in the sticky right column."
88
+ ],
89
+ docs: ["howto/crud-detail.md", "uikit/detail.md"]
90
+ };
91
+ }
92
+ export function standaloneForm(input) {
93
+ return {
94
+ files: [
95
+ {
96
+ path: `app/pages${input.route}/form.vue`,
97
+ content: `<script setup lang="ts">
98
+ import type { FieldDescriptor } from "mapomodule/types";
99
+
100
+ ${PAGE_META(input.model + " form", "i-lucide-square-pen")}
101
+
102
+ interface ${input.model} {
103
+ ${renderModel(input.fields)}
104
+ }
105
+
106
+ const repository = useCrud<${input.model}>("${input.endpoint}");
107
+ const model = ref<${input.model}>({} as ${input.model});
108
+ const errors = ref<Record<string, string[]>>({});
109
+ const saving = ref(false);
110
+ const snack = useSnackStore();
111
+
112
+ const fields: FieldDescriptor<${input.model}>[] = [
113
+ ${renderDescriptors(input.fields, input.api)}
114
+ ];
115
+
116
+ async function save() {
117
+ saving.value = true;
118
+ errors.value = {};
119
+ try {
120
+ await repository.create(model.value);
121
+ snack.success("Saved");
122
+ } catch (error) {
123
+ // Mapo puts the backend payload on the error, so field errors map 1:1.
124
+ errors.value = (error as { data?: Record<string, string[]> }).data ?? {};
125
+ snack.error("Could not save");
126
+ } finally {
127
+ saving.value = false;
128
+ }
129
+ }
130
+ <\/script>
131
+
132
+ <template>
133
+ <div class="p-6 space-y-4">
134
+ <MapoForm v-model="model" :fields="fields" :errors="errors" />
135
+ <UButton :loading="saving" @click="save">Save</UButton>
136
+ </div>
137
+ </template>
138
+ `
139
+ }
140
+ ],
141
+ notes: [
142
+ "`useCrud` is auto-imported; no import statement is needed.",
143
+ "Use this when you own the submit flow \u2014 otherwise MapoDetail does it for you."
144
+ ],
145
+ docs: ["howto/form-standalone.md", "uikit/form/index.md"]
146
+ };
147
+ }
148
+ export function customField(input) {
149
+ const component = `${input.model}Field`;
150
+ const type = input.name;
151
+ return {
152
+ files: [
153
+ {
154
+ path: `app/components/${component}.vue`,
155
+ content: `<script setup lang="ts">
156
+ import type { CustomDescriptor } from "mapomodule/types";
157
+
158
+ // The contract a field component must implement \u2014 nothing more.
159
+ defineProps<{
160
+ modelValue: string | null;
161
+ descriptor: CustomDescriptor;
162
+ errors?: string[];
163
+ readonly?: boolean;
164
+ disabled?: boolean;
165
+ }>();
166
+
167
+ const emit = defineEmits<{ "update:modelValue": [value: string | null] }>();
168
+ <\/script>
169
+
170
+ <template>
171
+ <UFormField :label="descriptor.label" :error="errors?.[0]">
172
+ <UInput
173
+ :model-value="modelValue ?? ''"
174
+ :disabled="disabled || readonly"
175
+ @update:model-value="emit('update:modelValue', String($event) || null)"
176
+ />
177
+ </UFormField>
178
+ </template>
179
+ `
180
+ },
181
+ {
182
+ path: `app/plugins/${type}-field.ts`,
183
+ content: `export default defineNuxtPlugin(() => {
184
+ // Registers the type globally: any descriptor can now use \`type: "${type}"\`.
185
+ defineFormField("${type}", () => import("~/components/${component}.vue"), {
186
+ attrs: {},
187
+ });
188
+ });
189
+ `
190
+ }
191
+ ],
192
+ notes: [
193
+ `Use it with \`{ key: "\u2026", type: "${type}", label: "\u2026" }\`.`,
194
+ "Registering an existing type warns unless you pass `{ override: true }`.",
195
+ "Types added this way are invisible to `mapo_inspect_app`, which reads a build-time snapshot."
196
+ ],
197
+ docs: ["uikit/form/registry.md", "uikit/form/custom-fields.md"]
198
+ };
199
+ }
200
+ export function loginPage() {
201
+ return {
202
+ files: [
203
+ {
204
+ path: "app/pages/login.vue",
205
+ content: `<script setup lang="ts">
206
+ // The login page must opt out of the admin layout.
207
+ definePageMeta({ layout: false });
208
+ <\/script>
209
+
210
+ <template>
211
+ <MapoLogin />
212
+ </template>
213
+ `
214
+ }
215
+ ],
216
+ notes: [
217
+ "The path must match `mapo.loginUrl` (default `/login`), or the auth middleware redirects to a 404.",
218
+ "MapoLogin posts to `mapo.authLoginUrl` and then reads `mapo.userInfoApi`."
219
+ ],
220
+ docs: ["howto/auth-permissions.md", "uikit/login.md"]
221
+ };
222
+ }
223
+ export function themeOverride() {
224
+ return {
225
+ files: [
226
+ {
227
+ path: "app/assets/css/mapo.css",
228
+ content: `@import "tailwindcss";
229
+ @import "@nuxt/ui";
230
+
231
+ /* Mapo design tokens. Override only what you need: everything else keeps
232
+ the defaults shipped by @mapomodule/uikit. */
233
+ :root {
234
+ --ui-primary: var(--color-green-600);
235
+ --mapo-sidebar-width: 16rem;
236
+ --mapo-topbar-height: 64px;
237
+ }
238
+
239
+ .dark {
240
+ --ui-primary: var(--color-green-400);
241
+ }
242
+ `
243
+ },
244
+ {
245
+ path: "nuxt.config.snippet.ts",
246
+ content: `// Add to nuxt.config.ts \u2014 the CSS must go through the uikit module so
247
+ // Tailwind v4 and @nuxt/ui process it in the same pipeline.
248
+ export default defineNuxtConfig({
249
+ mapo: {
250
+ uikit: {
251
+ css: "~/assets/css/mapo.css",
252
+ ui: {
253
+ button: { defaultVariants: { size: "md" } },
254
+ },
255
+ },
256
+ },
257
+ });
258
+ `
259
+ }
260
+ ],
261
+ notes: [
262
+ "`nuxt.config.snippet.ts` is a fragment to merge by hand, not a file Nuxt loads.",
263
+ "To replace a whole component instead of restyling it, use the MapoOverride system."
264
+ ],
265
+ docs: ["howto/theming.md", "uikit/theming.md", "uikit/mapoverride.md"]
266
+ };
267
+ }
268
+ export function backendProxy(input) {
269
+ return {
270
+ files: [
271
+ {
272
+ path: "server/middleware/backend-proxy.ts",
273
+ content: `/**
274
+ * Proxies /api/* to the backend, keeping cookies on the app's own origin so
275
+ * the session survives without CORS.
276
+ */
277
+ export default defineEventHandler(async (event) => {
278
+ const url = getRequestURL(event);
279
+ if (!url.pathname.startsWith("/api/")) return;
280
+
281
+ const target = process.env.BACKEND_URL ?? "http://localhost:8000";
282
+
283
+ return proxyRequest(event, \`\${target}\${url.pathname}\${url.search}\`, {
284
+ // Forward the session cookie both ways.
285
+ cookieDomainRewrite: url.host,
286
+ headers: { host: new URL(target).host },
287
+ });
288
+ });
289
+ `
290
+ }
291
+ ],
292
+ notes: [
293
+ `Point \`mapo.authLoginUrl\`, \`mapo.userInfoApi\` and endpoints such as \`${input.endpoint}\` at the proxied paths.`,
294
+ "For a Django/DRF backend, CSRF needs the token header \u2014 see the recipe."
295
+ ],
296
+ docs: ["howto/backend-integration.md", "modules/camomilla.md"]
297
+ };
298
+ }
299
+ export function menuPage(input) {
300
+ return {
301
+ files: [
302
+ {
303
+ path: `app/pages${input.route}/[id].vue`,
304
+ content: `<script setup lang="ts">
305
+ ${PAGE_META("Menu", "i-lucide-menu")}
306
+
307
+ const route = useRoute();
308
+ const id = computed(() => route.params.id as string);
309
+ <\/script>
310
+
311
+ <template>
312
+ <MapoMenuManager
313
+ :endpoint="'${input.endpoint}'"
314
+ :id="id"
315
+ page-types-endpoint="${input.endpoint}/page_types"
316
+ />
317
+ </template>
318
+ `
319
+ }
320
+ ],
321
+ notes: [
322
+ "The backend must expose the menu tree and the available page types.",
323
+ "Nodes are reordered by drag & drop; the tree is saved as a whole."
324
+ ],
325
+ docs: ["howto/menu-manager.md", "uikit/menu-manager.md"]
326
+ };
327
+ }
328
+ export function mediaPage(input) {
329
+ return {
330
+ files: [
331
+ {
332
+ path: `app/pages${input.route}/index.vue`,
333
+ content: `<script setup lang="ts">
334
+ ${PAGE_META("Media", "i-lucide-image")}
335
+ <\/script>
336
+
337
+ <template>
338
+ <MapoMediaManager />
339
+ </template>
340
+ `
341
+ }
342
+ ],
343
+ notes: [
344
+ "Configure `mapo.uikit.media.endpoints` unless an integration already serves them.",
345
+ "In a form, pick media with the `media`, `media-m2m` or `enhanced-media` field types."
346
+ ],
347
+ docs: ["howto/media-manager.md", "uikit/media.md"]
348
+ };
349
+ }
File without changes
@@ -0,0 +1,70 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ const CACHE_TTL_MS = 6e4;
4
+ const cache = /* @__PURE__ */ new Map();
5
+ export class SchemaUnavailableError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "SchemaUnavailableError";
9
+ }
10
+ }
11
+ function parseDocument(raw, origin) {
12
+ const trimmed = raw.trimStart();
13
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
14
+ const looksLikeYaml = /^openapi:\s/m.test(trimmed);
15
+ throw new SchemaUnavailableError(
16
+ looksLikeYaml ? `${origin} returned YAML. Request JSON instead \u2014 drf-spectacular accepts \`?format=json\`.` : `${origin} did not return JSON (the response starts with "${trimmed.slice(0, 30)}\u2026"). An HTML page usually means the schema endpoint requires authentication.`
17
+ );
18
+ }
19
+ try {
20
+ return JSON.parse(raw);
21
+ } catch (error) {
22
+ throw new SchemaUnavailableError(
23
+ `${origin} returned malformed JSON: ${error instanceof Error ? error.message : String(error)}`
24
+ );
25
+ }
26
+ }
27
+ async function fetchDocument(url, token) {
28
+ let response;
29
+ try {
30
+ response = await fetch(url, {
31
+ headers: {
32
+ accept: "application/json",
33
+ ...token ? { authorization: `Bearer ${token}` } : {}
34
+ }
35
+ });
36
+ } catch (error) {
37
+ throw new SchemaUnavailableError(
38
+ `Could not reach ${url} (${error instanceof Error ? error.message : String(error)}). Is the backend running?`
39
+ );
40
+ }
41
+ if (!response.ok) {
42
+ const hint = response.status === 401 || response.status === 403 ? " The schema endpoint needs credentials: set the token env var declared in `mapo.mcp.backend.tokenEnv`." : "";
43
+ throw new SchemaUnavailableError(
44
+ `${url} answered ${response.status}.${hint}`
45
+ );
46
+ }
47
+ return parseDocument(await response.text(), url);
48
+ }
49
+ function readDocument(path, rootDir) {
50
+ const absolute = isAbsolute(path) ? path : resolve(rootDir ?? process.cwd(), path);
51
+ if (!existsSync(absolute)) {
52
+ throw new SchemaUnavailableError(`No schema file at ${absolute}.`);
53
+ }
54
+ return parseDocument(readFileSync(absolute, "utf-8"), absolute);
55
+ }
56
+ export async function loadOpenApiDocument(source, { token = null, rootDir = null } = {}) {
57
+ const cached = cache.get(source);
58
+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.document;
59
+ const document = /^https?:\/\//i.test(source) ? await fetchDocument(source, token) : readDocument(source, rootDir);
60
+ if (!document.components?.schemas) {
61
+ throw new SchemaUnavailableError(
62
+ `${source} is not an OpenAPI document with \`components.schemas\` (found keys: ${Object.keys(document).join(", ") || "none"}).`
63
+ );
64
+ }
65
+ cache.set(source, { at: Date.now(), document });
66
+ return document;
67
+ }
68
+ export function clearSchemaCache() {
69
+ cache.clear();
70
+ }
File without changes