@plugmatica/plugin-build 0.0.0-stage → 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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/README.md +221 -2
  4. package/dev-target/README.md +20 -0
  5. package/dev-target/compose.yaml +119 -0
  6. package/dist/chunk-EOLUQEKQ.js +587 -0
  7. package/dist/chunk-QHTGR4ZB.js +9378 -0
  8. package/dist/chunk-TQNG5OZ3.js +3135 -0
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +2606 -0
  11. package/dist/index.d.ts +2144 -0
  12. package/dist/index.js +230 -0
  13. package/dist/vite-WRwB4IG8.d.ts +929 -0
  14. package/dist/vite.d.ts +3 -0
  15. package/dist/vite.js +20 -0
  16. package/package.json +94 -4
  17. package/templates/README.md +29 -0
  18. package/templates/backend-capabilities/LICENSE.txt +231 -0
  19. package/templates/backend-capabilities/backend/Cargo.toml +21 -0
  20. package/templates/backend-capabilities/backend/src/lib.rs +179 -0
  21. package/templates/backend-capabilities/backend/tests/basic.rs +174 -0
  22. package/templates/backend-capabilities/manifest.source.json +64 -0
  23. package/templates/backend-capabilities/package.json +22 -0
  24. package/templates/backend-composition/LICENSE.txt +231 -0
  25. package/templates/backend-composition/backend/Cargo.toml +21 -0
  26. package/templates/backend-composition/backend/src/lib.rs +96 -0
  27. package/templates/backend-composition/backend/tests/basic.rs +75 -0
  28. package/templates/backend-composition/manifest.source.json +26 -0
  29. package/templates/backend-composition/package.json +22 -0
  30. package/templates/backend-entities/LICENSE.txt +231 -0
  31. package/templates/backend-entities/backend/Cargo.toml +20 -0
  32. package/templates/backend-entities/backend/src/lib.rs +77 -0
  33. package/templates/backend-entities/backend/tests/basic.rs +26 -0
  34. package/templates/backend-entities/manifest.source.json +15 -0
  35. package/templates/backend-entities/package.json +22 -0
  36. package/templates/backend-minimal/LICENSE.txt +231 -0
  37. package/templates/backend-minimal/backend/Cargo.toml +21 -0
  38. package/templates/backend-minimal/backend/src/lib.rs +69 -0
  39. package/templates/backend-minimal/backend/tests/basic.rs +67 -0
  40. package/templates/backend-minimal/manifest.source.json +15 -0
  41. package/templates/backend-minimal/package.json +22 -0
  42. package/templates/backend-operations/LICENSE.txt +231 -0
  43. package/templates/backend-operations/backend/Cargo.toml +21 -0
  44. package/templates/backend-operations/backend/src/lib.rs +117 -0
  45. package/templates/backend-operations/backend/tests/basic.rs +169 -0
  46. package/templates/backend-operations/manifest.source.json +15 -0
  47. package/templates/backend-operations/package.json +22 -0
  48. package/templates/frontend-entity/LICENSE.txt +27 -0
  49. package/templates/frontend-entity/README.md +46 -0
  50. package/templates/frontend-entity/frontend/i18n/en-GB.json +5 -0
  51. package/templates/frontend-entity/frontend/package.json +32 -0
  52. package/templates/frontend-entity/frontend/src/CustomerListPage.tsx +98 -0
  53. package/templates/frontend-entity/frontend/src/model.ts +5 -0
  54. package/templates/frontend-entity/frontend/tests/entityLifecycle.test.tsx +79 -0
  55. package/templates/frontend-entity/frontend/tsconfig.json +4 -0
  56. package/templates/frontend-entity/frontend/vite.config.ts +3 -0
  57. package/templates/frontend-entity/frontend/vitest.config.ts +9 -0
  58. package/templates/frontend-entity/manifest.source.json +53 -0
  59. package/templates/frontend-entity/package.json +22 -0
  60. package/templates/frontend-entity/pnpm-workspace.yaml +2 -0
  61. package/templates/frontend-extension/LICENSE.txt +27 -0
  62. package/templates/frontend-extension/README.md +7 -0
  63. package/templates/frontend-extension/frontend/i18n/en-GB.json +4 -0
  64. package/templates/frontend-extension/frontend/package.json +25 -0
  65. package/templates/frontend-extension/frontend/src/CustomerNotes.tsx +24 -0
  66. package/templates/frontend-extension/frontend/tsconfig.json +4 -0
  67. package/templates/frontend-extension/frontend/vite.config.ts +3 -0
  68. package/templates/frontend-extension/manifest.source.json +16 -0
  69. package/templates/frontend-extension/package.json +22 -0
  70. package/templates/frontend-extension/pnpm-workspace.yaml +2 -0
  71. package/templates/frontend-minimal/LICENSE.txt +27 -0
  72. package/templates/frontend-minimal/README.md +5 -0
  73. package/templates/frontend-minimal/frontend/i18n/en-GB.json +4 -0
  74. package/templates/frontend-minimal/frontend/package.json +25 -0
  75. package/templates/frontend-minimal/frontend/src/Page.tsx +16 -0
  76. package/templates/frontend-minimal/frontend/src/entry.ts +1 -0
  77. package/templates/frontend-minimal/frontend/tsconfig.json +4 -0
  78. package/templates/frontend-minimal/frontend/vite.config.ts +3 -0
  79. package/templates/frontend-minimal/manifest.source.json +51 -0
  80. package/templates/frontend-minimal/package.json +22 -0
  81. package/templates/frontend-minimal/pnpm-workspace.yaml +2 -0
  82. package/templates/frontend-provider-event/LICENSE.txt +27 -0
  83. package/templates/frontend-provider-event/README.md +7 -0
  84. package/templates/frontend-provider-event/frontend/i18n/en-GB.json +3 -0
  85. package/templates/frontend-provider-event/frontend/package.json +25 -0
  86. package/templates/frontend-provider-event/frontend/src/CustomerBadgeProvider.ts +24 -0
  87. package/templates/frontend-provider-event/frontend/src/CustomerSavedHandler.ts +22 -0
  88. package/templates/frontend-provider-event/frontend/tsconfig.json +4 -0
  89. package/templates/frontend-provider-event/frontend/vite.config.ts +3 -0
  90. package/templates/frontend-provider-event/manifest.source.json +16 -0
  91. package/templates/frontend-provider-event/package.json +22 -0
  92. package/templates/frontend-provider-event/pnpm-workspace.yaml +2 -0
  93. package/templates/full-stack-minimal/LICENSE.txt +231 -0
  94. package/templates/full-stack-minimal/README.md +49 -0
  95. package/templates/full-stack-minimal/backend/Cargo.toml +18 -0
  96. package/templates/full-stack-minimal/backend/src/lib.rs +49 -0
  97. package/templates/full-stack-minimal/backend/tests/basic.rs +49 -0
  98. package/templates/full-stack-minimal/frontend/i18n/en-GB.json +6 -0
  99. package/templates/full-stack-minimal/frontend/package.json +25 -0
  100. package/templates/full-stack-minimal/frontend/src/Page.tsx +29 -0
  101. package/templates/full-stack-minimal/frontend/src/entry.ts +1 -0
  102. package/templates/full-stack-minimal/frontend/tsconfig.json +4 -0
  103. package/templates/full-stack-minimal/frontend/vite.config.ts +3 -0
  104. package/templates/full-stack-minimal/manifest.source.json +55 -0
  105. package/templates/full-stack-minimal/package.json +24 -0
  106. package/templates/full-stack-minimal/pnpm-workspace.yaml +2 -0
  107. package/templates/full-stack-workflow-node/LICENSE.txt +231 -0
  108. package/templates/full-stack-workflow-node/README.md +111 -0
  109. package/templates/full-stack-workflow-node/backend/Cargo.toml +12 -0
  110. package/templates/full-stack-workflow-node/backend/src/lib.rs +70 -0
  111. package/templates/full-stack-workflow-node/frontend/i18n/en-GB.json +10 -0
  112. package/templates/full-stack-workflow-node/frontend/package.json +29 -0
  113. package/templates/full-stack-workflow-node/frontend/src/editors/FormatLabelEditor.tsx +25 -0
  114. package/templates/full-stack-workflow-node/frontend/src/entry.ts +2 -0
  115. package/templates/full-stack-workflow-node/frontend/src/nodes/FormatLabel.tsx +18 -0
  116. package/templates/full-stack-workflow-node/frontend/src/presentations/FormatLabelPresentation.tsx +7 -0
  117. package/templates/full-stack-workflow-node/frontend/tsconfig.json +4 -0
  118. package/templates/full-stack-workflow-node/frontend/vite.config.ts +5 -0
  119. package/templates/full-stack-workflow-node/manifest.source.json +18 -0
  120. package/templates/full-stack-workflow-node/package.json +25 -0
  121. package/templates/full-stack-workflow-node/pnpm-workspace.yaml +2 -0
  122. package/templates/localization-fr-fr/LICENSE.txt +27 -0
  123. package/templates/localization-fr-fr/README.md +5 -0
  124. package/templates/localization-fr-fr/localization/plugmatica.customer.fr-FR.json +4 -0
  125. package/templates/localization-fr-fr/manifest.source.json +36 -0
  126. package/templates/localization-fr-fr/package.json +18 -0
  127. package/templates/starter-projection.json +448 -0
  128. package/tsconfig.plugin.json +14 -0
