@mapomodule/mcp 0.0.0-stage → 1.0.0-beta.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.
Files changed (166) hide show
  1. package/README.md +509 -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 +274 -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 +124 -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/endpoint.d.ts +0 -0
  21. package/dist/runtime/core/endpoint.js +8 -0
  22. package/dist/runtime/core/indexer.d.ts +0 -0
  23. package/dist/runtime/core/indexer.js +194 -0
  24. package/dist/runtime/core/instructions.d.ts +0 -0
  25. package/dist/runtime/core/instructions.js +10 -0
  26. package/dist/runtime/core/knowledge.d.ts +0 -0
  27. package/dist/runtime/core/knowledge.js +76 -0
  28. package/dist/runtime/core/openapi.d.ts +0 -0
  29. package/dist/runtime/core/openapi.js +229 -0
  30. package/dist/runtime/core/overview.d.ts +0 -0
  31. package/dist/runtime/core/overview.js +15 -0
  32. package/dist/runtime/core/prompts.d.ts +0 -0
  33. package/dist/runtime/core/prompts.js +108 -0
  34. package/dist/runtime/core/recipes.d.ts +0 -0
  35. package/dist/runtime/core/recipes.js +496 -0
  36. package/dist/runtime/core/resources.d.ts +0 -0
  37. package/dist/runtime/core/resources.js +92 -0
  38. package/dist/runtime/core/scaffold/fields.d.ts +0 -0
  39. package/dist/runtime/core/scaffold/fields.js +64 -0
  40. package/dist/runtime/core/scaffold/index.d.ts +0 -0
  41. package/dist/runtime/core/scaffold/index.js +74 -0
  42. package/dist/runtime/core/scaffold/templates.d.ts +0 -0
  43. package/dist/runtime/core/scaffold/templates.js +349 -0
  44. package/dist/runtime/core/schema-source.d.ts +0 -0
  45. package/dist/runtime/core/schema-source.js +70 -0
  46. package/dist/runtime/core/search.d.ts +0 -0
  47. package/dist/runtime/core/search.js +173 -0
  48. package/dist/runtime/core/tokenize.d.ts +0 -0
  49. package/dist/runtime/core/tokenize.js +96 -0
  50. package/dist/runtime/core/tool-spec.d.ts +0 -0
  51. package/dist/runtime/core/tool-spec.js +3 -0
  52. package/dist/runtime/core/tools/api.d.ts +0 -0
  53. package/dist/runtime/core/tools/api.js +192 -0
  54. package/dist/runtime/core/tools/app.d.ts +0 -0
  55. package/dist/runtime/core/tools/app.js +141 -0
  56. package/dist/runtime/core/tools/backend.d.ts +0 -0
  57. package/dist/runtime/core/tools/backend.js +143 -0
  58. package/dist/runtime/core/tools/docs.d.ts +0 -0
  59. package/dist/runtime/core/tools/docs.js +154 -0
  60. package/dist/runtime/core/tools/scaffold.d.ts +0 -0
  61. package/dist/runtime/core/tools/scaffold.js +127 -0
  62. package/dist/runtime/core/types.d.ts +0 -0
  63. package/dist/runtime/core/types.js +0 -0
  64. package/dist/runtime/core/write.d.ts +0 -0
  65. package/dist/runtime/core/write.js +53 -0
  66. package/dist/runtime/mcp/handlers/mapo/index.js +7 -0
  67. package/dist/runtime/mcp/handlers/mapo/prompts/crud-page.js +3 -0
  68. package/dist/runtime/mcp/handlers/mapo/prompts/custom-field.js +3 -0
  69. package/dist/runtime/mcp/handlers/mapo/prompts/debug-form.js +3 -0
  70. package/dist/runtime/mcp/handlers/mapo/prompts/migrate-v1.js +3 -0
  71. package/dist/runtime/mcp/handlers/mapo/prompts/theme.js +3 -0
  72. package/dist/runtime/mcp/handlers/mapo/resources/app-manifest.js +19 -0
  73. package/dist/runtime/mcp/handlers/mapo/resources/docs.js +34 -0
  74. package/dist/runtime/mcp/handlers/mapo/resources/fields.js +34 -0
  75. package/dist/runtime/mcp/handlers/mapo/resources/knowledge-index.js +22 -0
  76. package/dist/runtime/mcp/handlers/mapo/resources/overview.js +20 -0
  77. package/dist/runtime/mcp/handlers/mapo/tools/backend-schema.js +3 -0
  78. package/dist/runtime/mcp/handlers/mapo/tools/component-api.js +3 -0
  79. package/dist/runtime/mcp/handlers/mapo/tools/composable-api.js +3 -0
  80. package/dist/runtime/mcp/handlers/mapo/tools/doctor.js +3 -0
  81. package/dist/runtime/mcp/handlers/mapo/tools/get-doc.js +3 -0
  82. package/dist/runtime/mcp/handlers/mapo/tools/inspect-app.js +3 -0
  83. package/dist/runtime/mcp/handlers/mapo/tools/list-field-types.js +3 -0
  84. package/dist/runtime/mcp/handlers/mapo/tools/list-recipes.js +3 -0
  85. package/dist/runtime/mcp/handlers/mapo/tools/scaffold.js +3 -0
  86. package/dist/runtime/mcp/handlers/mapo/tools/search-docs.js +3 -0
  87. package/dist/runtime/nitro/context.d.ts +0 -0
  88. package/dist/runtime/nitro/context.js +21 -0
  89. package/dist/runtime/nitro/to-mcp-prompt.d.ts +0 -0
  90. package/dist/runtime/nitro/to-mcp-prompt.js +23 -0
  91. package/dist/runtime/nitro/to-mcp-tool.d.ts +0 -0
  92. package/dist/runtime/nitro/to-mcp-tool.js +28 -0
  93. package/dist/runtime/types/virtual-modules.d.ts +6 -0
  94. package/dist/types.d.mts +9 -0
  95. package/package.json +73 -4
  96. package/src/__tests__/cli.test.ts +137 -0
  97. package/src/__tests__/doctor.test.ts +145 -0
  98. package/src/__tests__/endpoint.test.ts +31 -0
  99. package/src/__tests__/fixtures/drf-schema.json +142 -0
  100. package/src/__tests__/fixtures.ts +198 -0
  101. package/src/__tests__/indexer.test.ts +114 -0
  102. package/src/__tests__/knowledge.test.ts +225 -0
  103. package/src/__tests__/openapi.test.ts +256 -0
  104. package/src/__tests__/overview.test.ts +105 -0
  105. package/src/__tests__/recipes.test.ts +55 -0
  106. package/src/__tests__/resources.test.ts +69 -0
  107. package/src/__tests__/scaffold.test.ts +153 -0
  108. package/src/__tests__/search.test.ts +105 -0
  109. package/src/__tests__/tools.test.ts +226 -0
  110. package/src/__tests__/write.test.ts +134 -0
  111. package/src/build/extract-components.ts +135 -0
  112. package/src/build/extract-composables.ts +125 -0
  113. package/src/build/extract-fields.ts +250 -0
  114. package/src/build/index.ts +103 -0
  115. package/src/cli.ts +375 -0
  116. package/src/index.ts +65 -0
  117. package/src/module.ts +213 -0
  118. package/src/runtime/core/doctor.ts +204 -0
  119. package/src/runtime/core/endpoint.ts +27 -0
  120. package/src/runtime/core/indexer.ts +285 -0
  121. package/src/runtime/core/instructions.ts +18 -0
  122. package/src/runtime/core/knowledge.ts +121 -0
  123. package/src/runtime/core/openapi.ts +417 -0
  124. package/src/runtime/core/overview.ts +44 -0
  125. package/src/runtime/core/prompts.ts +150 -0
  126. package/src/runtime/core/recipes.ts +574 -0
  127. package/src/runtime/core/resources.ts +150 -0
  128. package/src/runtime/core/scaffold/fields.ts +127 -0
  129. package/src/runtime/core/scaffold/index.ts +120 -0
  130. package/src/runtime/core/scaffold/templates.ts +394 -0
  131. package/src/runtime/core/schema-source.ts +123 -0
  132. package/src/runtime/core/search.ts +282 -0
  133. package/src/runtime/core/tokenize.ts +146 -0
  134. package/src/runtime/core/tool-spec.ts +74 -0
  135. package/src/runtime/core/tools/api.ts +300 -0
  136. package/src/runtime/core/tools/app.ts +201 -0
  137. package/src/runtime/core/tools/backend.ts +197 -0
  138. package/src/runtime/core/tools/docs.ts +218 -0
  139. package/src/runtime/core/tools/scaffold.ts +176 -0
  140. package/src/runtime/core/types.ts +133 -0
  141. package/src/runtime/core/write.ts +119 -0
  142. package/src/runtime/mcp/handlers/mapo/index.ts +16 -0
  143. package/src/runtime/mcp/handlers/mapo/prompts/crud-page.ts +4 -0
  144. package/src/runtime/mcp/handlers/mapo/prompts/custom-field.ts +4 -0
  145. package/src/runtime/mcp/handlers/mapo/prompts/debug-form.ts +4 -0
  146. package/src/runtime/mcp/handlers/mapo/prompts/migrate-v1.ts +4 -0
  147. package/src/runtime/mcp/handlers/mapo/prompts/theme.ts +4 -0
  148. package/src/runtime/mcp/handlers/mapo/resources/app-manifest.ts +28 -0
  149. package/src/runtime/mcp/handlers/mapo/resources/docs.ts +41 -0
  150. package/src/runtime/mcp/handlers/mapo/resources/fields.ts +37 -0
  151. package/src/runtime/mcp/handlers/mapo/resources/knowledge-index.ts +24 -0
  152. package/src/runtime/mcp/handlers/mapo/resources/overview.ts +22 -0
  153. package/src/runtime/mcp/handlers/mapo/tools/backend-schema.ts +4 -0
  154. package/src/runtime/mcp/handlers/mapo/tools/component-api.ts +4 -0
  155. package/src/runtime/mcp/handlers/mapo/tools/composable-api.ts +4 -0
  156. package/src/runtime/mcp/handlers/mapo/tools/doctor.ts +4 -0
  157. package/src/runtime/mcp/handlers/mapo/tools/get-doc.ts +4 -0
  158. package/src/runtime/mcp/handlers/mapo/tools/inspect-app.ts +4 -0
  159. package/src/runtime/mcp/handlers/mapo/tools/list-field-types.ts +4 -0
  160. package/src/runtime/mcp/handlers/mapo/tools/list-recipes.ts +4 -0
  161. package/src/runtime/mcp/handlers/mapo/tools/scaffold.ts +4 -0
  162. package/src/runtime/mcp/handlers/mapo/tools/search-docs.ts +4 -0
  163. package/src/runtime/nitro/context.ts +41 -0
  164. package/src/runtime/nitro/to-mcp-prompt.ts +30 -0
  165. package/src/runtime/nitro/to-mcp-tool.ts +35 -0
  166. package/src/runtime/types/virtual-modules.d.ts +6 -0
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Scaffold templates.
3
+ *
4
+ * Modelled on the canonical recipes in `docs/howto/` and on the pages that
5
+ * actually run in `apps/example-e2e`, so the generated code compiles and works
6
+ * as-is. Types are imported from `mapomodule/types`, the aggregate a consuming
7
+ * app installs.
8
+ */
9
+ import { renderDescriptors, renderModel } from "./fields.js";
10
+ import type { ParsedField } from "./fields.js";
11
+ import type { ApiKnowledge } from "../types.js";
12
+
13
+ export interface TemplateInput {
14
+ /** Resource name in kebab/snake, e.g. `articles`. */
15
+ name: string;
16
+ /** PascalCase singular, e.g. `Article`. */
17
+ model: string;
18
+ /** REST endpoint, e.g. `/api/articles`. */
19
+ endpoint: string;
20
+ /** Route base, e.g. `/articles`. */
21
+ route: string;
22
+ fields: ParsedField[];
23
+ api?: ApiKnowledge;
24
+ }
25
+
26
+ export interface TemplateOutput {
27
+ files: Array<{ path: string; content: string }>;
28
+ notes: string[];
29
+ docs: string[];
30
+ }
31
+
32
+ const PAGE_META = (label: string, icon: string) =>
33
+ `definePageMeta({
34
+ layout: "mapo-default",
35
+ middleware: ["auth"],
36
+ label: "${label}",
37
+ icon: "${icon}",
38
+ });`;
39
+
40
+ export function listPage(input: TemplateInput): TemplateOutput {
41
+ const columns = input.fields
42
+ .map(
43
+ (field) =>
44
+ ` { key: "${field.key}", label: "${field.label}", sortable: true },`,
45
+ )
46
+ .join("\n");
47
+
48
+ return {
49
+ files: [
50
+ {
51
+ path: `app/pages${input.route}/index.vue`,
52
+ content: `<script setup lang="ts">
53
+ import type { ListColumn } from "mapomodule/types";
54
+
55
+ ${PAGE_META(input.model + "s", "i-lucide-list")}
56
+
57
+ interface ${input.model} {
58
+ id: number;
59
+ ${renderModel(input.fields)}
60
+ }
61
+
62
+ const columns: ListColumn<${input.model}>[] = [
63
+ { key: "id", label: "ID", class: "w-14 font-mono text-xs text-muted" },
64
+ ${columns}
65
+ ];
66
+ </script>
67
+
68
+ <template>
69
+ <MapoList
70
+ endpoint="${input.endpoint}"
71
+ detail-base="${input.route}"
72
+ :columns="columns"
73
+ model-name="${input.model}"
74
+ />
75
+ </template>
76
+ `,
77
+ },
78
+ ],
79
+ notes: [
80
+ `The list calls \`${input.endpoint}\` with \`?page=&search=&ordering=\` — the backend must paginate.`,
81
+ `Row clicks navigate to \`${input.route}/<id>\`; scaffold the detail page next.`,
82
+ ],
83
+ docs: ["howto/crud-list.md", "uikit/list.md"],
84
+ };
85
+ }
86
+
87
+ export function detailPage(input: TemplateInput): TemplateOutput {
88
+ return {
89
+ files: [
90
+ {
91
+ path: `app/pages${input.route}/[id].vue`,
92
+ content: `<script setup lang="ts">
93
+ import type { FieldDescriptor } from "mapomodule/types";
94
+
95
+ ${PAGE_META(input.model, "i-lucide-file-pen")}
96
+
97
+ interface ${input.model} {
98
+ id: number;
99
+ ${renderModel(input.fields)}
100
+ }
101
+
102
+ const route = useRoute();
103
+ const id = computed(() => route.params.id as string);
104
+
105
+ const fields: FieldDescriptor<${input.model}>[] = [
106
+ ${renderDescriptors(input.fields, input.api)}
107
+ ];
108
+ </script>
109
+
110
+ <template>
111
+ <MapoDetail
112
+ :endpoint="'${input.endpoint}'"
113
+ :id="id"
114
+ :fields="fields"
115
+ model-name="${input.model}"
116
+ @saved="navigateTo('${input.route}')"
117
+ />
118
+ </template>
119
+ `,
120
+ },
121
+ ],
122
+ notes: [
123
+ "`id` is `'new'` when creating: MapoDetail switches to POST on its own.",
124
+ "Move fields to `sidebarFields` to render them in the sticky right column.",
125
+ ],
126
+ docs: ["howto/crud-detail.md", "uikit/detail.md"],
127
+ };
128
+ }
129
+
130
+ export function standaloneForm(input: TemplateInput): TemplateOutput {
131
+ return {
132
+ files: [
133
+ {
134
+ path: `app/pages${input.route}/form.vue`,
135
+ content: `<script setup lang="ts">
136
+ import type { FieldDescriptor } from "mapomodule/types";
137
+
138
+ ${PAGE_META(input.model + " form", "i-lucide-square-pen")}
139
+
140
+ interface ${input.model} {
141
+ ${renderModel(input.fields)}
142
+ }
143
+
144
+ const repository = useCrud<${input.model}>("${input.endpoint}");
145
+ const model = ref<${input.model}>({} as ${input.model});
146
+ const errors = ref<Record<string, string[]>>({});
147
+ const saving = ref(false);
148
+ const snack = useSnackStore();
149
+
150
+ const fields: FieldDescriptor<${input.model}>[] = [
151
+ ${renderDescriptors(input.fields, input.api)}
152
+ ];
153
+
154
+ async function save() {
155
+ saving.value = true;
156
+ errors.value = {};
157
+ try {
158
+ await repository.create(model.value);
159
+ snack.success("Saved");
160
+ } catch (error) {
161
+ // Mapo puts the backend payload on the error, so field errors map 1:1.
162
+ errors.value = (error as { data?: Record<string, string[]> }).data ?? {};
163
+ snack.error("Could not save");
164
+ } finally {
165
+ saving.value = false;
166
+ }
167
+ }
168
+ </script>
169
+
170
+ <template>
171
+ <div class="p-6 space-y-4">
172
+ <MapoForm v-model="model" :fields="fields" :errors="errors" />
173
+ <UButton :loading="saving" @click="save">Save</UButton>
174
+ </div>
175
+ </template>
176
+ `,
177
+ },
178
+ ],
179
+ notes: [
180
+ "`useCrud` is auto-imported; no import statement is needed.",
181
+ "Use this when you own the submit flow — otherwise MapoDetail does it for you.",
182
+ ],
183
+ docs: ["howto/form-standalone.md", "uikit/form/index.md"],
184
+ };
185
+ }
186
+
187
+ export function customField(input: TemplateInput): TemplateOutput {
188
+ const component = `${input.model}Field`;
189
+ const type = input.name;
190
+
191
+ return {
192
+ files: [
193
+ {
194
+ path: `app/components/${component}.vue`,
195
+ content: `<script setup lang="ts">
196
+ import type { CustomDescriptor } from "mapomodule/types";
197
+
198
+ // The contract a field component must implement — nothing more.
199
+ defineProps<{
200
+ modelValue: string | null;
201
+ descriptor: CustomDescriptor;
202
+ errors?: string[];
203
+ readonly?: boolean;
204
+ disabled?: boolean;
205
+ }>();
206
+
207
+ const emit = defineEmits<{ "update:modelValue": [value: string | null] }>();
208
+ </script>
209
+
210
+ <template>
211
+ <UFormField :label="descriptor.label" :error="errors?.[0]">
212
+ <UInput
213
+ :model-value="modelValue ?? ''"
214
+ :disabled="disabled || readonly"
215
+ @update:model-value="emit('update:modelValue', String($event) || null)"
216
+ />
217
+ </UFormField>
218
+ </template>
219
+ `,
220
+ },
221
+ {
222
+ path: `app/plugins/${type}-field.ts`,
223
+ content: `export default defineNuxtPlugin(() => {
224
+ // Registers the type globally: any descriptor can now use \`type: "${type}"\`.
225
+ defineFormField("${type}", () => import("~/components/${component}.vue"), {
226
+ attrs: {},
227
+ });
228
+ });
229
+ `,
230
+ },
231
+ ],
232
+ notes: [
233
+ `Use it with \`{ key: "…", type: "${type}", label: "…" }\`.`,
234
+ "Registering an existing type warns unless you pass `{ override: true }`.",
235
+ "Types added this way are invisible to `mapo_inspect_app`, which reads a build-time snapshot.",
236
+ ],
237
+ docs: ["uikit/form/registry.md", "uikit/form/custom-fields.md"],
238
+ };
239
+ }
240
+
241
+ export function loginPage(): TemplateOutput {
242
+ return {
243
+ files: [
244
+ {
245
+ path: "app/pages/login.vue",
246
+ content: `<script setup lang="ts">
247
+ // The login page must opt out of the admin layout.
248
+ definePageMeta({ layout: false });
249
+ </script>
250
+
251
+ <template>
252
+ <MapoLogin />
253
+ </template>
254
+ `,
255
+ },
256
+ ],
257
+ notes: [
258
+ "The path must match `mapo.loginUrl` (default `/login`), or the auth middleware redirects to a 404.",
259
+ "MapoLogin posts to `mapo.authLoginUrl` and then reads `mapo.userInfoApi`.",
260
+ ],
261
+ docs: ["howto/auth-permissions.md", "uikit/login.md"],
262
+ };
263
+ }
264
+
265
+ export function themeOverride(): TemplateOutput {
266
+ return {
267
+ files: [
268
+ {
269
+ path: "app/assets/css/mapo.css",
270
+ content: `@import "tailwindcss";
271
+ @import "@nuxt/ui";
272
+
273
+ /* Mapo design tokens. Override only what you need: everything else keeps
274
+ the defaults shipped by @mapomodule/uikit. */
275
+ :root {
276
+ --ui-primary: var(--color-green-600);
277
+ --mapo-sidebar-width: 16rem;
278
+ --mapo-topbar-height: 64px;
279
+ }
280
+
281
+ .dark {
282
+ --ui-primary: var(--color-green-400);
283
+ }
284
+ `,
285
+ },
286
+ {
287
+ path: "nuxt.config.snippet.ts",
288
+ content: `// Add to nuxt.config.ts — the CSS must go through the uikit module so
289
+ // Tailwind v4 and @nuxt/ui process it in the same pipeline.
290
+ export default defineNuxtConfig({
291
+ mapo: {
292
+ uikit: {
293
+ css: "~/assets/css/mapo.css",
294
+ ui: {
295
+ button: { defaultVariants: { size: "md" } },
296
+ },
297
+ },
298
+ },
299
+ });
300
+ `,
301
+ },
302
+ ],
303
+ notes: [
304
+ "`nuxt.config.snippet.ts` is a fragment to merge by hand, not a file Nuxt loads.",
305
+ "To replace a whole component instead of restyling it, use the MapoOverride system.",
306
+ ],
307
+ docs: ["howto/theming.md", "uikit/theming.md", "uikit/mapoverride.md"],
308
+ };
309
+ }
310
+
311
+ export function backendProxy(input: TemplateInput): TemplateOutput {
312
+ return {
313
+ files: [
314
+ {
315
+ path: "server/middleware/backend-proxy.ts",
316
+ content: `/**
317
+ * Proxies /api/* to the backend, keeping cookies on the app's own origin so
318
+ * the session survives without CORS.
319
+ */
320
+ export default defineEventHandler(async (event) => {
321
+ const url = getRequestURL(event);
322
+ if (!url.pathname.startsWith("/api/")) return;
323
+
324
+ const target = process.env.BACKEND_URL ?? "http://localhost:8000";
325
+
326
+ return proxyRequest(event, \`\${target}\${url.pathname}\${url.search}\`, {
327
+ // Forward the session cookie both ways.
328
+ cookieDomainRewrite: url.host,
329
+ headers: { host: new URL(target).host },
330
+ });
331
+ });
332
+ `,
333
+ },
334
+ ],
335
+ notes: [
336
+ `Point \`mapo.authLoginUrl\`, \`mapo.userInfoApi\` and endpoints such as \`${input.endpoint}\` at the proxied paths.`,
337
+ "For a Django/DRF backend, CSRF needs the token header — see the recipe.",
338
+ ],
339
+ docs: ["howto/backend-integration.md", "modules/camomilla.md"],
340
+ };
341
+ }
342
+
343
+ export function menuPage(input: TemplateInput): TemplateOutput {
344
+ return {
345
+ files: [
346
+ {
347
+ path: `app/pages${input.route}/[id].vue`,
348
+ content: `<script setup lang="ts">
349
+ ${PAGE_META("Menu", "i-lucide-menu")}
350
+
351
+ const route = useRoute();
352
+ const id = computed(() => route.params.id as string);
353
+ </script>
354
+
355
+ <template>
356
+ <MapoMenuManager
357
+ :endpoint="'${input.endpoint}'"
358
+ :id="id"
359
+ page-types-endpoint="${input.endpoint}/page_types"
360
+ />
361
+ </template>
362
+ `,
363
+ },
364
+ ],
365
+ notes: [
366
+ "The backend must expose the menu tree and the available page types.",
367
+ "Nodes are reordered by drag & drop; the tree is saved as a whole.",
368
+ ],
369
+ docs: ["howto/menu-manager.md", "uikit/menu-manager.md"],
370
+ };
371
+ }
372
+
373
+ export function mediaPage(input: TemplateInput): TemplateOutput {
374
+ return {
375
+ files: [
376
+ {
377
+ path: `app/pages${input.route}/index.vue`,
378
+ content: `<script setup lang="ts">
379
+ ${PAGE_META("Media", "i-lucide-image")}
380
+ </script>
381
+
382
+ <template>
383
+ <MapoMediaManager />
384
+ </template>
385
+ `,
386
+ },
387
+ ],
388
+ notes: [
389
+ "Configure `mapo.uikit.media.endpoints` unless an integration already serves them.",
390
+ "In a form, pick media with the `media`, `media-m2m` or `enhanced-media` field types.",
391
+ ],
392
+ docs: ["howto/media-manager.md", "uikit/media.md"],
393
+ };
394
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Loads an OpenAPI document from a URL or a local file.
3
+ *
4
+ * Isolated from the mapping so the mapping stays pure, and from the tool so the
5
+ * failure modes — unreachable backend, HTML login page instead of JSON, YAML
6
+ * where JSON was expected — can be reported in a way the caller can act on.
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { isAbsolute, resolve } from "node:path";
10
+ import type { OpenApiDocument } from "./openapi.js";
11
+
12
+ /** Documents change rarely during a session; re-fetching on every call is rude. */
13
+ const CACHE_TTL_MS = 60_000;
14
+
15
+ const cache = new Map<string, { at: number; document: OpenApiDocument }>();
16
+
17
+ export class SchemaUnavailableError extends Error {
18
+ constructor(message: string) {
19
+ super(message);
20
+ this.name = "SchemaUnavailableError";
21
+ }
22
+ }
23
+
24
+ function parseDocument(raw: string, origin: string): OpenApiDocument {
25
+ const trimmed = raw.trimStart();
26
+
27
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
28
+ // drf-spectacular serves YAML by default; JSON is one query param away.
29
+ const looksLikeYaml = /^openapi:\s/m.test(trimmed);
30
+ throw new SchemaUnavailableError(
31
+ looksLikeYaml
32
+ ? `${origin} returned YAML. Request JSON instead — drf-spectacular accepts \`?format=json\`.`
33
+ : `${origin} did not return JSON (the response starts with "${trimmed.slice(0, 30)}…"). ` +
34
+ "An HTML page usually means the schema endpoint requires authentication.",
35
+ );
36
+ }
37
+
38
+ try {
39
+ return JSON.parse(raw) as OpenApiDocument;
40
+ } catch (error) {
41
+ throw new SchemaUnavailableError(
42
+ `${origin} returned malformed JSON: ${error instanceof Error ? error.message : String(error)}`,
43
+ );
44
+ }
45
+ }
46
+
47
+ async function fetchDocument(
48
+ url: string,
49
+ token: string | null,
50
+ ): Promise<OpenApiDocument> {
51
+ let response: Response;
52
+ try {
53
+ response = await fetch(url, {
54
+ headers: {
55
+ accept: "application/json",
56
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
57
+ },
58
+ });
59
+ } catch (error) {
60
+ throw new SchemaUnavailableError(
61
+ `Could not reach ${url} (${error instanceof Error ? error.message : String(error)}). ` +
62
+ "Is the backend running?",
63
+ );
64
+ }
65
+
66
+ if (!response.ok) {
67
+ const hint =
68
+ response.status === 401 || response.status === 403
69
+ ? " The schema endpoint needs credentials: set the token env var declared in `mapo.mcp.backend.tokenEnv`."
70
+ : "";
71
+ throw new SchemaUnavailableError(
72
+ `${url} answered ${response.status}.${hint}`,
73
+ );
74
+ }
75
+
76
+ return parseDocument(await response.text(), url);
77
+ }
78
+
79
+ function readDocument(path: string, rootDir: string | null): OpenApiDocument {
80
+ const absolute = isAbsolute(path)
81
+ ? path
82
+ : resolve(rootDir ?? process.cwd(), path);
83
+ if (!existsSync(absolute)) {
84
+ throw new SchemaUnavailableError(`No schema file at ${absolute}.`);
85
+ }
86
+ return parseDocument(readFileSync(absolute, "utf-8"), absolute);
87
+ }
88
+
89
+ export interface LoadSchemaOptions {
90
+ token?: string | null;
91
+ /** Base for relative file paths. */
92
+ rootDir?: string | null;
93
+ }
94
+
95
+ /**
96
+ * `source` is an http(s) URL or a path. Supporting a file means a team can
97
+ * commit an exported schema and work offline, which is also how this is tested.
98
+ */
99
+ export async function loadOpenApiDocument(
100
+ source: string,
101
+ { token = null, rootDir = null }: LoadSchemaOptions = {},
102
+ ): Promise<OpenApiDocument> {
103
+ const cached = cache.get(source);
104
+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.document;
105
+
106
+ const document = /^https?:\/\//i.test(source)
107
+ ? await fetchDocument(source, token)
108
+ : readDocument(source, rootDir);
109
+
110
+ if (!document.components?.schemas) {
111
+ throw new SchemaUnavailableError(
112
+ `${source} is not an OpenAPI document with \`components.schemas\` (found keys: ${Object.keys(document).join(", ") || "none"}).`,
113
+ );
114
+ }
115
+
116
+ cache.set(source, { at: Date.now(), document });
117
+ return document;
118
+ }
119
+
120
+ /** Test helper. */
121
+ export function clearSchemaCache(): void {
122
+ cache.clear();
123
+ }