@@ -0,0 +1,3135 @@
1
+ import {
2
+ PLUGMATICA_FRONTEND_POLICY,
3
+ assertBackendManifestProjection,
4
+ buildPluginContractGraph,
5
+ compilePluginSource,
6
+ currentExtensionContractFromManifest,
7
+ materializeGeneratedFrontendManifest,
8
+ projectBackendManifest,
9
+ validateExtensionDependencyGraph
10
+ } from "./chunk-QHTGR4ZB.js";
11
+
12
+ // src/scaffold.ts
13
+ import {
14
+ mkdir,
15
+ readFile,
16
+ readdir,
17
+ rm,
18
+ stat,
19
+ writeFile
20
+ } from "fs/promises";
21
+ import { basename, dirname, resolve, sep } from "path";
22
+ import { fileURLToPath } from "url";
23
+ var TEMPLATE_ROOT = fileURLToPath(new URL("../templates/", import.meta.url));
24
+ var TEMPLATE_CATALOG = resolve(TEMPLATE_ROOT, "starter-projection.json");
25
+ async function listPluginTemplates() {
26
+ const catalog = await readTemplateCatalog();
27
+ return catalog.starters.map((starter) => ({
28
+ ...starter,
29
+ facets: [...starter.facets],
30
+ tags: [...starter.tags],
31
+ files: [...starter.files],
32
+ templateParameters: starter.templateParameters.map((parameter) => ({
33
+ ...parameter
34
+ }))
35
+ }));
36
+ }
37
+ async function createPluginScaffold(options) {
38
+ assertSupportedNode();
39
+ assertSupportedPackageManager();
40
+ const root = resolve(options.directory);
41
+ const catalog = await readTemplateCatalog();
42
+ const templateId = options.template ?? "frontend-minimal";
43
+ const template = catalog.starters.find(
44
+ (candidate) => candidate.id === templateId
45
+ );
46
+ if (!template) {
47
+ throw new Error(
48
+ `Unknown Plugmatica template '${templateId}'. Run 'plugmatica templates' to list supported starters.`
49
+ );
50
+ }
51
+ const pluginKey = options.pluginKey ?? `example.${basename(root).replace(/[^a-zA-Z0-9.-]/g, "-")}`;
52
+ const name = options.name ?? pluginKey;
53
+ const parameters = resolveTemplateParameters(template, options);
54
+ await prepareDestination(root, options.force === true);
55
+ const templateRoot = resolve(TEMPLATE_ROOT, template.id);
56
+ const materialized = /* @__PURE__ */ new Map();
57
+ for (const relativePath of template.files) {
58
+ const source = resolve(templateRoot, relativePath);
59
+ assertPathInside(
60
+ templateRoot,
61
+ source,
62
+ `Template file '${relativePath}' escapes its template root.`
63
+ );
64
+ const raw = await readFile(source, "utf8");
65
+ materialized.set(
66
+ relativePath,
67
+ substituteTemplateParameters(raw, parameters)
68
+ );
69
+ }
70
+ const manifestSource = materialized.get("manifest.source.json");
71
+ if (!manifestSource) {
72
+ throw new Error(
73
+ `Template '${template.id}' is missing manifest.source.json.`
74
+ );
75
+ }
76
+ const originalManifest = JSON.parse(manifestSource);
77
+ const originalPluginKey = requiredString(
78
+ originalManifest.key,
79
+ `${template.id} manifest key`
80
+ );
81
+ const originalModuleName = isRecord(originalManifest.frontend) && typeof originalManifest.frontend.moduleName === "string" ? originalManifest.frontend.moduleName : void 0;
82
+ if (originalPluginKey !== pluginKey) {
83
+ for (const [relativePath, content] of materialized) {
84
+ materialized.set(
85
+ relativePath,
86
+ content.replaceAll(originalPluginKey, pluginKey)
87
+ );
88
+ }
89
+ }
90
+ personalizeManifest(materialized, {
91
+ template,
92
+ pluginKey,
93
+ name,
94
+ description: options.description ?? "Plugmatica plugin package.",
95
+ author: options.author ?? "Plugin author",
96
+ moduleName: options.moduleName,
97
+ originalModuleName
98
+ });
99
+ personalizeFrontendPackages(materialized, pluginKey);
100
+ personalizeBackendCrates(materialized, pluginKey);
101
+ assertNoTemplateTokens(template, materialized);
102
+ for (const [relativePath, content] of materialized) {
103
+ const target = resolve(root, relativePath);
104
+ assertPathInside(
105
+ root,
106
+ target,
107
+ `Template output '${relativePath}' escapes the destination.`
108
+ );
109
+ await mkdir(dirname(target), { recursive: true });
110
+ await writeFile(target, content, "utf8");
111
+ }
112
+ const gitignore = resolve(root, ".gitignore");
113
+ try {
114
+ await stat(gitignore);
115
+ } catch {
116
+ await writeFile(
117
+ gitignore,
118
+ "frontend/dist/\nbackend/target/\nmanifest.json\nnode_modules/\n",
119
+ "utf8"
120
+ );
121
+ }
122
+ return {
123
+ root,
124
+ template: template.id,
125
+ pluginKey,
126
+ facets: {
127
+ frontend: template.facets.includes("frontend"),
128
+ backend: template.facets.includes("backend"),
129
+ localization: template.facets.includes("localization")
130
+ }
131
+ };
132
+ }
133
+ function resolveTemplateParameters(template, options) {
134
+ const values = {
135
+ targetSurface: options.targetSurface,
136
+ targetKey: options.targetKey,
137
+ targetPoint: options.targetPoint,
138
+ targetContractId: options.targetContractId,
139
+ targetContractVersion: options.targetContractVersion,
140
+ providerKey: options.providerKey,
141
+ providerContractId: options.providerContractId,
142
+ providerContractVersion: options.providerContractVersion,
143
+ eventKey: options.eventKey,
144
+ eventContractId: options.eventContractId,
145
+ eventContractVersion: options.eventContractVersion,
146
+ ...options.templateValues
147
+ };
148
+ const resolved = /* @__PURE__ */ new Map();
149
+ const missing = [];
150
+ for (const parameter of template.templateParameters) {
151
+ const value = values[parameter.name] ?? parameter.default;
152
+ if (!value && parameter.required) {
153
+ missing.push(`--${camelToKebab(parameter.name)}`);
154
+ continue;
155
+ }
156
+ if (value) resolved.set(parameter.token, value);
157
+ }
158
+ if (missing.length) {
159
+ throw new Error(
160
+ `Template '${template.id}' requires ${missing.join(", ")}. Run 'plugmatica templates --json' for parameter metadata.`
161
+ );
162
+ }
163
+ return resolved;
164
+ }
165
+ function substituteTemplateParameters(content, parameters) {
166
+ let output = content;
167
+ for (const [token, value] of parameters)
168
+ output = output.replaceAll(token, value);
169
+ return output;
170
+ }
171
+ function personalizeManifest(materialized, identity) {
172
+ const raw = materialized.get("manifest.source.json");
173
+ if (!raw)
174
+ throw new Error(
175
+ `Template '${identity.template.id}' is missing manifest.source.json.`
176
+ );
177
+ const manifest = JSON.parse(raw);
178
+ manifest.key = identity.pluginKey;
179
+ manifest.name = identity.name;
180
+ manifest.description = identity.description;
181
+ manifest.author = identity.author;
182
+ if (isRecord(manifest.frontend)) {
183
+ manifest.frontend.moduleName = identity.moduleName ?? identity.pluginKey.replace(/[^a-zA-Z0-9_]/g, "_");
184
+ }
185
+ if (isRecord(manifest.shell)) {
186
+ namespaceShellIdentity(manifest.shell, identity.pluginKey);
187
+ }
188
+ namespaceManifestPermissions(manifest, identity.pluginKey);
189
+ let next = `${JSON.stringify(manifest, null, 2)}
190
+ `;
191
+ if (identity.originalModuleName && isRecord(manifest.frontend)) {
192
+ const nextModuleName = String(manifest.frontend.moduleName);
193
+ if (identity.originalModuleName !== nextModuleName) {
194
+ for (const [relativePath, content] of materialized) {
195
+ materialized.set(
196
+ relativePath,
197
+ content.replaceAll(identity.originalModuleName, nextModuleName)
198
+ );
199
+ }
200
+ next = `${JSON.stringify(manifest, null, 2)}
201
+ `;
202
+ }
203
+ }
204
+ materialized.set("manifest.source.json", next);
205
+ }
206
+ function namespaceShellIdentity(shell, pluginKey) {
207
+ const keyMap = /* @__PURE__ */ new Map();
208
+ const mapKey = (value) => {
209
+ const existing = keyMap.get(value);
210
+ if (existing) return existing;
211
+ const suffix = value.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/^-+|-+$/g, "") || "item";
212
+ const next = value === pluginKey ? pluginKey : `${pluginKey}.${suffix}`;
213
+ keyMap.set(value, next);
214
+ return next;
215
+ };
216
+ walkObjects(shell, (object) => {
217
+ if (typeof object.key === "string") mapKey(object.key);
218
+ });
219
+ walkObjects(shell, (object) => {
220
+ if (typeof object.key === "string") object.key = mapKey(object.key);
221
+ if (typeof object.appKey === "string")
222
+ object.appKey = mapKey(object.appKey);
223
+ if (typeof object.path === "string" && object.path.startsWith("/")) {
224
+ const prefix = `/${pluginKey.replace(/[^a-zA-Z0-9-]/g, "-").replace(/^-+|-+$/g, "") || "plugin"}`;
225
+ object.path = object.path === "/" ? prefix : `${prefix}${object.path}`;
226
+ }
227
+ });
228
+ }
229
+ function namespaceManifestPermissions(manifest, pluginKey) {
230
+ walkObjects(manifest, (object) => {
231
+ if (!Array.isArray(object.permissions)) return;
232
+ object.permissions = object.permissions.map((permission) => {
233
+ if (typeof permission !== "string" || !permission.startsWith("example."))
234
+ return permission;
235
+ return `${pluginKey}.${permission.slice("example.".length)}`;
236
+ });
237
+ });
238
+ }
239
+ function personalizeFrontendPackages(materialized, pluginKey) {
240
+ for (const [relativePath, content] of materialized) {
241
+ if (basename(relativePath) !== "package.json") continue;
242
+ const pkg = JSON.parse(content);
243
+ if (typeof pkg.name === "string") {
244
+ pkg.name = relativePath === "package.json" ? rootPackageName(pluginKey) : frontendPackageName(pluginKey);
245
+ }
246
+ materialized.set(relativePath, `${JSON.stringify(pkg, null, 2)}
247
+ `);
248
+ }
249
+ }
250
+ function rootPackageName(pluginKey) {
251
+ const parts = pluginKey.split(".").filter(Boolean);
252
+ const clean = (value) => value.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "") || "plugin";
253
+ if (parts.length > 1) {
254
+ return `@${clean(parts[0])}/${clean(parts.slice(1).join("-"))}`;
255
+ }
256
+ return clean(pluginKey);
257
+ }
258
+ function personalizeBackendCrates(materialized, pluginKey) {
259
+ const crateName = pluginKey.replace(/[^a-zA-Z0-9_-]/g, "-").replace(/^-+|-+$/g, "") || "plugmatica-plugin";
260
+ const crateIdentifier = crateName.replaceAll("-", "_");
261
+ const crateRenames = /* @__PURE__ */ new Map();
262
+ for (const [relativePath, content] of materialized) {
263
+ if (!relativePath.endsWith("Cargo.toml")) continue;
264
+ const packageName = content.match(
265
+ /\[package\][\s\S]*?\n\s*name\s*=\s*["']([^"']+)["']/
266
+ )?.[1];
267
+ if (packageName) {
268
+ crateRenames.set(packageName.replaceAll("-", "_"), crateIdentifier);
269
+ }
270
+ materialized.set(
271
+ relativePath,
272
+ content.replace(
273
+ /(\[package\][\s\S]*?\n\s*name\s*=\s*)["'][^"']+["']/,
274
+ `$1"${crateName}"`
275
+ )
276
+ );
277
+ }
278
+ for (const [relativePath, content] of materialized) {
279
+ if (!relativePath.endsWith(".rs")) continue;
280
+ let personalized = content;
281
+ for (const [originalIdentifier, personalizedIdentifier] of crateRenames) {
282
+ if (originalIdentifier === personalizedIdentifier) continue;
283
+ personalized = personalized.replace(
284
+ new RegExp(`\\b${escapeRegExp(originalIdentifier)}\\b`, "g"),
285
+ personalizedIdentifier
286
+ );
287
+ }
288
+ materialized.set(relativePath, personalized);
289
+ }
290
+ }
291
+ function escapeRegExp(value) {
292
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
293
+ }
294
+ function frontendPackageName(pluginKey) {
295
+ const parts = pluginKey.split(".").filter(Boolean);
296
+ const clean = (value) => value.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "") || "plugin";
297
+ if (parts.length > 1) {
298
+ return `@${clean(parts[0])}/${clean(parts.slice(1).join("-"))}-frontend`;
299
+ }
300
+ return `${clean(pluginKey)}-frontend`;
301
+ }
302
+ function assertNoTemplateTokens(template, materialized) {
303
+ for (const [relativePath, content] of materialized) {
304
+ const unresolved = content.match(/\{\{[A-Za-z][A-Za-z0-9]*\}\}/g);
305
+ if (unresolved?.length) {
306
+ throw new Error(
307
+ `Template '${template.id}' left unresolved placeholder(s) in ${relativePath}: ${[...new Set(unresolved)].join(", ")}.`
308
+ );
309
+ }
310
+ }
311
+ }
312
+ async function prepareDestination(root, force) {
313
+ try {
314
+ const entries2 = await readdir(root);
315
+ if (entries2.length && !force) {
316
+ throw new Error(
317
+ `Destination '${root}' is not empty. Choose an empty directory or pass --force to replace it.`
318
+ );
319
+ }
320
+ if (force) await rm(root, { recursive: true, force: true });
321
+ } catch (error) {
322
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
323
+ throw error;
324
+ }
325
+ await mkdir(root, { recursive: true });
326
+ }
327
+ async function readTemplateCatalog() {
328
+ const catalog = JSON.parse(
329
+ await readFile(TEMPLATE_CATALOG, "utf8")
330
+ );
331
+ if (catalog.schemaVersion !== 1 || !Array.isArray(catalog.starters)) {
332
+ throw new Error("Packaged Plugmatica starter catalogue is invalid.");
333
+ }
334
+ return catalog;
335
+ }
336
+ function assertPathInside(root, target, message) {
337
+ const normalizedRoot = resolve(root);
338
+ const normalizedTarget = resolve(target);
339
+ if (normalizedTarget !== normalizedRoot && !normalizedTarget.startsWith(`${normalizedRoot}${sep}`)) {
340
+ throw new Error(message);
341
+ }
342
+ }
343
+ function walkObjects(value, visit) {
344
+ if (Array.isArray(value)) {
345
+ for (const item of value) walkObjects(item, visit);
346
+ return;
347
+ }
348
+ if (!isRecord(value)) return;
349
+ visit(value);
350
+ for (const nested of Object.values(value)) walkObjects(nested, visit);
351
+ }
352
+ function isRecord(value) {
353
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
354
+ }
355
+ function requiredString(value, label) {
356
+ if (typeof value !== "string" || !value)
357
+ throw new Error(`${label} must be a non-empty string.`);
358
+ return value;
359
+ }
360
+ function camelToKebab(value) {
361
+ return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
362
+ }
363
+ function assertSupportedNode(major = Number(process.versions.node.split(".")[0])) {
364
+ if (major < PLUGMATICA_FRONTEND_POLICY.node.minimumMajor) {
365
+ throw new Error(
366
+ `Plugmatica plugin tooling requires Node ${PLUGMATICA_FRONTEND_POLICY.node.minimumMajor}+.`
367
+ );
368
+ }
369
+ }
370
+ function assertSupportedPackageManager(userAgent = process.env.npm_config_user_agent) {
371
+ if (!userAgent) return;
372
+ const match = /^(npm|pnpm|yarn)\/(\d+)(?:\.|\s|$)/.exec(userAgent.trim());
373
+ if (!match) return;
374
+ const manager = match[1];
375
+ const major = Number.parseInt(match[2] ?? "", 10);
376
+ const minimum = PLUGMATICA_FRONTEND_POLICY.packageManagers[manager];
377
+ if (Number.isFinite(major) && major < minimum) {
378
+ throw new Error(
379
+ `Plugmatica plugin tooling requires ${manager} ${minimum}+; current ${manager} runtime is ${major}.`
380
+ );
381
+ }
382
+ }
383
+
384
+ // src/compatibility/types.ts
385
+ var CONTRACT_BASELINE_FORMAT_VERSION = 1;
386
+
387
+ // src/compatibility/contract.ts
388
+ import fs from "fs";
389
+ import path from "path";
390
+ import {
391
+ createCurrentExtensionContract
392
+ } from "@plugmatica/core-sdk";
393
+ function buildCurrentContractSnapshot(options) {
394
+ const sourceDir = path.resolve(options.sourceDir);
395
+ const manifestPath = path.resolve(options.manifestPath);
396
+ const manifest = JSON.parse(
397
+ fs.readFileSync(manifestPath, "utf8")
398
+ );
399
+ const pluginId = requiredString2(manifest.key, "manifest.key");
400
+ const compilerResult = options.compilerResult ?? compilePluginSource(sourceDir, {
401
+ pageRoutes: compilerPageRoutes(manifest)
402
+ });
403
+ if (path.resolve(compilerResult.root) !== sourceDir) {
404
+ throw new Error(
405
+ `Provided compilerResult root '${compilerResult.root}' does not match sourceDir '${sourceDir}'.`
406
+ );
407
+ }
408
+ const fatal = compilerResult.issues.filter(
409
+ (issue2) => issue2.severity === "error"
410
+ );
411
+ if (fatal.length > 0) {
412
+ throw new Error(
413
+ `Cannot generate Current Extension Contract because semantic compilation produced ${fatal.length} error(s).`
414
+ );
415
+ }
416
+ const merged = materializeGeneratedFrontendManifest(manifest, compilerResult);
417
+ const contract = currentExtensionContractFromManifest(merged);
418
+ const diagnostics = diagnosticsFromCompiler(compilerResult);
419
+ const version = optionalString(manifest.version);
420
+ return {
421
+ pluginId,
422
+ ...version ? { pluginVersion: version } : {},
423
+ contract,
424
+ diagnostics,
425
+ compilerResult
426
+ };
427
+ }
428
+ function createRepositoryBaselineFile(snapshot) {
429
+ return {
430
+ formatVersion: CONTRACT_BASELINE_FORMAT_VERSION,
431
+ pluginId: snapshot.pluginId,
432
+ ...snapshot.pluginVersion ? { pluginVersion: snapshot.pluginVersion } : {},
433
+ contract: normalizeCurrentExtensionContract(snapshot.contract),
434
+ ...snapshot.diagnostics.length > 0 ? { diagnostics: canonicalizeDiagnostics(snapshot.diagnostics) } : {}
435
+ };
436
+ }
437
+ function normalizeCurrentExtensionContract(value) {
438
+ if (!isRecord2(value)) {
439
+ throw new Error("Extension contract must be a JSON object.");
440
+ }
441
+ const surfaces = readArray(value.surfaces, "contract.surfaces").map(
442
+ readSurface
443
+ );
444
+ const events = readArray(value.events ?? [], "contract.events").map(
445
+ readEvent
446
+ );
447
+ const providers = readArray(value.providers ?? [], "contract.providers").map(
448
+ readProvider
449
+ );
450
+ return createCurrentExtensionContract({ surfaces, events, providers });
451
+ }
452
+ function parseContractBaselineFile(value) {
453
+ if (!isRecord2(value)) {
454
+ throw new Error("Contract baseline must be a JSON object.");
455
+ }
456
+ if (value.formatVersion !== CONTRACT_BASELINE_FORMAT_VERSION) {
457
+ throw new Error(
458
+ `Contract baseline formatVersion must be ${CONTRACT_BASELINE_FORMAT_VERSION}; received ${String(value.formatVersion)}.`
459
+ );
460
+ }
461
+ const pluginId = requiredString2(value.pluginId, "baseline.pluginId");
462
+ const pluginVersion = optionalString(value.pluginVersion);
463
+ const contract = normalizeCurrentExtensionContract(value.contract);
464
+ const diagnostics = value.diagnostics === void 0 ? void 0 : canonicalizeDiagnostics(
465
+ readArray(value.diagnostics, "baseline.diagnostics").map(
466
+ readDiagnostic
467
+ )
468
+ );
469
+ return {
470
+ formatVersion: CONTRACT_BASELINE_FORMAT_VERSION,
471
+ pluginId,
472
+ ...pluginVersion ? { pluginVersion } : {},
473
+ contract,
474
+ ...diagnostics && diagnostics.length > 0 ? { diagnostics } : {}
475
+ };
476
+ }
477
+ function readContractBaselineFile(file) {
478
+ return parseContractBaselineFile(JSON.parse(fs.readFileSync(file, "utf8")));
479
+ }
480
+ function writeContractBaselineFile(file, baseline) {
481
+ const resolved = path.resolve(file);
482
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
483
+ const normalized = parseContractBaselineFile(baseline);
484
+ fs.writeFileSync(resolved, `${JSON.stringify(normalized, null, 2)}
485
+ `);
486
+ }
487
+ function contractFromManifestPayload(value) {
488
+ if (!isRecord2(value)) {
489
+ throw new Error("Baseline payload must be a JSON object.");
490
+ }
491
+ if (value.formatVersion === CONTRACT_BASELINE_FORMAT_VERSION && "contract" in value) {
492
+ const baseline = parseContractBaselineFile(value);
493
+ return {
494
+ pluginId: baseline.pluginId,
495
+ ...baseline.pluginVersion ? { pluginVersion: baseline.pluginVersion } : {},
496
+ contract: baseline.contract,
497
+ ...baseline.diagnostics ? { diagnostics: baseline.diagnostics } : {}
498
+ };
499
+ }
500
+ if (isRecord2(value.manifest)) {
501
+ const nested = contractFromManifestPayload(value.manifest);
502
+ return {
503
+ ...nested,
504
+ ...readManifestMetadata({
505
+ publishedAt: value.publishedAt,
506
+ installedAt: value.installedAt
507
+ })
508
+ };
509
+ }
510
+ if ("contract" in value && isRecord2(value.contract)) {
511
+ return {
512
+ ...readManifestMetadata({
513
+ pluginId: value.pluginId ?? value.key,
514
+ pluginVersion: value.pluginVersion ?? value.version,
515
+ publishedAt: value.publishedAt,
516
+ installedAt: value.installedAt
517
+ }),
518
+ contract: normalizeCurrentExtensionContract(value.contract)
519
+ };
520
+ }
521
+ if (typeof value.key === "string" && ("frontend" in value || "manifestVersion" in value)) {
522
+ const manifest = value;
523
+ return {
524
+ pluginId: manifest.key,
525
+ ...readManifestMetadata({
526
+ pluginVersion: value.version,
527
+ publishedAt: value.publishedAt,
528
+ installedAt: value.installedAt
529
+ }),
530
+ contract: currentExtensionContractFromManifest(manifest)
531
+ };
532
+ }
533
+ if ("surfaces" in value) {
534
+ return { contract: normalizeCurrentExtensionContract(value) };
535
+ }
536
+ throw new Error(
537
+ "Baseline payload is neither a Plugmatica contract baseline, Current Extension Contract, nor plugin manifest."
538
+ );
539
+ }
540
+ function readManifestMetadata(values) {
541
+ const pluginId = optionalString(values.pluginId);
542
+ const pluginVersion = optionalString(values.pluginVersion);
543
+ const publishedAt = optionalString(values.publishedAt);
544
+ const installedAt = optionalString(values.installedAt);
545
+ return {
546
+ ...pluginId ? { pluginId } : {},
547
+ ...pluginVersion ? { pluginVersion } : {},
548
+ ...publishedAt ? { publishedAt } : {},
549
+ ...installedAt ? { installedAt } : {}
550
+ };
551
+ }
552
+ function diagnosticsFromCompiler(result) {
553
+ return result.nodes.filter((node) => node.emitsSurface).map((node) => ({
554
+ kind: "surface",
555
+ key: node.key,
556
+ surface: node.surface,
557
+ source: {
558
+ file: node.source.file,
559
+ component: node.source.component,
560
+ ...node.source.semanticSourceName ? { semanticSourceName: node.source.semanticSourceName } : {}
561
+ }
562
+ })).sort(compareDiagnostics);
563
+ }
564
+ function canonicalizeDiagnostics(diagnostics) {
565
+ return diagnostics.map((entry) => ({
566
+ kind: entry.kind,
567
+ key: requiredString2(entry.key, "diagnostic.key"),
568
+ ...entry.surface ? { surface: entry.surface } : {},
569
+ ...entry.source ? {
570
+ source: {
571
+ ...entry.source.file ? { file: entry.source.file } : {},
572
+ ...entry.source.component ? { component: entry.source.component } : {},
573
+ ...entry.source.semanticSourceName ? { semanticSourceName: entry.source.semanticSourceName } : {}
574
+ }
575
+ } : {}
576
+ })).sort(compareDiagnostics);
577
+ }
578
+ function compareDiagnostics(left, right) {
579
+ return left.kind.localeCompare(right.kind) || (left.surface ?? "").localeCompare(right.surface ?? "") || left.key.localeCompare(right.key);
580
+ }
581
+ function readDiagnostic(value) {
582
+ if (!isRecord2(value))
583
+ throw new Error("baseline.diagnostics[] must be an object.");
584
+ const kind = requiredString2(value.kind, "diagnostic.kind");
585
+ if (kind !== "surface" && kind !== "event" && kind !== "provider") {
586
+ throw new Error(`Unsupported diagnostic kind '${kind}'.`);
587
+ }
588
+ const source = isRecord2(value.source) ? {
589
+ ...optionalString(value.source.file) ? { file: optionalString(value.source.file) } : {},
590
+ ...optionalString(value.source.component) ? { component: optionalString(value.source.component) } : {},
591
+ ...optionalString(value.source.semanticSourceName) ? {
592
+ semanticSourceName: optionalString(
593
+ value.source.semanticSourceName
594
+ )
595
+ } : {}
596
+ } : void 0;
597
+ return {
598
+ kind,
599
+ key: requiredString2(value.key, "diagnostic.key"),
600
+ ...optionalString(value.surface) ? { surface: optionalString(value.surface) } : {},
601
+ ...source && Object.keys(source).length > 0 ? { source } : {}
602
+ };
603
+ }
604
+ function compilerPageRoutes(source) {
605
+ const shell = source.shell;
606
+ if (!isRecord2(shell)) return [];
607
+ const pages = Array.isArray(shell.pages) ? shell.pages : [];
608
+ return pages.flatMap((page) => {
609
+ if (!isRecord2(page)) return [];
610
+ const key = optionalString(page.key)?.trim() ?? "";
611
+ const module = optionalString(page.module)?.trim() ?? "";
612
+ return key && module ? [{ key, module }] : [];
613
+ });
614
+ }
615
+ function readSurface(value) {
616
+ if (!isRecord2(value))
617
+ throw new Error("contract.surfaces[] must be an object.");
618
+ return {
619
+ surface: requiredString2(
620
+ value.surface,
621
+ "surface.surface"
622
+ ),
623
+ key: requiredString2(value.key, "surface.key"),
624
+ contract: readContractDefinition(value.contract, "surface.contract"),
625
+ points: readArray(value.points ?? [], "surface.points").map((point) => {
626
+ if (!isRecord2(point))
627
+ throw new Error("surface.points[] must be an object.");
628
+ if (typeof point.multiple !== "boolean")
629
+ throw new Error("surface.point.multiple must be boolean.");
630
+ const ownerAnchors = readArray(
631
+ point.ownerAnchors ?? [],
632
+ "surface.point.ownerAnchors"
633
+ ).map((anchor) => requiredString2(anchor, "surface.point.ownerAnchors[]"));
634
+ const ownerAnchorsComplete = point.ownerAnchorsComplete === true;
635
+ return {
636
+ key: requiredString2(point.key, "surface.point.key"),
637
+ multiple: point.multiple,
638
+ ...ownerAnchors.length > 0 ? { ownerAnchors } : {},
639
+ ...ownerAnchorsComplete ? { ownerAnchorsComplete: true } : {}
640
+ };
641
+ }),
642
+ operations: readArray(value.operations ?? [], "surface.operations").map(
643
+ (operation) => requiredString2(operation, "surface.operation")
644
+ )
645
+ };
646
+ }
647
+ function readEvent(value) {
648
+ if (!isRecord2(value)) throw new Error("contract.events[] must be an object.");
649
+ if (typeof value.multiple !== "boolean")
650
+ throw new Error("event.multiple must be boolean.");
651
+ return {
652
+ key: requiredString2(value.key, "event.key"),
653
+ contract: readContractDefinition(value.contract, "event.contract"),
654
+ multiple: value.multiple
655
+ };
656
+ }
657
+ function readProvider(value) {
658
+ if (!isRecord2(value))
659
+ throw new Error("contract.providers[] must be an object.");
660
+ if (typeof value.multiple !== "boolean")
661
+ throw new Error("provider.multiple must be boolean.");
662
+ return {
663
+ key: requiredString2(value.key, "provider.key"),
664
+ contract: readContractDefinition(value.contract, "provider.contract"),
665
+ multiple: value.multiple
666
+ };
667
+ }
668
+ function readContractDefinition(value, field) {
669
+ if (!isRecord2(value)) throw new Error(`${field} must be an object.`);
670
+ return {
671
+ id: requiredString2(value.id, `${field}.id`),
672
+ version: requiredString2(value.version, `${field}.version`)
673
+ };
674
+ }
675
+ function readArray(value, field) {
676
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array.`);
677
+ return value;
678
+ }
679
+ function requiredString2(value, field) {
680
+ if (typeof value !== "string" || !value.trim()) {
681
+ throw new Error(`${field} must be a non-empty string.`);
682
+ }
683
+ return value.trim();
684
+ }
685
+ function optionalString(value) {
686
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
687
+ }
688
+ function isRecord2(value) {
689
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
690
+ }
691
+
692
+ // src/compatibility/providers.ts
693
+ import crypto from "crypto";
694
+ import fs2 from "fs";
695
+ import path2 from "path";
696
+ import { spawnSync } from "child_process";
697
+ var RegistryBaselineUnavailableError = class extends Error {
698
+ constructor(message, options) {
699
+ super(message, options);
700
+ this.name = "RegistryBaselineUnavailableError";
701
+ }
702
+ };
703
+ var ExplicitContractBaselineProvider = class {
704
+ /**
705
+ * Stable discriminator describing the record/provider kind.
706
+ */
707
+ kind = "explicit";
708
+ /**
709
+ * Source file path.
710
+ */
711
+ file;
712
+ constructor(file) {
713
+ this.file = path2.resolve(file);
714
+ }
715
+ /**
716
+ * Resolve a compatibility baseline for the supplied plugin context.
717
+ *
718
+ * @param context - Plugin/project compatibility context.
719
+ * @returns Resolved baseline, or null when this provider has no applicable baseline.
720
+ */
721
+ async resolve(context) {
722
+ if (!fs2.existsSync(this.file)) {
723
+ throw new Error(
724
+ `Explicit Contract Baseline '${this.file}' does not exist.`
725
+ );
726
+ }
727
+ const payload = JSON.parse(fs2.readFileSync(this.file, "utf8"));
728
+ return materializeContractBaseline(contractFromManifestPayload(payload), context, {
729
+ kind: "explicit",
730
+ description: "Explicit Contract Baseline",
731
+ reference: this.file
732
+ });
733
+ }
734
+ };
735
+ var RepositoryContractBaselineProvider = class {
736
+ /**
737
+ * Stable discriminator describing the record/provider kind.
738
+ */
739
+ kind = "repository";
740
+ /**
741
+ * Repository baseline filename or path.
742
+ */
743
+ fileName;
744
+ constructor(fileName = "plugmatica.contract.json") {
745
+ this.fileName = fileName;
746
+ }
747
+ /**
748
+ * Resolve a compatibility baseline for the supplied plugin context.
749
+ *
750
+ * @param context - Plugin/project compatibility context.
751
+ * @returns Resolved baseline, or null when this provider has no applicable baseline.
752
+ */
753
+ async resolve(context) {
754
+ const file = path2.isAbsolute(this.fileName) ? this.fileName : path2.resolve(context.projectRoot, this.fileName);
755
+ if (!fs2.existsSync(file)) return null;
756
+ return materializeContractBaseline(readContractBaselineFile(file), context, {
757
+ kind: this.kind,
758
+ description: "Repository Contract Baseline",
759
+ reference: file
760
+ });
761
+ }
762
+ };
763
+ var GitTagContractBaselineProvider = class {
764
+ /**
765
+ * Stable discriminator describing the record/provider kind.
766
+ */
767
+ kind = "git";
768
+ /**
769
+ * Git-tag baseline resolution options.
770
+ */
771
+ options;
772
+ constructor(options) {
773
+ const tag = options.tag.trim();
774
+ if (!tag || /[\r\n\0]/.test(tag))
775
+ throw new Error(
776
+ "Git Contract Baseline tag must be a non-empty single-line value."
777
+ );
778
+ this.options = { ...options, tag };
779
+ }
780
+ /**
781
+ * Resolve a compatibility baseline for the supplied plugin context.
782
+ *
783
+ * @param context - Plugin/project compatibility context.
784
+ * @returns Resolved baseline, or null when this provider has no applicable baseline.
785
+ */
786
+ async resolve(context) {
787
+ const git = this.options.git ?? "git";
788
+ const rootResult = spawnSync(git, ["rev-parse", "--show-toplevel"], {
789
+ cwd: context.projectRoot,
790
+ encoding: "utf8",
791
+ stdio: ["ignore", "pipe", "pipe"]
792
+ });
793
+ if (rootResult.status !== 0 || !rootResult.stdout.trim()) return null;
794
+ const repositoryRoot = fs2.realpathSync.native(rootResult.stdout.trim());
795
+ const configured = this.options.baselinePath ?? "plugmatica.contract.json";
796
+ const absolute = path2.isAbsolute(configured);
797
+ const baselineFile = absolute ? path2.resolve(configured) : path2.resolve(fs2.realpathSync.native(context.projectRoot), configured);
798
+ let relativeBaseline = path2.relative(repositoryRoot, baselineFile);
799
+ if (absolute && isOutsideRepository(relativeBaseline)) {
800
+ relativeBaseline = path2.relative(
801
+ repositoryRoot,
802
+ path2.join(realPathWithMissingParents(path2.dirname(baselineFile)), path2.basename(baselineFile))
803
+ );
804
+ }
805
+ if (!relativeBaseline || isOutsideRepository(relativeBaseline)) {
806
+ throw new Error(
807
+ `Git Contract Baseline '${baselineFile}' is outside repository '${repositoryRoot}'.`
808
+ );
809
+ }
810
+ const reference = `${this.options.tag}:${relativeBaseline.replaceAll(path2.sep, "/")}`;
811
+ const show = spawnSync(git, ["show", reference], {
812
+ cwd: repositoryRoot,
813
+ encoding: "utf8",
814
+ stdio: ["ignore", "pipe", "pipe"],
815
+ maxBuffer: 8 * 1024 * 1024
816
+ });
817
+ if (show.status !== 0 || !show.stdout.trim()) return null;
818
+ return materializeContractBaseline(
819
+ contractFromManifestPayload(JSON.parse(show.stdout)),
820
+ context,
821
+ {
822
+ kind: "git",
823
+ description: "Git tag Contract Baseline",
824
+ reference: `git:${reference}`,
825
+ mismatchLabel: "Git Contract Baseline"
826
+ }
827
+ );
828
+ }
829
+ };
830
+ function isOutsideRepository(relative3) {
831
+ return relative3 === ".." || relative3.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative3);
832
+ }
833
+ function realPathWithMissingParents(directory) {
834
+ try {
835
+ return fs2.realpathSync.native(directory);
836
+ } catch (error) {
837
+ const code = error.code;
838
+ const parent = path2.dirname(directory);
839
+ if (code !== "ENOENT" && code !== "ENOTDIR" || parent === directory) throw error;
840
+ return path2.join(realPathWithMissingParents(parent), path2.basename(directory));
841
+ }
842
+ }
843
+ var InstalledPluginContractBaselineProvider = class {
844
+ /**
845
+ * Stable discriminator describing the record/provider kind.
846
+ */
847
+ kind = "installed";
848
+ /**
849
+ * Installed plugin manifest/package candidates searched in order.
850
+ */
851
+ candidates;
852
+ constructor(candidates) {
853
+ this.candidates = (typeof candidates === "string" ? [candidates] : candidates).map((item) => path2.resolve(item));
854
+ }
855
+ /**
856
+ * Resolve a compatibility baseline for the supplied plugin context.
857
+ *
858
+ * @param context - Plugin/project compatibility context.
859
+ * @returns Resolved baseline, or null when this provider has no applicable baseline.
860
+ */
861
+ async resolve(context) {
862
+ for (const candidate of this.candidates) {
863
+ const file = resolveInstalledManifest(candidate);
864
+ if (!file || !fs2.existsSync(file)) continue;
865
+ const payload = JSON.parse(fs2.readFileSync(file, "utf8"));
866
+ const parsed = contractFromManifestPayload(payload);
867
+ if (parsed.pluginId && parsed.pluginId !== context.pluginId) continue;
868
+ return materializeContractBaseline(parsed, context, {
869
+ kind: "installed",
870
+ description: "Installed plugin manifest",
871
+ reference: file
872
+ });
873
+ }
874
+ return null;
875
+ }
876
+ };
877
+ var RegistryContractBaselineProvider = class {
878
+ /**
879
+ * Stable discriminator describing the record/provider kind.
880
+ */
881
+ kind = "registry";
882
+ /**
883
+ * Registry baseline resolution, cache, and timeout options.
884
+ */
885
+ options;
886
+ constructor(options) {
887
+ this.options = options;
888
+ }
889
+ /**
890
+ * Resolve a compatibility baseline for the supplied plugin context.
891
+ *
892
+ * @param context - Plugin/project compatibility context.
893
+ * @returns Resolved baseline, or null when this provider has no applicable baseline.
894
+ */
895
+ async resolve(context) {
896
+ const endpoint = resolveRegistryEndpoint(this.options.endpoint, context);
897
+ const cacheFile = this.options.cacheDir ? registryCacheFile(this.options.cacheDir, context.pluginId, endpoint) : null;
898
+ const cached = cacheFile ? readRegistryCache(cacheFile) : null;
899
+ const ttl = this.options.cacheTtlMs ?? 15 * 60 * 1e3;
900
+ if (context.offline) {
901
+ if (context.mode === "publish") {
902
+ throw new RegistryBaselineUnavailableError(
903
+ "Publish validation requires the authoritative destination registry and cannot run in offline mode."
904
+ );
905
+ }
906
+ if (!cached) return null;
907
+ return registryBaselineFromPayload(cached.payload, context, endpoint, {
908
+ cache: "offline",
909
+ registryName: this.options.registryName
910
+ });
911
+ }
912
+ if (context.mode === "development" && cached && Date.now() - cached.cachedAt <= ttl) {
913
+ return registryBaselineFromPayload(cached.payload, context, endpoint, {
914
+ cache: "fresh",
915
+ registryName: this.options.registryName
916
+ });
917
+ }
918
+ const fetcher = this.options.fetch ?? globalThis.fetch;
919
+ if (!fetcher) {
920
+ if (cached) {
921
+ return registryBaselineFromPayload(cached.payload, context, endpoint, {
922
+ cache: "stale-fallback",
923
+ registryName: this.options.registryName
924
+ });
925
+ }
926
+ throw new RegistryBaselineUnavailableError(
927
+ "No fetch implementation is available for registry baseline resolution."
928
+ );
929
+ }
930
+ const timeoutMs = this.options.timeoutMs ?? (context.mode === "development" ? 3e3 : 15e3);
931
+ const controller = new AbortController();
932
+ let timeout;
933
+ const timeoutError = new Error(
934
+ `Registry Contract Baseline request exceeded ${timeoutMs}ms.`
935
+ );
936
+ const timeoutPromise = new Promise((_resolve, reject) => {
937
+ timeout = setTimeout(() => {
938
+ controller.abort(timeoutError);
939
+ reject(timeoutError);
940
+ }, timeoutMs);
941
+ });
942
+ try {
943
+ const response = await Promise.race([
944
+ fetcher(endpoint, {
945
+ headers: this.options.headers,
946
+ signal: controller.signal
947
+ }),
948
+ timeoutPromise
949
+ ]);
950
+ if (response.status === 404 || response.status === 204) return null;
951
+ if (!response.ok) {
952
+ throw new Error(
953
+ `Registry returned HTTP ${response.status} ${response.statusText}`
954
+ );
955
+ }
956
+ const payload = await response.json();
957
+ if (cacheFile) writeRegistryCache(cacheFile, payload);
958
+ return registryBaselineFromPayload(payload, context, endpoint, {
959
+ registryName: this.options.registryName
960
+ });
961
+ } catch (error) {
962
+ if (context.mode === "development" && cached) {
963
+ return registryBaselineFromPayload(cached.payload, context, endpoint, {
964
+ cache: "stale-fallback",
965
+ registryName: this.options.registryName
966
+ });
967
+ }
968
+ throw new RegistryBaselineUnavailableError(
969
+ `Registry Contract Baseline is unavailable from '${endpoint}'.`,
970
+ { cause: error }
971
+ );
972
+ } finally {
973
+ if (timeout !== void 0) clearTimeout(timeout);
974
+ }
975
+ }
976
+ };
977
+ async function resolveContractBaseline(options) {
978
+ const { context } = options;
979
+ const byKind = /* @__PURE__ */ new Map();
980
+ for (const provider of options.providers) byKind.set(provider.kind, provider);
981
+ if (context.mode === "publish") {
982
+ const registry = byKind.get("registry");
983
+ if (registry) {
984
+ const attempts2 = [];
985
+ try {
986
+ const baseline = await registry.resolve(context);
987
+ if (baseline) {
988
+ attempts2.push({
989
+ kind: "registry",
990
+ status: "selected",
991
+ message: "Selected the destination's published contract as authoritative publish history."
992
+ });
993
+ markPublishSkipped(byKind, attempts2, "registry");
994
+ return { baseline, attempts: attempts2, mode: context.mode };
995
+ }
996
+ attempts2.push({
997
+ kind: "registry",
998
+ status: "not-found",
999
+ message: "The destination has no previously published contract for this plugin."
1000
+ });
1001
+ markPublishSkipped(byKind, attempts2, "registry");
1002
+ return { baseline: null, attempts: attempts2, mode: context.mode };
1003
+ } catch (error) {
1004
+ throw new RegistryBaselineUnavailableError(
1005
+ "Publish compatibility cannot fall back to repository or installed history because the destination registry is authoritative.",
1006
+ { cause: error }
1007
+ );
1008
+ }
1009
+ }
1010
+ const explicit = byKind.get("explicit");
1011
+ if (explicit) {
1012
+ const baseline = await explicit.resolve(context);
1013
+ return {
1014
+ baseline,
1015
+ mode: context.mode,
1016
+ attempts: [
1017
+ {
1018
+ kind: "explicit",
1019
+ status: baseline ? "selected" : "not-found",
1020
+ message: baseline ? "Selected the explicitly supplied publish baseline because no destination registry provider was configured." : "The explicit publish baseline did not resolve."
1021
+ }
1022
+ ]
1023
+ };
1024
+ }
1025
+ return { baseline: null, attempts: [], mode: context.mode };
1026
+ }
1027
+ const attempts = [];
1028
+ const precedence = [
1029
+ "explicit",
1030
+ "git",
1031
+ "repository",
1032
+ "registry",
1033
+ "installed"
1034
+ ];
1035
+ for (const kind of precedence) {
1036
+ const provider = byKind.get(kind);
1037
+ if (!provider) continue;
1038
+ try {
1039
+ const baseline = await provider.resolve(context);
1040
+ if (!baseline) {
1041
+ attempts.push({
1042
+ kind,
1043
+ status: "not-found",
1044
+ message: `${baselineLabel(kind)} was not available.`
1045
+ });
1046
+ continue;
1047
+ }
1048
+ attempts.push({
1049
+ kind,
1050
+ status: "selected",
1051
+ message: `Selected ${baselineLabel(kind)} by development precedence.`
1052
+ });
1053
+ for (const remaining of precedence.slice(precedence.indexOf(kind) + 1)) {
1054
+ if (byKind.has(remaining)) {
1055
+ attempts.push({
1056
+ kind: remaining,
1057
+ status: "skipped",
1058
+ message: `Skipped because ${baselineLabel(kind)} has higher development precedence.`
1059
+ });
1060
+ }
1061
+ }
1062
+ return { baseline, attempts, mode: context.mode };
1063
+ } catch (error) {
1064
+ if (kind === "registry") {
1065
+ attempts.push({
1066
+ kind,
1067
+ status: "unavailable",
1068
+ message: error instanceof Error ? error.message : String(error)
1069
+ });
1070
+ continue;
1071
+ }
1072
+ throw error;
1073
+ }
1074
+ }
1075
+ return { baseline: null, attempts, mode: context.mode };
1076
+ }
1077
+ function materializeContractBaseline(parsed, context, source) {
1078
+ const pluginId = parsed.pluginId ?? context.pluginId;
1079
+ if (pluginId !== context.pluginId) {
1080
+ throw new Error(
1081
+ source.kind === "registry" ? `Registry baseline pluginId '${pluginId}' does not match '${context.pluginId}'.` : `${source.mismatchLabel ?? source.description} pluginId '${pluginId}' does not match current plugin '${context.pluginId}'.`
1082
+ );
1083
+ }
1084
+ const publishedAt = source.kind === "explicit" || source.kind === "registry" ? parsed.publishedAt : void 0;
1085
+ const installedAt = source.kind === "explicit" || source.kind === "installed" ? parsed.installedAt : void 0;
1086
+ return {
1087
+ pluginId,
1088
+ ...parsed.pluginVersion ? { pluginVersion: parsed.pluginVersion } : {},
1089
+ ...publishedAt ? { publishedAt } : {},
1090
+ ...installedAt ? { installedAt } : {},
1091
+ contract: parsed.contract,
1092
+ ...parsed.diagnostics ? { diagnostics: parsed.diagnostics } : {},
1093
+ provenance: {
1094
+ kind: source.kind,
1095
+ description: source.description,
1096
+ reference: source.reference,
1097
+ ...parsed.pluginVersion ? { pluginVersion: parsed.pluginVersion } : {},
1098
+ ...publishedAt ? { publishedAt } : {},
1099
+ ...installedAt ? { installedAt } : {},
1100
+ ...source.registryName ? { registry: source.registryName } : {},
1101
+ ...source.cache ? { cache: source.cache } : {}
1102
+ }
1103
+ };
1104
+ }
1105
+ function registryBaselineFromPayload(payload, context, endpoint, options) {
1106
+ return materializeContractBaseline(contractFromManifestPayload(payload), context, {
1107
+ kind: "registry",
1108
+ description: "Published Contract Baseline",
1109
+ reference: endpoint,
1110
+ registryName: options.registryName,
1111
+ cache: options.cache
1112
+ });
1113
+ }
1114
+ function resolveInstalledManifest(candidate) {
1115
+ if (!fs2.existsSync(candidate)) return null;
1116
+ const stat2 = fs2.statSync(candidate);
1117
+ if (stat2.isFile()) return candidate;
1118
+ for (const name of ["manifest.json", "manifest.source.json", "plugin.json"]) {
1119
+ const file = path2.join(candidate, name);
1120
+ if (fs2.existsSync(file) && fs2.statSync(file).isFile()) return file;
1121
+ }
1122
+ return null;
1123
+ }
1124
+ function resolveRegistryEndpoint(endpoint, context) {
1125
+ if (typeof endpoint === "function") return endpoint(context);
1126
+ return endpoint.replaceAll("{pluginId}", encodeURIComponent(context.pluginId)).replaceAll("{version}", encodeURIComponent(context.pluginVersion ?? ""));
1127
+ }
1128
+ function registryCacheFile(cacheDir, pluginId, endpoint) {
1129
+ const hash = crypto.createHash("sha256").update(`${pluginId}
1130
+ ${endpoint}`).digest("hex").slice(0, 20);
1131
+ return path2.resolve(cacheDir, `${safeFilePart(pluginId)}-${hash}.json`);
1132
+ }
1133
+ function safeFilePart(value) {
1134
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "_");
1135
+ }
1136
+ function readRegistryCache(file) {
1137
+ if (!fs2.existsSync(file)) return null;
1138
+ try {
1139
+ const value = JSON.parse(fs2.readFileSync(file, "utf8"));
1140
+ if (typeof value.cachedAt !== "number" || !("payload" in value))
1141
+ return null;
1142
+ return { cachedAt: value.cachedAt, payload: value.payload };
1143
+ } catch {
1144
+ return null;
1145
+ }
1146
+ }
1147
+ function writeRegistryCache(file, payload) {
1148
+ fs2.mkdirSync(path2.dirname(file), { recursive: true });
1149
+ fs2.writeFileSync(
1150
+ file,
1151
+ `${JSON.stringify({ cachedAt: Date.now(), payload }, null, 2)}
1152
+ `
1153
+ );
1154
+ }
1155
+ function baselineLabel(kind) {
1156
+ switch (kind) {
1157
+ case "explicit":
1158
+ return "Explicit Contract Baseline";
1159
+ case "repository":
1160
+ return "Repository Contract Baseline";
1161
+ case "git":
1162
+ return "Git tag Contract Baseline";
1163
+ case "registry":
1164
+ return "Published Contract Baseline";
1165
+ case "installed":
1166
+ return "installed-plugin Contract Baseline";
1167
+ }
1168
+ }
1169
+ function markPublishSkipped(providers, attempts, selected) {
1170
+ for (const kind of ["explicit", "git", "repository", "installed"]) {
1171
+ if (providers.has(kind)) {
1172
+ attempts.push({
1173
+ kind,
1174
+ status: "skipped",
1175
+ message: `Skipped during publish validation because ${baselineLabel(selected)} is authoritative.`
1176
+ });
1177
+ }
1178
+ }
1179
+ }
1180
+
1181
+ // src/compatibility/compare.ts
1182
+ function compareExtensionContracts(options) {
1183
+ const {
1184
+ pluginId,
1185
+ currentPluginVersion,
1186
+ current,
1187
+ baseline,
1188
+ baselineResolution,
1189
+ currentDiagnostics = []
1190
+ } = options;
1191
+ if (!baseline) {
1192
+ return {
1193
+ pluginId,
1194
+ ...currentPluginVersion ? { currentPluginVersion } : {},
1195
+ status: "no-baseline",
1196
+ breaking: false,
1197
+ baseline: null,
1198
+ ...baselineResolution ? { baselineResolution } : {},
1199
+ added: [],
1200
+ removed: [],
1201
+ changed: [],
1202
+ preserved: [],
1203
+ likelyRenames: [],
1204
+ summary: { added: 0, removed: 0, changed: 0, preserved: 0, breaking: 0 }
1205
+ };
1206
+ }
1207
+ if (baseline.pluginId !== pluginId) {
1208
+ throw new Error(
1209
+ `Contract Baseline plugin '${baseline.pluginId}' does not match Current Extension Contract plugin '${pluginId}'.`
1210
+ );
1211
+ }
1212
+ const changes = [
1213
+ ...compareSurfaces(baseline.contract.surfaces, current.surfaces),
1214
+ ...compareSimple("event", baseline.contract.events, current.events),
1215
+ ...compareSimple(
1216
+ "provider",
1217
+ baseline.contract.providers,
1218
+ current.providers
1219
+ )
1220
+ ].map(
1221
+ (change) => attachDiagnosticSources(
1222
+ change,
1223
+ baseline.diagnostics ?? [],
1224
+ currentDiagnostics
1225
+ )
1226
+ ).sort(compareChanges);
1227
+ const added = changes.filter((change) => change.change === "added");
1228
+ const removed = changes.filter((change) => change.change === "removed");
1229
+ const changed = changes.filter((change) => change.change === "changed");
1230
+ const preserved = changes.filter((change) => change.change === "preserved");
1231
+ const likelyRenames = detectLikelyRenames(removed, added);
1232
+ const breakingCount = changes.filter((change) => change.breaking).length;
1233
+ return {
1234
+ pluginId,
1235
+ ...currentPluginVersion ? { currentPluginVersion } : {},
1236
+ status: breakingCount > 0 ? "breaking" : "compatible",
1237
+ breaking: breakingCount > 0,
1238
+ baseline: baseline.provenance,
1239
+ ...baselineResolution ? { baselineResolution } : {},
1240
+ added,
1241
+ removed,
1242
+ changed,
1243
+ preserved,
1244
+ likelyRenames,
1245
+ summary: {
1246
+ added: added.length,
1247
+ removed: removed.length,
1248
+ changed: changed.length,
1249
+ preserved: preserved.length,
1250
+ breaking: breakingCount
1251
+ }
1252
+ };
1253
+ }
1254
+ function compareSurfaces(baseline, current) {
1255
+ const before = new Map(
1256
+ baseline.map((surface) => [surfaceIdentity(surface), surface])
1257
+ );
1258
+ const after = new Map(
1259
+ current.map((surface) => [surfaceIdentity(surface), surface])
1260
+ );
1261
+ const identities = [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].sort();
1262
+ return identities.map((identity) => {
1263
+ const oldValue = before.get(identity);
1264
+ const newValue = after.get(identity);
1265
+ if (!oldValue) {
1266
+ return baseChange(
1267
+ "surface",
1268
+ identity,
1269
+ newValue.key,
1270
+ "added",
1271
+ false,
1272
+ [],
1273
+ newValue.surface
1274
+ );
1275
+ }
1276
+ if (!newValue) {
1277
+ return baseChange(
1278
+ "surface",
1279
+ identity,
1280
+ oldValue.key,
1281
+ "removed",
1282
+ true,
1283
+ ["Public extension surface was removed."],
1284
+ oldValue.surface
1285
+ );
1286
+ }
1287
+ const reasons = [];
1288
+ const pointChanges = comparePoints(oldValue.points, newValue.points);
1289
+ const operationChanges = compareOperations(
1290
+ oldValue.operations,
1291
+ newValue.operations
1292
+ );
1293
+ let breaking = false;
1294
+ if (!sameContract(oldValue.contract, newValue.contract)) {
1295
+ reasons.push(
1296
+ `Surface contract changed from ${oldValue.contract.id}@${oldValue.contract.version} to ${newValue.contract.id}@${newValue.contract.version}.`
1297
+ );
1298
+ breaking = true;
1299
+ }
1300
+ for (const point of pointChanges) {
1301
+ if (point.change === "removed")
1302
+ reasons.push(`Extension point '${point.key}' was removed.`);
1303
+ if (point.change === "changed")
1304
+ reasons.push(`Extension point '${point.key}' multiplicity changed.`);
1305
+ if (point.breaking) breaking = true;
1306
+ }
1307
+ for (const operation of operationChanges) {
1308
+ if (operation.change === "removed")
1309
+ reasons.push(`Operation '${operation.key}' was removed.`);
1310
+ if (operation.breaking) breaking = true;
1311
+ }
1312
+ if (reasons.length === 0 && pointChanges.length === 0 && operationChanges.length === 0) {
1313
+ return baseChange(
1314
+ "surface",
1315
+ identity,
1316
+ newValue.key,
1317
+ "preserved",
1318
+ false,
1319
+ [],
1320
+ newValue.surface
1321
+ );
1322
+ }
1323
+ if (pointChanges.some((change) => change.change === "added")) {
1324
+ reasons.push(
1325
+ ...pointChanges.filter((change) => change.change === "added").map((change) => `Extension point '${change.key}' was added.`)
1326
+ );
1327
+ }
1328
+ if (operationChanges.some((change) => change.change === "added")) {
1329
+ reasons.push(
1330
+ ...operationChanges.filter((change) => change.change === "added").map((change) => `Operation '${change.key}' was added.`)
1331
+ );
1332
+ }
1333
+ return {
1334
+ ...baseChange(
1335
+ "surface",
1336
+ identity,
1337
+ newValue.key,
1338
+ "changed",
1339
+ breaking,
1340
+ reasons,
1341
+ newValue.surface
1342
+ ),
1343
+ ...pointChanges.length > 0 ? { pointChanges } : {},
1344
+ ...operationChanges.length > 0 ? { operationChanges } : {}
1345
+ };
1346
+ });
1347
+ }
1348
+ function compareSimple(kind, baseline, current) {
1349
+ const before = new Map(baseline.map((entry) => [String(entry.key), entry]));
1350
+ const after = new Map(current.map((entry) => [String(entry.key), entry]));
1351
+ const keys = [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].sort();
1352
+ return keys.map((key) => {
1353
+ const oldValue = before.get(key);
1354
+ const newValue = after.get(key);
1355
+ const identity = `${kind}:${key}`;
1356
+ if (!oldValue) return baseChange(kind, identity, key, "added", false, []);
1357
+ if (!newValue) {
1358
+ return baseChange(kind, identity, key, "removed", true, [
1359
+ `Public extension ${kind} was removed.`
1360
+ ]);
1361
+ }
1362
+ const reasons = [];
1363
+ if (!sameContract(oldValue.contract, newValue.contract)) {
1364
+ reasons.push(
1365
+ `${title(kind)} contract changed from ${oldValue.contract.id}@${oldValue.contract.version} to ${newValue.contract.id}@${newValue.contract.version}.`
1366
+ );
1367
+ }
1368
+ if (oldValue.multiple !== newValue.multiple) {
1369
+ reasons.push(
1370
+ `${title(kind)} multiplicity changed from ${oldValue.multiple} to ${newValue.multiple}.`
1371
+ );
1372
+ }
1373
+ if (reasons.length === 0)
1374
+ return baseChange(kind, identity, key, "preserved", false, []);
1375
+ return baseChange(kind, identity, key, "changed", true, reasons);
1376
+ });
1377
+ }
1378
+ function comparePoints(baseline, current) {
1379
+ const before = new Map(baseline.map((point) => [String(point.key), point]));
1380
+ const after = new Map(current.map((point) => [String(point.key), point]));
1381
+ const changes = [];
1382
+ for (const key of [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].sort()) {
1383
+ const oldValue = before.get(key);
1384
+ const newValue = after.get(key);
1385
+ if (!oldValue) {
1386
+ changes.push({
1387
+ key,
1388
+ change: "added",
1389
+ breaking: false,
1390
+ afterMultiple: newValue.multiple
1391
+ });
1392
+ continue;
1393
+ }
1394
+ if (!newValue) {
1395
+ changes.push({
1396
+ key,
1397
+ change: "removed",
1398
+ breaking: true,
1399
+ beforeMultiple: oldValue.multiple
1400
+ });
1401
+ continue;
1402
+ }
1403
+ if (oldValue.multiple !== newValue.multiple) {
1404
+ changes.push({
1405
+ key,
1406
+ change: "changed",
1407
+ breaking: true,
1408
+ beforeMultiple: oldValue.multiple,
1409
+ afterMultiple: newValue.multiple
1410
+ });
1411
+ }
1412
+ }
1413
+ return changes;
1414
+ }
1415
+ function compareOperations(baseline, current) {
1416
+ const before = new Set(baseline.map(String));
1417
+ const after = new Set(current.map(String));
1418
+ const changes = [];
1419
+ for (const key of [.../* @__PURE__ */ new Set([...before, ...after])].sort()) {
1420
+ if (!before.has(key)) {
1421
+ changes.push({ key, change: "added", breaking: false });
1422
+ } else if (!after.has(key)) {
1423
+ changes.push({ key, change: "removed", breaking: true });
1424
+ }
1425
+ }
1426
+ return changes;
1427
+ }
1428
+ function detectLikelyRenames(removed, added) {
1429
+ const candidates = [];
1430
+ const consumedAdded = /* @__PURE__ */ new Set();
1431
+ for (const oldValue of removed) {
1432
+ const matches = added.filter(
1433
+ (newValue) => !consumedAdded.has(newValue.identity) && oldValue.kind === newValue.kind && oldValue.surface === newValue.surface && parentKey(oldValue.key) === parentKey(newValue.key)
1434
+ );
1435
+ if (matches.length !== 1) continue;
1436
+ const next = matches[0];
1437
+ consumedAdded.add(next.identity);
1438
+ candidates.push({
1439
+ kind: oldValue.kind,
1440
+ ...oldValue.surface ? { surface: oldValue.surface } : {},
1441
+ from: oldValue.key,
1442
+ to: next.key,
1443
+ confidence: "high",
1444
+ reason: "A removed and added public identity have the same extension kind and enclosing semantic scope. Review as a possible rename/refactor; no alias was applied automatically.",
1445
+ ...oldValue.source?.baseline ? { fromSource: oldValue.source.baseline } : {},
1446
+ ...next.source?.current ? { toSource: next.source.current } : {}
1447
+ });
1448
+ }
1449
+ return candidates.sort((left, right) => left.from.localeCompare(right.from));
1450
+ }
1451
+ function attachDiagnosticSources(change, baselineDiagnostics, currentDiagnostics) {
1452
+ const matches = (entry) => entry.kind === change.kind && entry.key === change.key && (change.kind !== "surface" || entry.surface === change.surface);
1453
+ const baseline = baselineDiagnostics.find(matches)?.source;
1454
+ const current = currentDiagnostics.find(matches)?.source;
1455
+ if (!baseline && !current) return change;
1456
+ return {
1457
+ ...change,
1458
+ source: {
1459
+ ...baseline ? { baseline } : {},
1460
+ ...current ? { current } : {}
1461
+ }
1462
+ };
1463
+ }
1464
+ function baseChange(kind, identity, key, change, breaking, reasons, surface) {
1465
+ return {
1466
+ kind,
1467
+ identity,
1468
+ key: String(key),
1469
+ ...surface ? { surface } : {},
1470
+ change,
1471
+ breaking,
1472
+ reasons
1473
+ };
1474
+ }
1475
+ function surfaceIdentity(surface) {
1476
+ return `surface:${surface.surface}:${surface.key}`;
1477
+ }
1478
+ function sameContract(left, right) {
1479
+ return left.id === right.id && left.version === right.version;
1480
+ }
1481
+ function parentKey(key) {
1482
+ const index = key.lastIndexOf(".");
1483
+ return index === -1 ? "" : key.slice(0, index);
1484
+ }
1485
+ function title(value) {
1486
+ return value.charAt(0).toUpperCase() + value.slice(1);
1487
+ }
1488
+ function compareChanges(left, right) {
1489
+ return left.identity.localeCompare(right.identity);
1490
+ }
1491
+
1492
+ // src/compatibility/report.ts
1493
+ function formatCompatibilityReport(report) {
1494
+ const lines = [];
1495
+ lines.push(
1496
+ `Plugmatica Compatibility Report \u2014 ${report.pluginId}${report.currentPluginVersion ? `@${report.currentPluginVersion}` : ""}`
1497
+ );
1498
+ lines.push(`Status: ${statusLabel(report.status)}`);
1499
+ if (report.baseline) {
1500
+ const provenance = [
1501
+ report.baseline.description,
1502
+ report.baseline.pluginVersion ? `version ${report.baseline.pluginVersion}` : null,
1503
+ report.baseline.registry ? `registry ${report.baseline.registry}` : null,
1504
+ report.baseline.cache ? `cache ${report.baseline.cache}` : null,
1505
+ report.baseline.reference ? `source ${report.baseline.reference}` : null
1506
+ ].filter(Boolean).join("; ");
1507
+ lines.push(`Baseline: ${provenance}`);
1508
+ } else {
1509
+ lines.push(
1510
+ "Baseline: none \u2014 no prior accepted contract exists, so compatibility cannot be determined."
1511
+ );
1512
+ }
1513
+ if (report.baselineResolution?.attempts.length) {
1514
+ lines.push("Baseline resolution:");
1515
+ for (const attempt of report.baselineResolution.attempts) {
1516
+ lines.push(` - ${attempt.kind}: ${attempt.status} \u2014 ${attempt.message}`);
1517
+ }
1518
+ }
1519
+ if (report.status === "no-baseline") return lines.join("\n");
1520
+ lines.push(
1521
+ `Summary: ${report.summary.added} added, ${report.summary.removed} removed, ${report.summary.changed} changed, ${report.summary.preserved} preserved; ${report.summary.breaking} breaking change(s).`
1522
+ );
1523
+ appendChanges(lines, "Added", report.added);
1524
+ appendChanges(lines, "Removed", report.removed);
1525
+ appendChanges(lines, "Changed", report.changed);
1526
+ if (report.likelyRenames.length > 0) {
1527
+ lines.push("Likely rename/refactor candidates:");
1528
+ for (const candidate of report.likelyRenames) {
1529
+ lines.push(
1530
+ ` - ${candidate.from} -> ${candidate.to} (${candidate.confidence})`
1531
+ );
1532
+ const fromSource = formatSourceHint(candidate.fromSource);
1533
+ const toSource = formatSourceHint(candidate.toSource);
1534
+ if (fromSource) lines.push(` from: ${fromSource}`);
1535
+ if (toSource) lines.push(` to: ${toSource}`);
1536
+ lines.push(` ${candidate.reason}`);
1537
+ }
1538
+ }
1539
+ return lines.join("\n");
1540
+ }
1541
+ var BreakingExtensionContractError = class extends Error {
1542
+ /**
1543
+ * Compatibility report for this release step.
1544
+ */
1545
+ report;
1546
+ constructor(report) {
1547
+ super(
1548
+ `Breaking extension-contract changes detected for '${report.pluginId}': ${report.summary.breaking} breaking change(s).`
1549
+ );
1550
+ this.name = "BreakingExtensionContractError";
1551
+ this.report = report;
1552
+ }
1553
+ };
1554
+ function enforceStrictCompatibility(report) {
1555
+ if (report.breaking) throw new BreakingExtensionContractError(report);
1556
+ }
1557
+ function appendChanges(lines, title2, changes) {
1558
+ if (changes.length === 0) return;
1559
+ lines.push(`${title2}:`);
1560
+ for (const change of changes) {
1561
+ lines.push(` - ${change.identity}${change.breaking ? " [BREAKING]" : ""}`);
1562
+ const source = change.change === "removed" ? change.source?.baseline : change.source?.current ?? change.source?.baseline;
1563
+ const sourceText = formatSourceHint(source);
1564
+ if (sourceText) lines.push(` source: ${sourceText}`);
1565
+ for (const reason of change.reasons) lines.push(` ${reason}`);
1566
+ }
1567
+ }
1568
+ function formatSourceHint(source) {
1569
+ if (!source) return null;
1570
+ const details = [source.component, source.semanticSourceName].filter(Boolean).join(" / ");
1571
+ if (source.file && details) return `${source.file} (${details})`;
1572
+ if (source.file) return source.file;
1573
+ return details || null;
1574
+ }
1575
+ function statusLabel(status) {
1576
+ switch (status) {
1577
+ case "no-baseline":
1578
+ return "NO BASELINE";
1579
+ case "compatible":
1580
+ return "COMPATIBLE";
1581
+ case "breaking":
1582
+ return "BREAKING";
1583
+ }
1584
+ }
1585
+
1586
+ // src/compatibility/workflow.ts
1587
+ import fs3 from "fs";
1588
+ import path3 from "path";
1589
+ function repositoryBaselinePath(projectRoot, configuredPath) {
1590
+ return configuredPath ? path3.resolve(projectRoot, configuredPath) : path3.resolve(projectRoot, "plugmatica.contract.json");
1591
+ }
1592
+ function initRepositoryContractBaseline(options) {
1593
+ const projectRoot = path3.resolve(
1594
+ options.projectRoot ?? path3.dirname(path3.resolve(options.manifestPath))
1595
+ );
1596
+ const target = repositoryBaselinePath(projectRoot, options.baselinePath);
1597
+ if (fs3.existsSync(target)) {
1598
+ throw new Error(
1599
+ `Repository Contract Baseline already exists at '${target}'. Use contract update to intentionally accept a new baseline.`
1600
+ );
1601
+ }
1602
+ const snapshot = buildCurrentContractSnapshot(options);
1603
+ writeContractBaselineFile(target, createRepositoryBaselineFile(snapshot));
1604
+ return { path: target, snapshot };
1605
+ }
1606
+ function updateRepositoryContractBaseline(options) {
1607
+ const projectRoot = path3.resolve(
1608
+ options.projectRoot ?? path3.dirname(path3.resolve(options.manifestPath))
1609
+ );
1610
+ const target = repositoryBaselinePath(projectRoot, options.baselinePath);
1611
+ if (!fs3.existsSync(target)) {
1612
+ throw new Error(
1613
+ `Repository Contract Baseline does not exist at '${target}'. Use contract init first.`
1614
+ );
1615
+ }
1616
+ const snapshot = buildCurrentContractSnapshot(options);
1617
+ writeContractBaselineFile(target, createRepositoryBaselineFile(snapshot));
1618
+ return { path: target, snapshot };
1619
+ }
1620
+ async function checkContractCompatibility(options) {
1621
+ const snapshot = buildCurrentContractSnapshot(options);
1622
+ const projectRoot = path3.resolve(
1623
+ options.projectRoot ?? path3.dirname(path3.resolve(options.manifestPath))
1624
+ );
1625
+ const resolution = await resolveContractBaseline({
1626
+ context: {
1627
+ pluginId: snapshot.pluginId,
1628
+ ...snapshot.pluginVersion ? { pluginVersion: snapshot.pluginVersion } : {},
1629
+ projectRoot,
1630
+ manifestPath: path3.resolve(options.manifestPath),
1631
+ mode: options.mode ?? "development",
1632
+ offline: Boolean(options.offline)
1633
+ },
1634
+ providers: options.providers ?? []
1635
+ });
1636
+ const report = compareExtensionContracts({
1637
+ pluginId: snapshot.pluginId,
1638
+ ...snapshot.pluginVersion ? { currentPluginVersion: snapshot.pluginVersion } : {},
1639
+ current: snapshot.contract,
1640
+ baseline: resolution.baseline,
1641
+ baselineResolution: resolution,
1642
+ currentDiagnostics: snapshot.diagnostics
1643
+ });
1644
+ return { report, resolution, snapshot };
1645
+ }
1646
+
1647
+ // src/boundaries/audit.ts
1648
+ import fs4 from "fs";
1649
+ import path4 from "path";
1650
+ import ts from "typescript";
1651
+ var allowedInternalDependencies = /* @__PURE__ */ new Map([
1652
+ ["@plugmatica/semantic-contracts", /* @__PURE__ */ new Set()],
1653
+ ["@plugmatica/i18n", /* @__PURE__ */ new Set()],
1654
+ ["@plugmatica/core-sdk", /* @__PURE__ */ new Set(["@plugmatica/semantic-contracts"])],
1655
+ ["@plugmatica/api-client", /* @__PURE__ */ new Set()],
1656
+ ["@plugmatica/ui-kit", /* @__PURE__ */ new Set(["@plugmatica/semantic-contracts", "@plugmatica/i18n"])],
1657
+ ["@plugmatica/data-viz", /* @__PURE__ */ new Set(["@plugmatica/ui-kit"])],
1658
+ ["@plugmatica/graph", /* @__PURE__ */ new Set(["@plugmatica/ui-kit"])],
1659
+ [
1660
+ "@plugmatica/plugin-sdk",
1661
+ /* @__PURE__ */ new Set(["@plugmatica/core-sdk", "@plugmatica/i18n", "@plugmatica/ui-kit"])
1662
+ ],
1663
+ ["@plugmatica/plugin-query", /* @__PURE__ */ new Set(["@plugmatica/plugin-sdk"])],
1664
+ ["@plugmatica/blocks", /* @__PURE__ */ new Set(["@plugmatica/plugin-sdk", "@plugmatica/ui-kit"])],
1665
+ [
1666
+ "@plugmatica/plugin-build",
1667
+ /* @__PURE__ */ new Set(["@plugmatica/core-sdk", "@plugmatica/i18n"])
1668
+ ],
1669
+ [
1670
+ "@plugmatica/plugin-devtools",
1671
+ /* @__PURE__ */ new Set([
1672
+ "@plugmatica/core-sdk",
1673
+ "@plugmatica/plugin-sdk",
1674
+ "@plugmatica/ui-kit"
1675
+ ])
1676
+ ]
1677
+ ]);
1678
+ function auditFrontendPackageBoundaries(frontendRoot) {
1679
+ const root = path4.resolve(frontendRoot);
1680
+ const issues = [];
1681
+ for (const packageJson of findPackageJsonFiles(root)) {
1682
+ const manifest = JSON.parse(fs4.readFileSync(packageJson, "utf8"));
1683
+ const packageName = typeof manifest.name === "string" ? manifest.name : null;
1684
+ if (!packageName) continue;
1685
+ const allowed = allowedInternalDependencies.get(packageName);
1686
+ if (!allowed) continue;
1687
+ for (const dependency of internalDependencies(manifest)) {
1688
+ if (!allowed.has(dependency)) {
1689
+ issues.push({
1690
+ code: "forbidden_internal_dependency",
1691
+ file: relative(root, packageJson),
1692
+ message: `${packageName} must not depend on ${dependency}. Allowed Plugmatica dependencies: ${[...allowed].join(", ") || "none"}.`
1693
+ });
1694
+ }
1695
+ }
1696
+ }
1697
+ for (const file of sourceFiles(root)) {
1698
+ const text = fs4.readFileSync(file, "utf8");
1699
+ const packageName = owningPackageName(root, file);
1700
+ const pluginAuthorSource = isPluginAuthorSource(root, file);
1701
+ const allowed = !pluginAuthorSource && packageName ? allowedInternalDependencies.get(packageName) : void 0;
1702
+ for (const reference of importReferences(text, file)) {
1703
+ const specifier = reference.specifier;
1704
+ if (specifier.includes("runtime-shell") && !isRuntimeShellFile(root, file)) {
1705
+ issues.push({
1706
+ code: "runtime_shell_leak",
1707
+ file: relative(root, file),
1708
+ message: `Host orchestration '${specifier}' must not be imported outside apps/runtime-shell. Use core-sdk, ui-kit, plugin-sdk or an explicit host adapter instead.`
1709
+ });
1710
+ }
1711
+ const internal = internalPackageName(specifier);
1712
+ if (allowed && internal && !allowed.has(internal) && internal !== packageName) {
1713
+ issues.push({
1714
+ code: "forbidden_internal_dependency",
1715
+ file: relative(root, file),
1716
+ message: `${packageName} imports ${specifier}, which violates the allowed frontend package direction.`
1717
+ });
1718
+ }
1719
+ if (pluginAuthorSource && isHostOnlyPluginImport(specifier)) {
1720
+ issues.push({
1721
+ code: "plugin_host_internal_import",
1722
+ file: relative(root, file),
1723
+ message: `Plugin source must not import host-only API '${specifier}'. Normal plugins use the public @plugmatica/plugin-sdk, @plugmatica/ui-kit and build/testing contracts.`
1724
+ });
1725
+ }
1726
+ if (pluginAuthorSource && specifier === "@plugmatica/ui-kit" && reference.importedNames.some(
1727
+ (name) => UI_KIT_HOST_BRIDGE_EXPORTS.has(name)
1728
+ )) {
1729
+ const names = reference.importedNames.filter(
1730
+ (name) => UI_KIT_HOST_BRIDGE_EXPORTS.has(name)
1731
+ );
1732
+ issues.push({
1733
+ code: "plugin_host_internal_import",
1734
+ file: relative(root, file),
1735
+ message: `Plugin source imports UI-kit host runtime bridge ${names.join(", ")}. These APIs are host-only; normal plugins consume semantic UI components instead.`
1736
+ });
1737
+ }
1738
+ }
1739
+ }
1740
+ const identityFile = path4.join(
1741
+ root,
1742
+ "packages/semantic-contracts/src/extensions/identity.ts"
1743
+ );
1744
+ if (fs4.existsSync(identityFile)) {
1745
+ const text = fs4.readFileSync(identityFile, "utf8");
1746
+ for (const { specifier } of importReferences(text, identityFile)) {
1747
+ if (/compatibility|baseline|registry/i.test(specifier)) {
1748
+ issues.push({
1749
+ code: "identity_history_leak",
1750
+ file: relative(root, identityFile),
1751
+ message: `Canonical identity derivation imports historical/registry concern '${specifier}'. Identity must depend on current semantic inputs only.`
1752
+ });
1753
+ }
1754
+ }
1755
+ }
1756
+ return {
1757
+ root,
1758
+ issues: issues.sort(
1759
+ (left, right) => left.file.localeCompare(right.file) || left.code.localeCompare(right.code) || left.message.localeCompare(right.message)
1760
+ )
1761
+ };
1762
+ }
1763
+ function assertFrontendPackageBoundaries(frontendRoot) {
1764
+ const audit = auditFrontendPackageBoundaries(frontendRoot);
1765
+ if (audit.issues.length === 0) return;
1766
+ throw new Error(formatPackageBoundaryAudit(audit));
1767
+ }
1768
+ function formatPackageBoundaryAudit(audit) {
1769
+ if (audit.issues.length === 0) return "Frontend package boundaries: OK";
1770
+ return [
1771
+ `Frontend package boundaries: ${audit.issues.length} violation(s)`,
1772
+ ...audit.issues.map(
1773
+ (issue2) => `- ${issue2.file} [${issue2.code}] ${issue2.message}`
1774
+ )
1775
+ ].join("\n");
1776
+ }
1777
+ function findPackageJsonFiles(root) {
1778
+ const roots = [path4.join(root, "packages"), path4.join(root, "apps")];
1779
+ return roots.flatMap((directory) => {
1780
+ if (!fs4.existsSync(directory)) return [];
1781
+ return fs4.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path4.join(directory, entry.name, "package.json")).filter((file) => fs4.existsSync(file));
1782
+ });
1783
+ }
1784
+ function sourceFiles(root) {
1785
+ const result = [];
1786
+ const walk2 = (directory) => {
1787
+ if (!fs4.existsSync(directory)) return;
1788
+ for (const entry of fs4.readdirSync(directory, { withFileTypes: true })) {
1789
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === "generated")
1790
+ continue;
1791
+ const target = path4.join(directory, entry.name);
1792
+ if (entry.isDirectory()) {
1793
+ if (isDetachedConsumerFixture(root, target)) continue;
1794
+ walk2(target);
1795
+ } else if (/\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name))
1796
+ result.push(target);
1797
+ }
1798
+ };
1799
+ walk2(path4.join(root, "packages"));
1800
+ walk2(path4.join(root, "apps"));
1801
+ return result.sort();
1802
+ }
1803
+ function isDetachedConsumerFixture(root, directory) {
1804
+ const value = relative(root, directory);
1805
+ return /^(?:packages|apps)\/[^/]+\/scripts\/release\/(?:consumer-fixture|standalone-fixture)(?:\/|$)/.test(
1806
+ value
1807
+ );
1808
+ }
1809
+ function internalDependencies(manifest) {
1810
+ const result = /* @__PURE__ */ new Set();
1811
+ for (const field of [
1812
+ "dependencies",
1813
+ "peerDependencies",
1814
+ "optionalDependencies"
1815
+ ]) {
1816
+ const record2 = manifest[field];
1817
+ if (!record2 || typeof record2 !== "object" || Array.isArray(record2))
1818
+ continue;
1819
+ for (const name of Object.keys(record2)) {
1820
+ if (name.startsWith("@plugmatica/")) result.add(name);
1821
+ }
1822
+ }
1823
+ return [...result].sort();
1824
+ }
1825
+ function owningPackageName(root, file) {
1826
+ const relativeFile = relative(root, file);
1827
+ const match = relativeFile.match(/^(packages|apps)\/([^/]+)\//);
1828
+ if (!match) return null;
1829
+ const packageJson = path4.join(root, match[1], match[2], "package.json");
1830
+ if (!fs4.existsSync(packageJson)) return null;
1831
+ const manifest = JSON.parse(fs4.readFileSync(packageJson, "utf8"));
1832
+ return typeof manifest.name === "string" ? manifest.name : null;
1833
+ }
1834
+ function importReferences(text, file) {
1835
+ const source = ts.createSourceFile(
1836
+ file,
1837
+ text,
1838
+ ts.ScriptTarget.Latest,
1839
+ true,
1840
+ file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
1841
+ );
1842
+ const result = /* @__PURE__ */ new Map();
1843
+ const add = (specifier, typeOnly, importedNames = []) => {
1844
+ const current = result.get(specifier);
1845
+ result.set(specifier, {
1846
+ specifier,
1847
+ // If a module is imported both as a type and as a runtime value, it is a
1848
+ // runtime dependency for boundary purposes.
1849
+ typeOnly: current ? current.typeOnly && typeOnly : typeOnly,
1850
+ importedNames: [
1851
+ .../* @__PURE__ */ new Set([...current?.importedNames ?? [], ...importedNames])
1852
+ ].sort()
1853
+ });
1854
+ };
1855
+ const visit = (node) => {
1856
+ if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
1857
+ add(
1858
+ node.moduleSpecifier.text,
1859
+ importDeclarationIsTypeOnly(node),
1860
+ importedNamesFromImport(node)
1861
+ );
1862
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) {
1863
+ add(
1864
+ node.moduleSpecifier.text,
1865
+ exportDeclarationIsTypeOnly(node),
1866
+ importedNamesFromExport(node)
1867
+ );
1868
+ } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
1869
+ const expression = node.moduleReference.expression;
1870
+ if (expression && ts.isStringLiteralLike(expression))
1871
+ add(expression.text, Boolean(node.isTypeOnly));
1872
+ } else if (ts.isCallExpression(node) && node.arguments.length === 1) {
1873
+ const argument = node.arguments[0];
1874
+ if (argument && ts.isStringLiteralLike(argument)) {
1875
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword)
1876
+ add(argument.text, false);
1877
+ if (ts.isIdentifier(node.expression) && node.expression.text === "require")
1878
+ add(argument.text, false);
1879
+ }
1880
+ }
1881
+ ts.forEachChild(node, visit);
1882
+ };
1883
+ visit(source);
1884
+ return [...result.values()];
1885
+ }
1886
+ function importedNamesFromImport(node) {
1887
+ const clause = node.importClause;
1888
+ if (!clause) return [];
1889
+ const result = [];
1890
+ if (clause.name) result.push("default");
1891
+ const bindings = clause.namedBindings;
1892
+ if (bindings && ts.isNamedImports(bindings)) {
1893
+ for (const element of bindings.elements) {
1894
+ result.push((element.propertyName ?? element.name).text);
1895
+ }
1896
+ }
1897
+ return result;
1898
+ }
1899
+ function importedNamesFromExport(node) {
1900
+ if (!node.exportClause || !ts.isNamedExports(node.exportClause)) return [];
1901
+ return node.exportClause.elements.map(
1902
+ (element) => (element.propertyName ?? element.name).text
1903
+ );
1904
+ }
1905
+ function importDeclarationIsTypeOnly(node) {
1906
+ const clause = node.importClause;
1907
+ if (!clause) return false;
1908
+ if (clause.isTypeOnly) return true;
1909
+ if (clause.name) return false;
1910
+ const bindings = clause.namedBindings;
1911
+ if (!bindings || ts.isNamespaceImport(bindings)) return false;
1912
+ return bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly);
1913
+ }
1914
+ function exportDeclarationIsTypeOnly(node) {
1915
+ if (node.isTypeOnly) return true;
1916
+ const clause = node.exportClause;
1917
+ if (!clause || !ts.isNamedExports(clause)) return false;
1918
+ return clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly);
1919
+ }
1920
+ function internalPackageName(specifier) {
1921
+ if (!specifier.startsWith("@plugmatica/")) return null;
1922
+ const [scope, name] = specifier.split("/");
1923
+ return scope && name ? `${scope}/${name}` : null;
1924
+ }
1925
+ function isRuntimeShellFile(root, file) {
1926
+ return relative(root, file).startsWith("apps/runtime-shell/");
1927
+ }
1928
+ function isPluginAuthorSource(root, file) {
1929
+ const value = relative(root, file);
1930
+ return value.startsWith("packages/reference-plugins/plugins/") || value.startsWith("packages/plugin-build/templates/") || value.startsWith("packages/plugin-build/test-fixtures/") || value.startsWith("packages/plugin-build/test-fixtures-invalid/");
1931
+ }
1932
+ var UI_KIT_HOST_BRIDGE_EXPORTS = /* @__PURE__ */ new Set([
1933
+ "UiExtensionRuntimeProvider",
1934
+ "useUiExtensionEnvironmentKey",
1935
+ "useUiExtensionRuntime"
1936
+ ]);
1937
+ function isHostOnlyPluginImport(specifier) {
1938
+ if (specifier.includes("runtime-shell")) return true;
1939
+ if (specifier === "@plugmatica/plugin-sdk/host") return true;
1940
+ if (specifier === "@plugmatica/plugin-sdk/extension-index") return true;
1941
+ if (specifier === "@plugmatica/ui-kit/host" || specifier.startsWith("@plugmatica/ui-kit/host/") || specifier === "@plugmatica/ui-kit/semantic" || specifier.startsWith("@plugmatica/ui-kit/semantic/"))
1942
+ return true;
1943
+ if (specifier.startsWith("@plugmatica/ui-kit/auto-extensibility"))
1944
+ return true;
1945
+ if (specifier.startsWith("@plugmatica/ui-kit/src/")) return true;
1946
+ return [
1947
+ "@plugmatica/api-client",
1948
+ "@plugmatica/auth-client",
1949
+ "@plugmatica/plugin-devtools"
1950
+ ].some(
1951
+ (packageName) => specifier === packageName || specifier.startsWith(`${packageName}/`)
1952
+ );
1953
+ }
1954
+ function relative(root, file) {
1955
+ return path4.relative(root, file).split(path4.sep).join("/");
1956
+ }
1957
+ function auditRepositoryPluginAuthoringBoundaries(repositoryRoot) {
1958
+ const root = path4.resolve(repositoryRoot);
1959
+ const pluginsRoot = path4.join(root, "plugins");
1960
+ const issues = [];
1961
+ if (!fs4.existsSync(pluginsRoot)) return { root, issues };
1962
+ const packages = /* @__PURE__ */ new Map();
1963
+ for (const entry of fs4.readdirSync(pluginsRoot, { withFileTypes: true })) {
1964
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
1965
+ const pluginRoot = path4.join(pluginsRoot, entry.name);
1966
+ const frontendRoot = path4.join(pluginRoot, "frontend");
1967
+ const packageJson = path4.join(frontendRoot, "package.json");
1968
+ if (!fs4.existsSync(packageJson)) continue;
1969
+ const manifest = JSON.parse(fs4.readFileSync(packageJson, "utf8"));
1970
+ if (typeof manifest.name === "string") {
1971
+ packages.set(manifest.name, { pluginRoot, frontendRoot });
1972
+ }
1973
+ }
1974
+ for (const [packageName, owner] of packages) {
1975
+ const packageJson = path4.join(owner.frontendRoot, "package.json");
1976
+ const manifest = JSON.parse(fs4.readFileSync(packageJson, "utf8"));
1977
+ for (const dependency of internalDependencies(manifest)) {
1978
+ if (dependency !== packageName && packages.has(dependency)) {
1979
+ issues.push({
1980
+ code: "sibling_plugin_frontend_dependency",
1981
+ file: relative(root, packageJson),
1982
+ message: `${packageName} must not depend on sibling plugin frontend package ${dependency}. Target the public runtime capability with extensionTarget.*(...) instead.`
1983
+ });
1984
+ }
1985
+ }
1986
+ const src = path4.join(owner.frontendRoot, "src");
1987
+ for (const file of walkSourceFiles(src)) {
1988
+ const text = fs4.readFileSync(file, "utf8");
1989
+ for (const reference of importReferences(text, file)) {
1990
+ const importedPackage = packageNameFromSpecifier(reference.specifier);
1991
+ if (importedPackage && importedPackage !== packageName && packages.has(importedPackage)) {
1992
+ issues.push({
1993
+ code: "sibling_plugin_frontend_dependency",
1994
+ file: relative(root, file),
1995
+ message: `${packageName} imports sibling plugin frontend package ${reference.specifier}. Keep the plugin self-contained and target the public runtime capability instead.`
1996
+ });
1997
+ }
1998
+ }
1999
+ if (/\b__pmTarget\s*:/.test(text)) {
2000
+ issues.push({
2001
+ code: "handwritten_extension_target_token",
2002
+ file: relative(root, file),
2003
+ message: "Plugin source contains a hand-authored __pmTarget token. Use extensionTarget.*(...) for provider-independent capability targeting or generated targets for intentional concrete coupling."
2004
+ });
2005
+ }
2006
+ }
2007
+ }
2008
+ return {
2009
+ root,
2010
+ issues: issues.sort(
2011
+ (left, right) => left.file.localeCompare(right.file) || left.code.localeCompare(right.code) || left.message.localeCompare(right.message)
2012
+ )
2013
+ };
2014
+ }
2015
+ function walkSourceFiles(directory) {
2016
+ const output = [];
2017
+ const visit = (current) => {
2018
+ if (!fs4.existsSync(current)) return;
2019
+ for (const entry of fs4.readdirSync(current, { withFileTypes: true })) {
2020
+ if (entry.name === "generated" || entry.name === "dist" || entry.name === "node_modules")
2021
+ continue;
2022
+ const target = path4.join(current, entry.name);
2023
+ if (entry.isDirectory()) visit(target);
2024
+ else if (entry.isFile() && /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !/\.d\.[cm]?ts$/.test(entry.name))
2025
+ output.push(target);
2026
+ }
2027
+ };
2028
+ visit(directory);
2029
+ return output.sort();
2030
+ }
2031
+ function packageNameFromSpecifier(specifier) {
2032
+ if (specifier.startsWith("@")) {
2033
+ const parts = specifier.split("/");
2034
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null;
2035
+ }
2036
+ const [first] = specifier.split("/");
2037
+ return first && !first.startsWith(".") ? first : null;
2038
+ }
2039
+
2040
+ // src/inspection/inspect.ts
2041
+ import fs5 from "fs";
2042
+ import path5 from "path";
2043
+ function inspectPlugin(options) {
2044
+ const snapshot = buildCurrentContractSnapshot(options);
2045
+ const source = JSON.parse(
2046
+ fs5.readFileSync(path5.resolve(options.manifestPath), "utf8")
2047
+ );
2048
+ const manifest = materializeGeneratedFrontendManifest(
2049
+ source,
2050
+ snapshot.compilerResult
2051
+ );
2052
+ const frontend = manifest.frontend;
2053
+ const graph = buildPluginContractGraph({
2054
+ manifest,
2055
+ compilerResult: snapshot.compilerResult
2056
+ });
2057
+ const graphValidation = validateExtensionDependencyGraph([manifest], {
2058
+ partial: true
2059
+ });
2060
+ return {
2061
+ pluginId: snapshot.pluginId,
2062
+ ...snapshot.pluginVersion ? { pluginVersion: snapshot.pluginVersion } : {},
2063
+ summary: {
2064
+ sourceFiles: snapshot.compilerResult.files.length,
2065
+ semanticNodes: snapshot.compilerResult.nodes.length,
2066
+ surfaces: snapshot.contract.surfaces.length,
2067
+ events: snapshot.contract.events.length,
2068
+ providers: snapshot.contract.providers.length,
2069
+ contributions: frontend?.extensions?.length ?? 0,
2070
+ dependencies: manifest.dependencies?.plugins?.length ?? 0,
2071
+ exposedModules: Array.isArray(frontend?.exposes) ? frontend.exposes.length : 0
2072
+ },
2073
+ currentExtensionContract: snapshot.contract,
2074
+ graph,
2075
+ graphValidation
2076
+ };
2077
+ }
2078
+ var graphIssueRepair = {
2079
+ duplicate_plugin_key: "Use a distinct key for each enabled plugin manifest.",
2080
+ self_dependency: "Remove this plugin from its own dependencies.plugins list.",
2081
+ missing_required_dependency: "Install/enable the declared dependency in the validation set, then check its version requirement.",
2082
+ incompatible_dependency_version: "Align dependencies.plugins version requirements with the installed provider version, or upgrade the provider.",
2083
+ undeclared_target_dependency: "Declare the target plugin in dependencies.plugins, or target a declared capability when provider selection is intentional.",
2084
+ unavailable_required_target: "Include the required target plugin in the validated manifest set and verify it is enabled at runtime.",
2085
+ unavailable_required_capability: "Include/install a provider exposing the required extension contract; check available provider versions.",
2086
+ ambiguous_capability_provider: "Select one compatible provider or target a specific plugin when a fixed owner is intended.",
2087
+ unavailable_required_shell_app: "Add or enable a plugin exposing the required shell application, then validate the whole manifest set.",
2088
+ ambiguous_shell_app_owner: "Ensure only one enabled plugin declares this shell application key.",
2089
+ missing_target_surface: "Compare the target plugin's declared extensionSurfaces and use an exact surface and key.",
2090
+ missing_target_point: "Use a point declared by the target extension surface, or ask its owner to publish that point.",
2091
+ missing_target_operation: "Use an operation published by the target extension surface.",
2092
+ missing_target_event: "Use a declared extension event key from the target plugin.",
2093
+ missing_target_provider: "Use a declared extension provider key from the target plugin.",
2094
+ incompatible_target_contract: "Align the extension contract ID and version with the target's published contract.",
2095
+ unexposed_extension_module: "Add the referenced module specifier to frontend.exposes or change the extension to a published module."
2096
+ };
2097
+ function formatPluginInspection(inspection) {
2098
+ const s = inspection.summary;
2099
+ const lines = [
2100
+ `Plugmatica Plugin Inspection \u2014 ${inspection.pluginId}${inspection.pluginVersion ? `@${inspection.pluginVersion}` : ""}`,
2101
+ `Source: ${s.sourceFiles} file(s), ${s.semanticNodes} semantic node(s)`,
2102
+ `Current Extension Contract: ${s.surfaces} surface(s), ${s.events} event(s), ${s.providers} provider(s)`,
2103
+ `Contributions: ${s.contributions}; dependencies: ${s.dependencies}; exposed modules: ${s.exposedModules}`,
2104
+ `Graph validation: ${inspection.graphValidation.issues.length === 0 ? "OK" : `${inspection.graphValidation.issues.length} issue(s)`}`
2105
+ ];
2106
+ for (const issue2 of inspection.graphValidation.issues) {
2107
+ lines.push(
2108
+ ` - ${issue2.severity.toUpperCase()} [${issue2.code}] ${issue2.message}`
2109
+ );
2110
+ const repair = graphIssueRepair[issue2.code];
2111
+ if (repair) lines.push(` Fix: ${repair}`);
2112
+ }
2113
+ if (inspection.graphValidation.dependencyCycles.length > 0) {
2114
+ lines.push(
2115
+ `Dependency cycles (allowed): ${inspection.graphValidation.dependencyCycles.map((cycle) => cycle.join(" -> ")).join("; ")}`
2116
+ );
2117
+ }
2118
+ return lines.join("\n");
2119
+ }
2120
+ function formatExtensionInventory(inspection) {
2121
+ const lines = [
2122
+ `Plugmatica Extensions \u2014 ${inspection.pluginId}${inspection.pluginVersion ? `@${inspection.pluginVersion}` : ""}`,
2123
+ "Surfaces:",
2124
+ ...inspection.currentExtensionContract.surfaces.length > 0 ? inspection.currentExtensionContract.surfaces.map(
2125
+ (surface) => ` - ${surface.surface}:${surface.key} (${surface.contract.id}@${surface.contract.version}) points=[${surface.points.map((point) => point.key).join(", ")}] operations=[${surface.operations.join(", ")}]`
2126
+ ) : [" - none"],
2127
+ "Events:",
2128
+ ...inspection.currentExtensionContract.events.length > 0 ? inspection.currentExtensionContract.events.map(
2129
+ (event) => ` - ${event.key} (${event.contract.id}@${event.contract.version})`
2130
+ ) : [" - none"],
2131
+ "Providers:",
2132
+ ...inspection.currentExtensionContract.providers.length > 0 ? inspection.currentExtensionContract.providers.map(
2133
+ (provider) => ` - ${provider.key} (${provider.contract.id}@${provider.contract.version})`
2134
+ ) : [" - none"]
2135
+ ];
2136
+ const contributions = inspection.graph.nodes.filter(
2137
+ (node) => node.kind === "contribution"
2138
+ );
2139
+ lines.push("Contributions:");
2140
+ lines.push(
2141
+ ...contributions.length > 0 ? contributions.map((node) => ` - ${node.label}`) : [" - none"]
2142
+ );
2143
+ return lines.join("\n");
2144
+ }
2145
+
2146
+ // src/inspection/workflow-nodes.ts
2147
+ import fs6 from "fs";
2148
+ import path6 from "path";
2149
+ import { spawnSync as spawnSync2 } from "child_process";
2150
+ var POINTS = ["catalog", "editor", "presentation"];
2151
+ var CONTRACT = "plugmatica.workflow.node.host";
2152
+ var VERSION = "^1.1.0";
2153
+ function record(value) {
2154
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2155
+ }
2156
+ function str(value) {
2157
+ return typeof value === "string" ? value : "";
2158
+ }
2159
+ function entries(value) {
2160
+ return Array.isArray(value) ? value.filter(record) : [];
2161
+ }
2162
+ function asRegistry(value) {
2163
+ const list = Array.isArray(value) ? value : record(value) ? Array.isArray(value.nodes) ? value.nodes : Array.isArray(value.nodeTypes) ? value.nodeTypes : null : null;
2164
+ if (!list || !list.every((item) => record(item) && str(item.nodeType).length > 0)) return null;
2165
+ return list;
2166
+ }
2167
+ function toKebab(value) {
2168
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
2169
+ }
2170
+ function inspectWorkflowNodePackage(options) {
2171
+ const root = path6.resolve(options.packageRoot);
2172
+ const issues = [];
2173
+ const error = (code, message) => issues.push({ severity: "error", scope: "package", code, message });
2174
+ const registryError = (code, message) => issues.push({ severity: "error", scope: "registry", code, message });
2175
+ const warn = (code, message) => issues.push({ severity: "warning", scope: "package", code, message });
2176
+ const result = {
2177
+ packageRoot: root,
2178
+ pluginKey: "",
2179
+ version: "",
2180
+ packageStatus: "invalid",
2181
+ registryStatus: "not_checked",
2182
+ browserStatus: "not_checked",
2183
+ nodes: [],
2184
+ triggers: [],
2185
+ modules: [],
2186
+ issues
2187
+ };
2188
+ function asset(relative3) {
2189
+ if (!relative3 || path6.isAbsolute(relative3) || relative3.split(/[\\/]/).some((s) => !s || s === "." || s === "..")) {
2190
+ error("unsafe_package_path", `Unsafe package asset path '${relative3}'`);
2191
+ return null;
2192
+ }
2193
+ let target = root;
2194
+ try {
2195
+ if (fs6.lstatSync(root).isSymbolicLink()) throw new Error("package root is a symlink");
2196
+ for (const segment of relative3.split(/[\\/]/)) {
2197
+ target = path6.join(target, segment);
2198
+ if (fs6.lstatSync(target).isSymbolicLink()) throw new Error("symlink is not allowed");
2199
+ }
2200
+ if (!fs6.statSync(target).isFile()) throw new Error("not a regular file");
2201
+ return target;
2202
+ } catch (cause) {
2203
+ error("package_asset_missing", `Invalid or missing '${relative3}': ${cause instanceof Error ? cause.message : String(cause)}`);
2204
+ return null;
2205
+ }
2206
+ }
2207
+ function json(relative3) {
2208
+ const location = asset(relative3);
2209
+ if (!location) return null;
2210
+ try {
2211
+ const value = JSON.parse(fs6.readFileSync(location, "utf8"));
2212
+ if (!record(value)) throw new Error("expected JSON object");
2213
+ return value;
2214
+ } catch (cause) {
2215
+ error("package_json_invalid", `${relative3}: ${cause instanceof Error ? cause.message : String(cause)}`);
2216
+ return null;
2217
+ }
2218
+ }
2219
+ const manifest = json("manifest.json");
2220
+ if (!manifest) return result;
2221
+ result.pluginKey = str(manifest.key);
2222
+ result.version = str(manifest.version);
2223
+ if (!result.pluginKey || !result.version) error("manifest_identity_missing", "manifest.json needs a plugin key and version");
2224
+ const backend = record(manifest.backend) ? manifest.backend : null;
2225
+ const frontend = record(manifest.frontend) ? manifest.frontend : null;
2226
+ if (manifest.backend != null && !backend) error("backend_facet_invalid", "Packaged backend facet must be an object");
2227
+ if (manifest.frontend != null && !frontend) error("frontend_facet_invalid", "Packaged frontend facet must be an object");
2228
+ const descriptor = backend ? json("backend/descriptor.json") : null;
2229
+ if (backend) {
2230
+ const wasmPath = str(backend.entryPoint);
2231
+ const wasm = asset(wasmPath);
2232
+ if (wasm) {
2233
+ const fd = fs6.openSync(wasm, "r");
2234
+ try {
2235
+ const header = Buffer.alloc(8);
2236
+ if (fs6.readSync(fd, header, 0, 8, 0) !== 8 || header.toString("hex") !== "0061736d01000000") {
2237
+ error("invalid_wasm", "backend entry point is not a WebAssembly v1 module");
2238
+ }
2239
+ } finally {
2240
+ fs6.closeSync(fd);
2241
+ }
2242
+ }
2243
+ }
2244
+ if (descriptor?.workflowNodes != null && (!Array.isArray(descriptor.workflowNodes) || descriptor.workflowNodes.some((item) => !record(item) || !str(item.nodeType)))) {
2245
+ error("backend_nodes_invalid", "Compiled backend workflowNodes must be an array of node descriptors with nodeType");
2246
+ }
2247
+ if (manifest.workflowNodes != null && (!Array.isArray(manifest.workflowNodes) || manifest.workflowNodes.some((item) => !record(item) || !str(item.nodeType)))) {
2248
+ error("manifest_nodes_invalid", "Packaged workflowNodes must be an array of node descriptors with nodeType");
2249
+ }
2250
+ let projectedNodes = [];
2251
+ if (backend && descriptor) {
2252
+ try {
2253
+ projectedNodes = projectBackendManifest({ key: result.pluginKey }, descriptor).workflowNodes;
2254
+ assertBackendManifestProjection(manifest, descriptor);
2255
+ } catch (cause) {
2256
+ error("backend_projection_invalid", `Packaged backend projection differs from the compiled descriptor or is invalid: ${cause instanceof Error ? cause.message : String(cause)}`);
2257
+ }
2258
+ } else if (manifest.workflowNodes !== void 0 && !backend) {
2259
+ error("manifest_nodes_without_backend", "Workflow executable nodes require an installed backend facet");
2260
+ }
2261
+ const declaredNodes = entries(descriptor?.workflowNodes).filter((item) => str(item.nodeType));
2262
+ const packagedNodes = entries(manifest.workflowNodes).filter((item) => str(item.nodeType));
2263
+ const generatedTriggers = projectedNodes.filter((item) => item.kind === "trigger");
2264
+ for (const trigger of generatedTriggers) {
2265
+ const event = record(trigger.trigger) ? str(trigger.trigger.event) : "";
2266
+ result.triggers.push({
2267
+ nodeType: str(trigger.nodeType),
2268
+ event,
2269
+ contractVersion: typeof trigger.contractVersion === "number" ? trigger.contractVersion : null,
2270
+ contractFingerprint: str(trigger.contractFingerprint) || null,
2271
+ registryStatus: "not_checked"
2272
+ });
2273
+ }
2274
+ const backendCommands = new Set(entries(descriptor?.commands).map((command) => str(command.key)).filter(Boolean));
2275
+ const byType = new Map(packagedNodes.map((item) => [str(item.nodeType), item]));
2276
+ const seenTypes = /* @__PURE__ */ new Set();
2277
+ if (new Set(packagedNodes.map((item) => str(item.nodeType))).size !== packagedNodes.length) {
2278
+ error("duplicate_manifest_node", "Packaged Workflow action list has duplicate nodeType entries");
2279
+ }
2280
+ for (const action of declaredNodes) {
2281
+ const nodeType = str(action.nodeType);
2282
+ if (seenTypes.has(nodeType)) error("duplicate_backend_node", `Duplicate backend node '${nodeType}'`);
2283
+ seenTypes.add(nodeType);
2284
+ if (!nodeType.startsWith(`${result.pluginKey}:action:`) || action.kind !== "action") {
2285
+ error("foreign_or_invalid_node", `Backend action '${nodeType}' is not owned by the package`);
2286
+ }
2287
+ const packaged = byType.get(nodeType);
2288
+ if (!packaged || packaged.contractFingerprint !== action.contractFingerprint || packaged.contractVersion !== action.contractVersion) {
2289
+ error("stale_backend_projection", `Manifest and compiled backend disagree about '${nodeType}'`);
2290
+ }
2291
+ if (!Number.isInteger(action.contractVersion) || Number(action.contractVersion) < 1 || !/^[0-9a-f]{64}$/i.test(str(action.contractFingerprint))) {
2292
+ error("invalid_backend_contract", `Action '${nodeType}' is missing a valid contract version/fingerprint`);
2293
+ }
2294
+ const executor = record(action.executor) ? action.executor : {};
2295
+ if (!str(executor.kind) || executor.kind === "command" && !str(executor.command)) {
2296
+ error("invalid_backend_executor", `Action '${nodeType}' is missing an executable command`);
2297
+ } else if (executor.kind === "command" && !backendCommands.has(str(executor.command))) {
2298
+ error("missing_backend_command", `Action '${nodeType}' refers to undeclared command '${str(executor.command)}'`);
2299
+ }
2300
+ result.nodes.push({
2301
+ nodeType,
2302
+ executor: `${str(executor.kind)}${executor.command ? `:${str(executor.command)}` : ""}`,
2303
+ contractVersion: typeof action.contractVersion === "number" ? action.contractVersion : null,
2304
+ contractFingerprint: str(action.contractFingerprint) || null,
2305
+ frontendModule: null,
2306
+ frontendAssociation: "unresolved",
2307
+ registryStatus: "not_checked"
2308
+ });
2309
+ }
2310
+ if (backend && !declaredNodes.length && !generatedTriggers.length) warn("no_backend_workflow_actions", "Backend descriptor declares no Workflow action nodes or generated event triggers");
2311
+ if (frontend) {
2312
+ let visit2 = function(folder) {
2313
+ for (const entry of fs6.readdirSync(folder, { withFileTypes: true })) {
2314
+ if (entry.isSymbolicLink()) {
2315
+ error("frontend_symlink", "Compiled frontend contains a symlink");
2316
+ continue;
2317
+ }
2318
+ const location = path6.join(folder, entry.name);
2319
+ if (entry.isDirectory()) visit2(location);
2320
+ else if (entry.isFile() && /\.m?js$/.test(entry.name)) {
2321
+ scripts.push(location);
2322
+ compiledContent += fs6.readFileSync(location, "utf8");
2323
+ }
2324
+ }
2325
+ };
2326
+ var visit = visit2;
2327
+ const exposes = Array.isArray(frontend.exposes) ? frontend.exposes.filter((e) => typeof e === "string") : [];
2328
+ if (exposes.length !== (Array.isArray(frontend.exposes) ? frontend.exposes.length : 0) || new Set(exposes).size !== exposes.length) {
2329
+ error("frontend_exposes_invalid", "Frontend exposes must be unique strings");
2330
+ }
2331
+ const remotePath = str(frontend.entryPoint);
2332
+ const remote = asset(remotePath);
2333
+ if (remote) {
2334
+ const source = fs6.readFileSync(remote, "utf8");
2335
+ if (source.trim().length < 128) error("frontend_placeholder", "Remote frontend entry is empty or a placeholder");
2336
+ const syntax = spawnSync2(process.execPath, ["--check", remote], { encoding: "utf8" });
2337
+ if (syntax.status !== 0) error("frontend_invalid_js", "Frontend entry is not parseable JavaScript");
2338
+ }
2339
+ const contributionModules = /* @__PURE__ */ new Map();
2340
+ const contributionKeys = /* @__PURE__ */ new Set();
2341
+ const actionTypes = new Set(result.nodes.map((node) => node.nodeType));
2342
+ const nodeContributions = /* @__PURE__ */ new Map();
2343
+ const moduleOwners = /* @__PURE__ */ new Map();
2344
+ if (frontend.extensions != null && !Array.isArray(frontend.extensions)) {
2345
+ error("frontend_extensions_invalid", "Frontend extensions must be an array");
2346
+ }
2347
+ for (const ext of entries(frontend.extensions)) {
2348
+ const target = record(ext.target) ? ext.target : {};
2349
+ if (target.surface !== "custom" || target.key !== "workflow.node") continue;
2350
+ const point = str(target.point);
2351
+ const moduleName = str(ext.module);
2352
+ const contributionKey = str(ext.key);
2353
+ if (!contributionKey || contributionKeys.has(contributionKey)) {
2354
+ error("workflow_contribution_key_invalid", `Workflow contribution has missing/duplicate key '${contributionKey}'`);
2355
+ }
2356
+ contributionKeys.add(contributionKey);
2357
+ if (!POINTS.some((p) => p === point)) {
2358
+ error("workflow_point_invalid", `Unknown workflow.node point '${point}'`);
2359
+ continue;
2360
+ }
2361
+ if (!exposes.includes(moduleName)) error("workflow_module_not_exposed", `Workflow module '${moduleName}' is not in frontend.exposes`);
2362
+ const contract = record(ext.contract) ? ext.contract : {};
2363
+ if (ext.kind !== "ui" || contract.id !== CONTRACT || contract.version !== VERSION) {
2364
+ error("workflow_contract_invalid", `Workflow module '${moduleName}' has incompatible ${point} contract`);
2365
+ }
2366
+ const metadata = record(ext.metadata) ? ext.metadata : {};
2367
+ const association = record(metadata.workflowNode) ? metadata.workflowNode : null;
2368
+ const associatedType = association ? str(association.nodeType) : "";
2369
+ if (Object.hasOwn(metadata, "workflowNode") && !associatedType) {
2370
+ error("workflow_node_metadata_invalid", `Workflow contribution '${contributionKey}' has invalid compiler-owned nodeType metadata`);
2371
+ }
2372
+ if (associatedType) {
2373
+ if (!actionTypes.has(associatedType)) {
2374
+ error("workflow_node_metadata_unknown_action", `Workflow contribution '${contributionKey}' references non-owned or unknown backend action '${associatedType}'`);
2375
+ } else {
2376
+ const previousOwner = moduleOwners.get(moduleName);
2377
+ if (previousOwner && previousOwner !== associatedType) {
2378
+ error("workflow_module_multiple_actions", `Workflow module '${moduleName}' cannot describe both '${previousOwner}' and '${associatedType}'`);
2379
+ }
2380
+ moduleOwners.set(moduleName, associatedType);
2381
+ const previous = nodeContributions.get(associatedType);
2382
+ if (previous && previous.module !== moduleName) {
2383
+ error("workflow_node_multiple_modules", `Workflow action '${associatedType}' has facets in two different exposes`);
2384
+ }
2385
+ const facets = previous?.points ?? /* @__PURE__ */ new Map();
2386
+ facets.set(point, (facets.get(point) ?? 0) + 1);
2387
+ nodeContributions.set(associatedType, { module: moduleName, points: facets });
2388
+ }
2389
+ } else if (options.requireUi && result.nodes.length) {
2390
+ error("workflow_node_metadata_missing", `Workflow contribution '${contributionKey}' lacks compiler-owned nodeType association`);
2391
+ }
2392
+ const points = contributionModules.get(moduleName) ?? /* @__PURE__ */ new Map();
2393
+ points.set(point, (points.get(point) ?? 0) + 1);
2394
+ contributionModules.set(moduleName, points);
2395
+ }
2396
+ let compiledContent = "";
2397
+ const scripts = [];
2398
+ const frontendRoot = path6.join(root, "frontend");
2399
+ if (fs6.existsSync(frontendRoot)) {
2400
+ if (fs6.lstatSync(frontendRoot).isSymbolicLink()) {
2401
+ error("frontend_symlink", "Frontend package root cannot be a symlink");
2402
+ } else if (fs6.statSync(frontendRoot).isDirectory()) {
2403
+ visit2(frontendRoot);
2404
+ }
2405
+ }
2406
+ const localImport = /(?:\bimport\s*(?:\(\s*)?|\bfrom\s*)["'](\.\.?\/[^"']+)["']/g;
2407
+ for (const script of scripts) {
2408
+ const code = fs6.readFileSync(script, "utf8");
2409
+ for (const match of code.matchAll(localImport)) {
2410
+ let specifier = match[1].split(/[?#]/)[0];
2411
+ try {
2412
+ specifier = decodeURIComponent(specifier);
2413
+ } catch {
2414
+ error("frontend_chunk_invalid", `Malformed local import '${specifier}'`);
2415
+ continue;
2416
+ }
2417
+ const imported = path6.resolve(path6.dirname(script), specifier);
2418
+ const relative3 = path6.relative(frontendRoot, imported);
2419
+ if (!relative3 || relative3 === ".." || relative3.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative3)) {
2420
+ error("frontend_chunk_escaped", `JS asset imports outside its frontend root: '${specifier}'`);
2421
+ } else if (!fs6.existsSync(imported) || !fs6.statSync(imported).isFile() || fs6.lstatSync(imported).isSymbolicLink()) {
2422
+ error("frontend_chunk_missing", `Missing/symlinked JS asset '${specifier}'`);
2423
+ }
2424
+ }
2425
+ }
2426
+ for (const [moduleName, points] of contributionModules) {
2427
+ for (const [point, count] of points) {
2428
+ if (count !== 1) error("workflow_point_duplicate", `Module '${moduleName}' declares ${count} ${point} contributions`);
2429
+ }
2430
+ const present = compiledContent.includes(moduleName);
2431
+ if (!present) error("frontend_expose_not_compiled", `Built frontend JS does not advertise '${moduleName}'`);
2432
+ result.modules.push({ module: moduleName, points: POINTS.filter((point) => points.has(point)), compiledExposePresent: present });
2433
+ if (options.requireUi) {
2434
+ for (const point of POINTS) {
2435
+ if (points.get(point) !== 1) error("workflow_facet_missing", `Module '${moduleName}' has no unique ${point} contribution`);
2436
+ }
2437
+ }
2438
+ }
2439
+ for (const expose of exposes) {
2440
+ if (!compiledContent.includes(expose)) error("frontend_expose_not_compiled", `Built frontend JS does not advertise '${expose}'`);
2441
+ }
2442
+ if (options.requireUi && result.nodes.length && result.modules.length !== result.nodes.length) {
2443
+ error("workflow_node_facet_count", `Expected ${result.nodes.length} unique Workflow UI modules; got ${result.modules.length}`);
2444
+ }
2445
+ for (const node of result.nodes) {
2446
+ const association = nodeContributions.get(node.nodeType);
2447
+ if (association) {
2448
+ node.frontendModule = association.module;
2449
+ node.frontendAssociation = "compiler_metadata";
2450
+ if (options.requireUi) for (const point of POINTS) {
2451
+ if (association.points.get(point) !== 1) {
2452
+ error("workflow_node_facet_missing", `Backend action '${node.nodeType}' must have exactly one ${point} contribution`);
2453
+ }
2454
+ }
2455
+ } else if (options.requireUi) {
2456
+ error("workflow_node_facet_missing", `Backend action '${node.nodeType}' has no compiler-owned UI contributions`);
2457
+ } else {
2458
+ const suffix = node.nodeType.split(":action:")[1];
2459
+ const matching = result.modules.filter((module) => toKebab(module.module.split("/").at(-1) ?? "") === suffix);
2460
+ if (matching.length === 1) {
2461
+ node.frontendModule = matching[0].module;
2462
+ node.frontendAssociation = "convention_only";
2463
+ }
2464
+ }
2465
+ }
2466
+ } else if (options.requireUi && result.nodes.length) {
2467
+ error("workflow_ui_missing", "Package contains executable Workflow actions but no frontend facet");
2468
+ }
2469
+ if (options.registryJson) {
2470
+ let installed = null;
2471
+ try {
2472
+ installed = asRegistry(JSON.parse(fs6.readFileSync(path6.resolve(options.registryJson), "utf8")));
2473
+ } catch (cause) {
2474
+ registryError("registry_json_invalid", `Cannot read saved runtime registry: ${cause instanceof Error ? cause.message : String(cause)}`);
2475
+ }
2476
+ if (!installed) {
2477
+ registryError("registry_json_invalid", "Saved runtime registry must be an array or {nodes:[]} / {nodeTypes:[]}, containing node descriptors");
2478
+ result.registryStatus = "mismatch";
2479
+ } else {
2480
+ const expected = [...result.nodes, ...result.triggers];
2481
+ for (const node of expected) {
2482
+ const matches = installed.filter((entry) => entry.nodeType === node.nodeType);
2483
+ const match = matches[0];
2484
+ node.registryStatus = matches.length === 0 ? "missing" : matches.length !== 1 || match.contractFingerprint !== node.contractFingerprint || match.contractVersion !== node.contractVersion ? "mismatch" : "matched";
2485
+ if (node.registryStatus !== "matched") registryError("active_registry_mismatch", `Active registry status for '${node.nodeType}': ${node.registryStatus} (${matches.length} matching type entries)`);
2486
+ }
2487
+ result.registryStatus = expected.length && expected.every((node) => node.registryStatus === "matched") ? "matched" : "mismatch";
2488
+ }
2489
+ }
2490
+ if (!options.registryJson) warn("live_registry_not_checked", "No effective runtime registry provided; installation/activation is not verified");
2491
+ warn("browser_not_checked", "A packaged frontend is not proof that the host loaded/rendered the module in a browser");
2492
+ result.packageStatus = issues.some((item) => item.severity === "error" && item.scope === "package") ? "invalid" : "valid";
2493
+ return result;
2494
+ }
2495
+ function formatWorkflowNodePackageInspection(result) {
2496
+ const lines = [
2497
+ `Workflow package inspection: ${result.pluginKey || "<unknown>"}@${result.version || "<unknown>"}`,
2498
+ `Package: ${result.packageRoot} (${result.packageStatus})`,
2499
+ `Effective backend registry: ${result.registryStatus}; browser facet loading: ${result.browserStatus}`,
2500
+ "Executable nodes (compiled backend contract):"
2501
+ ];
2502
+ for (const node of result.nodes) lines.push(
2503
+ ` ${node.nodeType} -> ${node.executor} (v${node.contractVersion ?? "?"}, ${node.contractFingerprint ?? "no fingerprint"}) -> ${node.frontendModule ?? "module not authoritatively linked"} (${node.frontendAssociation}) -> registry:${node.registryStatus}`
2504
+ );
2505
+ if (result.triggers.length) {
2506
+ lines.push("Generated event-trigger Workflow types (backend-owned; no action editor required):");
2507
+ for (const trigger of result.triggers) lines.push(
2508
+ ` ${trigger.nodeType} -> event:${trigger.event} (v${trigger.contractVersion ?? "?"}, ${trigger.contractFingerprint ?? "no fingerprint"}) -> registry:${trigger.registryStatus}`
2509
+ );
2510
+ }
2511
+ lines.push("Frontend Workflow modules (assembled contributions):");
2512
+ for (const module of result.modules) lines.push(` ${module.module}: ${module.points.join("/") || "no facets"}; built expose: ${module.compiledExposePresent}`);
2513
+ for (const issue2 of result.issues) lines.push(` ${issue2.severity.toUpperCase()} [${issue2.scope}:${issue2.code}] ${issue2.message}`);
2514
+ return `${lines.join("\n")}
2515
+ `;
2516
+ }
2517
+
2518
+ // src/history/history.ts
2519
+ import fs7 from "fs";
2520
+ import path7 from "path";
2521
+ function loadReleaseContractSnapshots(files) {
2522
+ return files.map((file) => {
2523
+ const resolved = path7.resolve(file);
2524
+ const baseline = readContractBaselineFile(resolved);
2525
+ return {
2526
+ label: baseline.pluginVersion ?? path7.basename(resolved),
2527
+ pluginId: baseline.pluginId,
2528
+ ...baseline.pluginVersion ? { pluginVersion: baseline.pluginVersion } : {},
2529
+ contract: baseline.contract,
2530
+ source: resolved
2531
+ };
2532
+ });
2533
+ }
2534
+ function buildReleaseCompatibilityHistory(releases) {
2535
+ if (releases.length === 0)
2536
+ throw new Error(
2537
+ "Release compatibility history requires at least one contract snapshot."
2538
+ );
2539
+ const pluginId = releases[0].pluginId;
2540
+ for (const release of releases) {
2541
+ if (release.pluginId !== pluginId) {
2542
+ throw new Error(
2543
+ `Release history mixes plugin '${pluginId}' with '${release.pluginId}'.`
2544
+ );
2545
+ }
2546
+ }
2547
+ const steps = [];
2548
+ for (let index = 1; index < releases.length; index += 1) {
2549
+ const from = releases[index - 1];
2550
+ const to = releases[index];
2551
+ const baseline = {
2552
+ pluginId,
2553
+ ...from.pluginVersion ? { pluginVersion: from.pluginVersion } : {},
2554
+ contract: from.contract,
2555
+ provenance: {
2556
+ kind: "explicit",
2557
+ description: "Release-history snapshot",
2558
+ ...from.source ? { reference: from.source } : {},
2559
+ ...from.pluginVersion ? { pluginVersion: from.pluginVersion } : {}
2560
+ }
2561
+ };
2562
+ steps.push({
2563
+ from,
2564
+ to,
2565
+ report: compareExtensionContracts({
2566
+ pluginId,
2567
+ ...to.pluginVersion ? { currentPluginVersion: to.pluginVersion } : {},
2568
+ current: to.contract,
2569
+ baseline
2570
+ })
2571
+ });
2572
+ }
2573
+ return { pluginId, releases: [...releases], steps };
2574
+ }
2575
+ function renderReleaseCompatibilityHistoryMermaid(history) {
2576
+ const lines = ["flowchart LR"];
2577
+ history.releases.forEach((release, index) => {
2578
+ lines.push(` r${index + 1}["${escapeMermaid(release.label)}"]`);
2579
+ });
2580
+ history.steps.forEach((step, index) => {
2581
+ const summary = step.report.summary;
2582
+ const label = step.report.status === "breaking" ? `BREAKING: ${summary.breaking}` : `${summary.added} added / ${summary.changed} changed`;
2583
+ lines.push(` r${index + 1} -- "${label}" --> r${index + 2}`);
2584
+ });
2585
+ return `${lines.join("\n")}
2586
+ `;
2587
+ }
2588
+ function renderReleaseCompatibilityHistoryMarkdown(history) {
2589
+ const lines = [
2590
+ `# ${history.pluginId} extension contract history`,
2591
+ "",
2592
+ "This is compatibility history only. It is never an input to Current Extension Contract identity generation.",
2593
+ "",
2594
+ "| From | To | Status | Added | Removed | Changed | Breaking |",
2595
+ "| --- | --- | --- | ---: | ---: | ---: | ---: |"
2596
+ ];
2597
+ if (history.steps.length === 0) {
2598
+ lines.push(
2599
+ `| \u2014 | ${history.releases[0].label} | baseline | 0 | 0 | 0 | 0 |`
2600
+ );
2601
+ } else {
2602
+ for (const step of history.steps) {
2603
+ lines.push(
2604
+ `| ${step.from.label} | ${step.to.label} | ${step.report.status} | ${step.report.summary.added} | ${step.report.summary.removed} | ${step.report.summary.changed} | ${step.report.summary.breaking} |`
2605
+ );
2606
+ }
2607
+ }
2608
+ lines.push("");
2609
+ return `${lines.join("\n")}
2610
+ `;
2611
+ }
2612
+ function writeReleaseCompatibilityHistory(options) {
2613
+ const outputDir = path7.resolve(options.outputDir);
2614
+ fs7.mkdirSync(outputDir, { recursive: true });
2615
+ const files = {
2616
+ json: path7.join(outputDir, "contract-history.json"),
2617
+ markdown: path7.join(outputDir, "contract-history.md"),
2618
+ mermaid: path7.join(outputDir, "contract-history.mmd")
2619
+ };
2620
+ fs7.writeFileSync(files.json, `${JSON.stringify(options.history, null, 2)}
2621
+ `);
2622
+ fs7.writeFileSync(
2623
+ files.markdown,
2624
+ renderReleaseCompatibilityHistoryMarkdown(options.history)
2625
+ );
2626
+ fs7.writeFileSync(
2627
+ files.mermaid,
2628
+ renderReleaseCompatibilityHistoryMermaid(options.history)
2629
+ );
2630
+ return files;
2631
+ }
2632
+ function escapeMermaid(value) {
2633
+ return value.replaceAll("\\", "\\\\").replaceAll('"', "'").replaceAll("\n", " ");
2634
+ }
2635
+
2636
+ // src/protocol/verify.ts
2637
+ import fs8 from "fs";
2638
+ import path8 from "path";
2639
+ import {
2640
+ EXTENSION_KINDS,
2641
+ EXTENSION_SURFACES,
2642
+ OPERATION_EXTENSION_PHASES,
2643
+ PLUGIN_MANIFEST_VERSION,
2644
+ PLUGIN_PROTOCOL_VERSION
2645
+ } from "@plugmatica/core-sdk";
2646
+ var FRONTEND_PROTOCOL_SNAPSHOT = {
2647
+ manifestVersion: PLUGIN_MANIFEST_VERSION,
2648
+ protocolVersion: PLUGIN_PROTOCOL_VERSION,
2649
+ extensionSurfaces: EXTENSION_SURFACES,
2650
+ operationExtensionPhases: OPERATION_EXTENSION_PHASES,
2651
+ extensionKinds: EXTENSION_KINDS
2652
+ };
2653
+ function verifyFrontendProtocolAgainstRust(backendRoot) {
2654
+ const root = path8.resolve(backendRoot);
2655
+ const file = [
2656
+ path8.join(root, "crates/plugin-manifest/protocol-metadata.json"),
2657
+ path8.join(root, "backend/crates/plugin-manifest/protocol-metadata.json")
2658
+ ].find((candidate) => fs8.existsSync(candidate));
2659
+ if (!file)
2660
+ throw new Error(`Could not find protocol-metadata.json below '${root}'.`);
2661
+ const actual = JSON.parse(
2662
+ fs8.readFileSync(file, "utf8")
2663
+ );
2664
+ const issues = [];
2665
+ compareScalar(
2666
+ issues,
2667
+ "manifestVersion",
2668
+ FRONTEND_PROTOCOL_SNAPSHOT.manifestVersion,
2669
+ actual.manifestVersion
2670
+ );
2671
+ compareScalar(
2672
+ issues,
2673
+ "protocolVersion",
2674
+ FRONTEND_PROTOCOL_SNAPSHOT.protocolVersion,
2675
+ actual.protocolVersion
2676
+ );
2677
+ compareList(
2678
+ issues,
2679
+ "extensionSurfaces",
2680
+ FRONTEND_PROTOCOL_SNAPSHOT.extensionSurfaces,
2681
+ actual.extensionSurfaces
2682
+ );
2683
+ compareList(
2684
+ issues,
2685
+ "operationExtensionPhases",
2686
+ FRONTEND_PROTOCOL_SNAPSHOT.operationExtensionPhases,
2687
+ actual.operationExtensionPhases
2688
+ );
2689
+ compareList(
2690
+ issues,
2691
+ "extensionKinds",
2692
+ FRONTEND_PROTOCOL_SNAPSHOT.extensionKinds,
2693
+ actual.extensionKinds
2694
+ );
2695
+ return {
2696
+ backendRoot: root,
2697
+ expected: FRONTEND_PROTOCOL_SNAPSHOT,
2698
+ actual,
2699
+ issues
2700
+ };
2701
+ }
2702
+ function formatProtocolParityReport(report) {
2703
+ if (report.issues.length === 0)
2704
+ return `Frontend/backend protocol parity: OK (${report.backendRoot})`;
2705
+ return [
2706
+ `Frontend/backend protocol parity: ${report.issues.length} drift issue(s)`,
2707
+ ...report.issues.map((issue2) => `- ${issue2}`),
2708
+ "Regenerate frontend protocol contracts from backend protocol-metadata.json."
2709
+ ].join("\n");
2710
+ }
2711
+ function compareScalar(issues, field, expected, actual) {
2712
+ if (expected !== actual)
2713
+ issues.push(
2714
+ `${field}: frontend '${expected}' != backend metadata '${actual}'.`
2715
+ );
2716
+ }
2717
+ function compareList(issues, field, expected, actual) {
2718
+ if (expected.join(",") !== actual.join(",")) {
2719
+ issues.push(
2720
+ `${field}: frontend [${expected.join(", ")}] != backend metadata [${actual.join(", ")}].`
2721
+ );
2722
+ }
2723
+ }
2724
+
2725
+ // src/release/audit.ts
2726
+ import fs9 from "fs";
2727
+ import path9 from "path";
2728
+ var DEPENDENCY_FIELDS = [
2729
+ "dependencies",
2730
+ "peerDependencies",
2731
+ "optionalDependencies",
2732
+ "devDependencies"
2733
+ ];
2734
+ var PUBLISHED_DEPENDENCY_FIELDS = [
2735
+ "dependencies",
2736
+ "peerDependencies",
2737
+ "optionalDependencies"
2738
+ ];
2739
+ function loadPackageReleasePolicy(frontendRoot) {
2740
+ const policyPath = path9.join(
2741
+ path9.resolve(frontendRoot),
2742
+ "release",
2743
+ "package-policy.json"
2744
+ );
2745
+ const parsed = JSON.parse(
2746
+ fs9.readFileSync(policyPath, "utf8")
2747
+ );
2748
+ if (parsed.schemaVersion !== 1 || !parsed.packages || typeof parsed.packages !== "object") {
2749
+ throw new Error(
2750
+ `Invalid Plugmatica package release policy at ${policyPath}.`
2751
+ );
2752
+ }
2753
+ return parsed;
2754
+ }
2755
+ function auditPackageReleaseContract(frontendRoot) {
2756
+ const root = path9.resolve(frontendRoot);
2757
+ const policyPath = path9.join(root, "release", "package-policy.json");
2758
+ const issues = [];
2759
+ let policy;
2760
+ try {
2761
+ policy = loadPackageReleasePolicy(root);
2762
+ } catch (error) {
2763
+ return {
2764
+ root,
2765
+ policyPath,
2766
+ issues: [
2767
+ {
2768
+ code: "invalid_policy",
2769
+ packageName: "<policy>",
2770
+ file: relative2(root, policyPath),
2771
+ message: error instanceof Error ? error.message : String(error)
2772
+ }
2773
+ ]
2774
+ };
2775
+ }
2776
+ const manifests = findPackageManifests(root);
2777
+ const manifestsByName = /* @__PURE__ */ new Map();
2778
+ for (const file of manifests) {
2779
+ const manifest = readManifest(file);
2780
+ const name = typeof manifest.name === "string" ? manifest.name : "";
2781
+ if (name) manifestsByName.set(name, { file, manifest });
2782
+ if (name && !policy.packages[name]) {
2783
+ issues.push(
2784
+ issue(
2785
+ root,
2786
+ name,
2787
+ file,
2788
+ "unclassified_package",
2789
+ `${name} is not classified in release/package-policy.json.`
2790
+ )
2791
+ );
2792
+ }
2793
+ }
2794
+ for (const [packageName, entry] of Object.entries(policy.packages)) {
2795
+ const packageJson = path9.join(root, entry.path, "package.json");
2796
+ if (!fs9.existsSync(packageJson)) {
2797
+ issues.push(
2798
+ issue(
2799
+ root,
2800
+ packageName,
2801
+ packageJson,
2802
+ "missing_package",
2803
+ `Policy entry ${packageName} points to missing ${entry.path}/package.json.`
2804
+ )
2805
+ );
2806
+ continue;
2807
+ }
2808
+ const manifest = readManifest(packageJson);
2809
+ if (manifest.name !== packageName) {
2810
+ issues.push(
2811
+ issue(
2812
+ root,
2813
+ packageName,
2814
+ packageJson,
2815
+ "package_name_mismatch",
2816
+ `Policy expects ${packageName}, but package.json declares ${String(manifest.name)}.`
2817
+ )
2818
+ );
2819
+ }
2820
+ const isPublic = entry.classification !== "host-internal";
2821
+ if (isPublic) {
2822
+ auditPublicPackage(
2823
+ root,
2824
+ policy,
2825
+ packageName,
2826
+ entry,
2827
+ packageJson,
2828
+ manifest,
2829
+ issues
2830
+ );
2831
+ } else if (manifest.private !== true) {
2832
+ issues.push(
2833
+ issue(
2834
+ root,
2835
+ packageName,
2836
+ packageJson,
2837
+ "internal_package_public",
2838
+ `${packageName} is host-internal and must remain private.`
2839
+ )
2840
+ );
2841
+ }
2842
+ auditExportSurface(root, packageName, entry, packageJson, manifest, issues);
2843
+ }
2844
+ return {
2845
+ root,
2846
+ policyPath,
2847
+ issues: issues.sort(
2848
+ (a, b) => a.file.localeCompare(b.file) || a.code.localeCompare(b.code) || a.message.localeCompare(b.message)
2849
+ )
2850
+ };
2851
+ }
2852
+ function assertPackageReleaseContract(frontendRoot) {
2853
+ const audit = auditPackageReleaseContract(frontendRoot);
2854
+ if (audit.issues.length > 0)
2855
+ throw new Error(formatPackageReleaseAudit(audit));
2856
+ }
2857
+ function formatPackageReleaseAudit(audit) {
2858
+ if (audit.issues.length === 0) return "Frontend package release contract: OK";
2859
+ return [
2860
+ `Frontend package release contract: ${audit.issues.length} violation(s)`,
2861
+ ...audit.issues.map(
2862
+ (item) => `- ${item.file} [${item.code}] ${item.message}`
2863
+ )
2864
+ ].join("\n");
2865
+ }
2866
+ function auditPublicPackage(root, policy, packageName, _entry, packageJson, manifest, issues) {
2867
+ if (manifest.private === true) {
2868
+ issues.push(
2869
+ issue(
2870
+ root,
2871
+ packageName,
2872
+ packageJson,
2873
+ "public_package_private",
2874
+ `${packageName} is classified as public but package.json is private.`
2875
+ )
2876
+ );
2877
+ }
2878
+ if (typeof manifest.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(
2879
+ manifest.version
2880
+ )) {
2881
+ issues.push(
2882
+ issue(
2883
+ root,
2884
+ packageName,
2885
+ packageJson,
2886
+ "public_package_version",
2887
+ `${packageName} must declare a valid independent semver package version; found ${String(manifest.version)}.`
2888
+ )
2889
+ );
2890
+ }
2891
+ const publishConfig = recordValue(manifest.publishConfig);
2892
+ if (publishConfig?.access !== "public") {
2893
+ issues.push(
2894
+ issue(
2895
+ root,
2896
+ packageName,
2897
+ packageJson,
2898
+ "missing_publish_config",
2899
+ `${packageName} must declare publishConfig.access = "public".`
2900
+ )
2901
+ );
2902
+ }
2903
+ if (typeof manifest.license !== "string" || !manifest.license.trim()) {
2904
+ issues.push(
2905
+ issue(
2906
+ root,
2907
+ packageName,
2908
+ packageJson,
2909
+ "missing_license",
2910
+ `${packageName} must declare a license before publication.`
2911
+ )
2912
+ );
2913
+ }
2914
+ const readme = path9.join(path9.dirname(packageJson), "README.md");
2915
+ if (!fs9.existsSync(readme)) {
2916
+ issues.push(
2917
+ issue(
2918
+ root,
2919
+ packageName,
2920
+ readme,
2921
+ "missing_readme",
2922
+ `${packageName} must include README.md in its package root.`
2923
+ )
2924
+ );
2925
+ }
2926
+ const files = Array.isArray(manifest.files) ? manifest.files.filter(
2927
+ (value) => typeof value === "string"
2928
+ ) : [];
2929
+ if (!files.includes("dist")) {
2930
+ issues.push(
2931
+ issue(
2932
+ root,
2933
+ packageName,
2934
+ packageJson,
2935
+ "missing_dist_files_entry",
2936
+ `${packageName} must explicitly publish its dist directory.`
2937
+ )
2938
+ );
2939
+ }
2940
+ for (const field of DEPENDENCY_FIELDS) {
2941
+ const dependencies = recordValue(manifest[field]);
2942
+ if (!dependencies) continue;
2943
+ for (const [dependency, version] of Object.entries(dependencies)) {
2944
+ if (typeof version === "string" && version.startsWith("workspace:")) {
2945
+ issues.push(
2946
+ issue(
2947
+ root,
2948
+ packageName,
2949
+ packageJson,
2950
+ "workspace_protocol_leak",
2951
+ `${packageName} ${field}.${dependency} uses ${version}; packed public manifests must be workspace-independent.`
2952
+ )
2953
+ );
2954
+ }
2955
+ const target = policy.packages[dependency];
2956
+ if (dependency.startsWith("@plugmatica/") && target && target.classification !== "host-internal") {
2957
+ const targetManifestPath = path9.join(root, target.path, "package.json");
2958
+ const targetManifest = readManifest(targetManifestPath);
2959
+ const expectedVersion = `^${String(targetManifest.version)}`;
2960
+ if (version !== expectedVersion) {
2961
+ issues.push(
2962
+ issue(
2963
+ root,
2964
+ packageName,
2965
+ packageJson,
2966
+ "public_dependency_version",
2967
+ `${packageName} ${field}.${dependency} must follow the independently versioned public package range ${expectedVersion}; found ${String(version)}.`
2968
+ )
2969
+ );
2970
+ }
2971
+ }
2972
+ }
2973
+ }
2974
+ for (const field of PUBLISHED_DEPENDENCY_FIELDS) {
2975
+ const dependencies = recordValue(manifest[field]);
2976
+ if (!dependencies) continue;
2977
+ for (const dependency of Object.keys(dependencies)) {
2978
+ if (!dependency.startsWith("@plugmatica/")) continue;
2979
+ const target = policy.packages[dependency];
2980
+ if (!target || target.classification === "host-internal") {
2981
+ issues.push(
2982
+ issue(
2983
+ root,
2984
+ packageName,
2985
+ packageJson,
2986
+ "private_dependency_leak",
2987
+ `${packageName} ${field} references ${dependency}, which is not a publishable Plugmatica package.`
2988
+ )
2989
+ );
2990
+ }
2991
+ }
2992
+ }
2993
+ }
2994
+ function auditExportSurface(root, packageName, entry, packageJson, manifest, issues) {
2995
+ const actual = exportKeys(manifest.exports);
2996
+ const expected = Object.keys(entry.exports).sort();
2997
+ if (actual.length !== expected.length || actual.some((value, index) => value !== expected[index])) {
2998
+ issues.push(
2999
+ issue(
3000
+ root,
3001
+ packageName,
3002
+ packageJson,
3003
+ "export_surface_mismatch",
3004
+ `${packageName} exports [${actual.join(", ")}] but release policy declares [${expected.join(", ")}].`
3005
+ )
3006
+ );
3007
+ }
3008
+ }
3009
+ function auditBuiltDeclarationDependencies(frontendRoot) {
3010
+ const root = path9.resolve(frontendRoot);
3011
+ const policy = loadPackageReleasePolicy(root);
3012
+ const issues = [];
3013
+ for (const [packageName, entry] of Object.entries(policy.packages)) {
3014
+ if (entry.classification === "host-internal") continue;
3015
+ const dist = path9.join(root, entry.path, "dist");
3016
+ if (!fs9.existsSync(dist)) continue;
3017
+ for (const file of walk(dist).filter(
3018
+ (candidate) => /\.d\.[cm]?ts$/.test(candidate)
3019
+ )) {
3020
+ const text = fs9.readFileSync(file, "utf8");
3021
+ for (const dependency of plugmaticaDeclarationImports(text)) {
3022
+ const target = policy.packages[dependency];
3023
+ if (!target || target.classification === "host-internal") {
3024
+ issues.push(
3025
+ issue(
3026
+ root,
3027
+ packageName,
3028
+ file,
3029
+ "unpublishable_declaration_dependency",
3030
+ `${packageName} declaration output references ${dependency}, which external consumers cannot resolve as a supported public package.`
3031
+ )
3032
+ );
3033
+ }
3034
+ }
3035
+ }
3036
+ }
3037
+ return issues;
3038
+ }
3039
+ function exportKeys(value) {
3040
+ if (!value || typeof value !== "object" || Array.isArray(value)) return [];
3041
+ return Object.keys(value).sort();
3042
+ }
3043
+ function plugmaticaDeclarationImports(text) {
3044
+ const result = /* @__PURE__ */ new Set();
3045
+ const matcher = /(?:from\s+|import\s*\(|require\s*\()\s*["'](@plugmatica\/[^"'/]+)(?:\/[^"']*)?["']/g;
3046
+ for (const match of text.matchAll(matcher)) {
3047
+ if (match[1]) result.add(match[1]);
3048
+ }
3049
+ return [...result].sort();
3050
+ }
3051
+ function findPackageManifests(root) {
3052
+ const result = [];
3053
+ for (const parent of ["packages", "apps"]) {
3054
+ const directory = path9.join(root, parent);
3055
+ if (!fs9.existsSync(directory)) continue;
3056
+ for (const entry of fs9.readdirSync(directory, { withFileTypes: true })) {
3057
+ if (!entry.isDirectory()) continue;
3058
+ const packageJson = path9.join(directory, entry.name, "package.json");
3059
+ if (fs9.existsSync(packageJson)) result.push(packageJson);
3060
+ }
3061
+ }
3062
+ return result.sort();
3063
+ }
3064
+ function walk(root) {
3065
+ const result = [];
3066
+ for (const entry of fs9.readdirSync(root, { withFileTypes: true })) {
3067
+ const target = path9.join(root, entry.name);
3068
+ if (entry.isDirectory()) result.push(...walk(target));
3069
+ else result.push(target);
3070
+ }
3071
+ return result;
3072
+ }
3073
+ function readManifest(file) {
3074
+ return JSON.parse(fs9.readFileSync(file, "utf8"));
3075
+ }
3076
+ function recordValue(value) {
3077
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3078
+ }
3079
+ function issue(root, packageName, file, code, message) {
3080
+ return { packageName, file: relative2(root, file), code, message };
3081
+ }
3082
+ function relative2(root, file) {
3083
+ return path9.relative(root, file).split(path9.sep).join("/");
3084
+ }
3085
+
3086
+ export {
3087
+ listPluginTemplates,
3088
+ createPluginScaffold,
3089
+ assertSupportedNode,
3090
+ assertSupportedPackageManager,
3091
+ CONTRACT_BASELINE_FORMAT_VERSION,
3092
+ buildCurrentContractSnapshot,
3093
+ createRepositoryBaselineFile,
3094
+ normalizeCurrentExtensionContract,
3095
+ parseContractBaselineFile,
3096
+ readContractBaselineFile,
3097
+ writeContractBaselineFile,
3098
+ contractFromManifestPayload,
3099
+ RegistryBaselineUnavailableError,
3100
+ ExplicitContractBaselineProvider,
3101
+ RepositoryContractBaselineProvider,
3102
+ GitTagContractBaselineProvider,
3103
+ InstalledPluginContractBaselineProvider,
3104
+ RegistryContractBaselineProvider,
3105
+ resolveContractBaseline,
3106
+ compareExtensionContracts,
3107
+ formatCompatibilityReport,
3108
+ BreakingExtensionContractError,
3109
+ enforceStrictCompatibility,
3110
+ repositoryBaselinePath,
3111
+ initRepositoryContractBaseline,
3112
+ updateRepositoryContractBaseline,
3113
+ checkContractCompatibility,
3114
+ auditFrontendPackageBoundaries,
3115
+ assertFrontendPackageBoundaries,
3116
+ formatPackageBoundaryAudit,
3117
+ auditRepositoryPluginAuthoringBoundaries,
3118
+ inspectPlugin,
3119
+ formatPluginInspection,
3120
+ formatExtensionInventory,
3121
+ inspectWorkflowNodePackage,
3122
+ formatWorkflowNodePackageInspection,
3123
+ loadReleaseContractSnapshots,
3124
+ buildReleaseCompatibilityHistory,
3125
+ renderReleaseCompatibilityHistoryMermaid,
3126
+ renderReleaseCompatibilityHistoryMarkdown,
3127
+ writeReleaseCompatibilityHistory,
3128
+ verifyFrontendProtocolAgainstRust,
3129
+ formatProtocolParityReport,
3130
+ loadPackageReleasePolicy,
3131
+ auditPackageReleaseContract,
3132
+ assertPackageReleaseContract,
3133
+ formatPackageReleaseAudit,
3134
+ auditBuiltDeclarationDependencies
3135
+ };