@animus-ui/extract 0.1.9 → 0.1.11

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 (126) hide show
  1. package/README.md +1 -1
  2. package/crates/extract-v2/animus-extract-v2.darwin-arm64.node +0 -0
  3. package/crates/extract-v2/animus-extract-v2.linux-arm64-gnu.node +0 -0
  4. package/crates/extract-v2/animus-extract-v2.linux-x64-gnu.node +0 -0
  5. package/dist/index.cjs +73 -2101
  6. package/dist/index.mjs +2 -2026
  7. package/dist/pipeline/analyze-project-args.d.ts.map +1 -0
  8. package/dist/pipeline/assemble-stylesheet.d.ts.map +1 -0
  9. package/dist/pipeline/asset-placeholders.d.ts.map +1 -0
  10. package/dist/pipeline/content-hash.d.ts.map +1 -0
  11. package/dist/pipeline/core-options.d.ts +162 -0
  12. package/dist/pipeline/core-options.d.ts.map +1 -0
  13. package/dist/pipeline/correlate-external-tokens.d.ts.map +1 -0
  14. package/dist/pipeline/discover-files.d.ts +12 -0
  15. package/dist/pipeline/discover-files.d.ts.map +1 -0
  16. package/dist/{discover-packages.d.ts → pipeline/discover-packages.d.ts} +7 -8
  17. package/dist/pipeline/discover-packages.d.ts.map +1 -0
  18. package/dist/pipeline/dynamic-prop-config.d.ts.map +1 -0
  19. package/dist/{engine-adapter.d.ts → pipeline/engine-adapter.d.ts} +2 -0
  20. package/dist/pipeline/engine-adapter.d.ts.map +1 -0
  21. package/dist/pipeline/engine-retirement.d.ts.map +1 -0
  22. package/dist/pipeline/error-diagnostics.d.ts.map +1 -0
  23. package/dist/pipeline/external-keyframes.d.ts.map +1 -0
  24. package/dist/{index.d.ts → pipeline/index.d.ts} +10 -1
  25. package/dist/pipeline/index.d.ts.map +1 -0
  26. package/dist/pipeline/manifest-diagnostics.d.ts.map +1 -0
  27. package/dist/{mdx-preprocessor.d.ts → pipeline/mdx-preprocessor.d.ts} +10 -0
  28. package/dist/pipeline/mdx-preprocessor.d.ts.map +1 -0
  29. package/dist/pipeline/path-aliases.d.ts.map +1 -0
  30. package/dist/pipeline/post-process-css.d.ts.map +1 -0
  31. package/dist/pipeline/prefix.d.ts.map +1 -0
  32. package/dist/pipeline/replacement-plans.d.ts.map +1 -0
  33. package/dist/pipeline/resolve-asset.d.ts.map +1 -0
  34. package/dist/pipeline/run-analysis.d.ts.map +1 -0
  35. package/dist/pipeline/source-identity.d.ts.map +1 -0
  36. package/dist/pipeline/source-ingestion.d.ts +173 -0
  37. package/dist/pipeline/source-ingestion.d.ts.map +1 -0
  38. package/dist/pipeline/static-css.d.ts.map +1 -0
  39. package/dist/pipeline/structural-self-check.d.ts +32 -0
  40. package/dist/pipeline/structural-self-check.d.ts.map +1 -0
  41. package/dist/pipeline/svelte-source-adapter.d.ts +88 -0
  42. package/dist/pipeline/svelte-source-adapter.d.ts.map +1 -0
  43. package/dist/pipeline/system-config.d.ts.map +1 -0
  44. package/dist/{system-props-module.d.ts → pipeline/system-props-module.d.ts} +4 -3
  45. package/dist/pipeline/system-props-module.d.ts.map +1 -0
  46. package/dist/pipeline/timing-waterfall.d.ts.map +1 -0
  47. package/dist/pipeline/tsconfig-paths.d.ts.map +1 -0
  48. package/dist/pipeline/unit-fallback.d.ts.map +1 -0
  49. package/dist/pipeline/utils.d.ts.map +1 -0
  50. package/dist/pipeline/watch-keys.d.ts.map +1 -0
  51. package/dist/pipeline-lkbOoyAr.mjs +3228 -0
  52. package/dist/pipeline-ojNeABi0.cjs +3685 -0
  53. package/dist/session/extraction-session.d.ts +446 -0
  54. package/dist/session/extraction-session.d.ts.map +1 -0
  55. package/dist/session/index.d.ts +24 -0
  56. package/dist/session/index.d.ts.map +1 -0
  57. package/dist/session/published-set.d.ts +32 -0
  58. package/dist/session/published-set.d.ts.map +1 -0
  59. package/dist/session/resolve-packages.d.ts +8 -0
  60. package/dist/session/resolve-packages.d.ts.map +1 -0
  61. package/dist/session/session-paths.d.ts +131 -0
  62. package/dist/session/session-paths.d.ts.map +1 -0
  63. package/dist/session/singleton.d.ts +124 -0
  64. package/dist/session/singleton.d.ts.map +1 -0
  65. package/dist/session/timing.d.ts +7 -0
  66. package/dist/session/timing.d.ts.map +1 -0
  67. package/dist/session/turbopack-orchestrator.d.ts +43 -0
  68. package/dist/session/turbopack-orchestrator.d.ts.map +1 -0
  69. package/dist/session.cjs +2146 -0
  70. package/dist/session.mjs +2110 -0
  71. package/package.json +18 -6
  72. package/dist/analyze-project-args.d.ts.map +0 -1
  73. package/dist/assemble-stylesheet.d.ts.map +0 -1
  74. package/dist/asset-placeholders.d.ts.map +0 -1
  75. package/dist/content-hash.d.ts.map +0 -1
  76. package/dist/correlate-external-tokens.d.ts.map +0 -1
  77. package/dist/discover-files.d.ts +0 -10
  78. package/dist/discover-files.d.ts.map +0 -1
  79. package/dist/discover-packages.d.ts.map +0 -1
  80. package/dist/dynamic-prop-config.d.ts.map +0 -1
  81. package/dist/engine-adapter.d.ts.map +0 -1
  82. package/dist/engine-retirement.d.ts.map +0 -1
  83. package/dist/error-diagnostics.d.ts.map +0 -1
  84. package/dist/external-keyframes.d.ts.map +0 -1
  85. package/dist/index.d.ts.map +0 -1
  86. package/dist/manifest-diagnostics.d.ts.map +0 -1
  87. package/dist/mdx-preprocessor.d.ts.map +0 -1
  88. package/dist/path-aliases.d.ts.map +0 -1
  89. package/dist/post-process-css.d.ts.map +0 -1
  90. package/dist/prefix.d.ts.map +0 -1
  91. package/dist/replacement-plans.d.ts.map +0 -1
  92. package/dist/resolve-asset.d.ts.map +0 -1
  93. package/dist/run-analysis.d.ts.map +0 -1
  94. package/dist/source-identity.d.ts.map +0 -1
  95. package/dist/static-css.d.ts.map +0 -1
  96. package/dist/system-config.d.ts.map +0 -1
  97. package/dist/system-props-module.d.ts.map +0 -1
  98. package/dist/timing-waterfall.d.ts.map +0 -1
  99. package/dist/tsconfig-paths.d.ts.map +0 -1
  100. package/dist/unit-fallback.d.ts.map +0 -1
  101. package/dist/utils.d.ts.map +0 -1
  102. package/dist/watch-keys.d.ts.map +0 -1
  103. /package/dist/{analyze-project-args.d.ts → pipeline/analyze-project-args.d.ts} +0 -0
  104. /package/dist/{assemble-stylesheet.d.ts → pipeline/assemble-stylesheet.d.ts} +0 -0
  105. /package/dist/{asset-placeholders.d.ts → pipeline/asset-placeholders.d.ts} +0 -0
  106. /package/dist/{content-hash.d.ts → pipeline/content-hash.d.ts} +0 -0
  107. /package/dist/{correlate-external-tokens.d.ts → pipeline/correlate-external-tokens.d.ts} +0 -0
  108. /package/dist/{dynamic-prop-config.d.ts → pipeline/dynamic-prop-config.d.ts} +0 -0
  109. /package/dist/{engine-retirement.d.ts → pipeline/engine-retirement.d.ts} +0 -0
  110. /package/dist/{error-diagnostics.d.ts → pipeline/error-diagnostics.d.ts} +0 -0
  111. /package/dist/{external-keyframes.d.ts → pipeline/external-keyframes.d.ts} +0 -0
  112. /package/dist/{manifest-diagnostics.d.ts → pipeline/manifest-diagnostics.d.ts} +0 -0
  113. /package/dist/{path-aliases.d.ts → pipeline/path-aliases.d.ts} +0 -0
  114. /package/dist/{post-process-css.d.ts → pipeline/post-process-css.d.ts} +0 -0
  115. /package/dist/{prefix.d.ts → pipeline/prefix.d.ts} +0 -0
  116. /package/dist/{replacement-plans.d.ts → pipeline/replacement-plans.d.ts} +0 -0
  117. /package/dist/{resolve-asset.d.ts → pipeline/resolve-asset.d.ts} +0 -0
  118. /package/dist/{run-analysis.d.ts → pipeline/run-analysis.d.ts} +0 -0
  119. /package/dist/{source-identity.d.ts → pipeline/source-identity.d.ts} +0 -0
  120. /package/dist/{static-css.d.ts → pipeline/static-css.d.ts} +0 -0
  121. /package/dist/{system-config.d.ts → pipeline/system-config.d.ts} +0 -0
  122. /package/dist/{timing-waterfall.d.ts → pipeline/timing-waterfall.d.ts} +0 -0
  123. /package/dist/{tsconfig-paths.d.ts → pipeline/tsconfig-paths.d.ts} +0 -0
  124. /package/dist/{unit-fallback.d.ts → pipeline/unit-fallback.d.ts} +0 -0
  125. /package/dist/{utils.d.ts → pipeline/utils.d.ts} +0 -0
  126. /package/dist/{watch-keys.d.ts → pipeline/watch-keys.d.ts} +0 -0
@@ -0,0 +1,3685 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let crypto = require("crypto");
24
+ let fs = require("fs");
25
+ let path = require("path");
26
+ let node_fs = require("node:fs");
27
+ let node_path = require("node:path");
28
+ node_path = __toESM(node_path);
29
+ let module$1 = require("module");
30
+ let browserslist = require("browserslist");
31
+ browserslist = __toESM(browserslist);
32
+ let lightningcss = require("lightningcss");
33
+ let _animus_ui_properties = require("@animus-ui/properties");
34
+ //#region pipeline/assemble-stylesheet.ts
35
+ /**
36
+ * The 7 Animus cascade layers. Always prefixed with `anm-` to avoid
37
+ * collision with other frameworks' layer names (e.g., Tailwind's `base`).
38
+ */
39
+ const ANIMUS_LAYERS = [
40
+ "anm-global",
41
+ "anm-base",
42
+ "anm-variants",
43
+ "anm-compounds",
44
+ "anm-states",
45
+ "anm-system",
46
+ "anm-custom"
47
+ ];
48
+ /**
49
+ * Build the `@layer` declaration line.
50
+ *
51
+ * When `isCustom` is false (default layers), uses ANIMUS_LAYERS directly.
52
+ * When `isCustom` is true, passes names through as-is — the consumer already
53
+ * wrote the final names including the `anm-` prefixed entries.
54
+ */
55
+ function buildLayerDeclaration(layers, isCustom) {
56
+ return `@layer ${(isCustom ? layers : [...ANIMUS_LAYERS]).join(", ")};\n`;
57
+ }
58
+ /**
59
+ * Validate that a consumer `layers` array contains all 7 Animus layers
60
+ * in the correct relative order. Consumer layers may be interleaved.
61
+ *
62
+ * @throws Error with descriptive message on violation
63
+ */
64
+ function validateLayerOrder(layers) {
65
+ const expected = [...ANIMUS_LAYERS];
66
+ let cursor = 0;
67
+ for (const layer of layers) if (cursor < expected.length && layer === expected[cursor]) cursor++;
68
+ if (cursor < expected.length) {
69
+ const missing = expected.slice(cursor);
70
+ const found = expected.slice(0, cursor);
71
+ if (!expected.every((l) => layers.includes(l))) {
72
+ const absent = expected.filter((l) => !layers.includes(l));
73
+ throw new Error(`[animus-extract] Custom layers missing required layers: ${absent.join(", ")}. All 7 Animus layers must be present: ${expected.join(", ")}`);
74
+ }
75
+ throw new Error(`[animus-extract] Custom layers have wrong order. Found ${found.join(", ")} but then expected ${missing[0]}. Required order: (${expected.join(" < ")}). You may interleave custom layers but must preserve this subsequence.`);
76
+ }
77
+ }
78
+ /**
79
+ * Strip a leading `@layer ...;` declaration line from CSS if present.
80
+ * The Rust crate embeds this in prod-mode output; we strip it so the
81
+ * shared assembler controls placement.
82
+ */
83
+ function stripLeadingLayerDeclaration(css) {
84
+ return css.replace(/^@layer\s+[^;{]+;\s*\n?/, "");
85
+ }
86
+ function assembleStylesheet(options) {
87
+ const hasCustomLayers = !!options.layers;
88
+ const layers = options.layers ?? ANIMUS_LAYERS;
89
+ if (options.layers) validateLayerOrder(options.layers);
90
+ const declaration = buildLayerDeclaration(layers, hasCustomLayers);
91
+ const variables = options.variableCss || "";
92
+ const componentCss = options.componentCss ? stripLeadingLayerDeclaration(options.componentCss) : "";
93
+ const body = [options.globalCss || "", componentCss].filter(Boolean).join("\n");
94
+ if (options.split) return {
95
+ declaration,
96
+ variables,
97
+ body
98
+ };
99
+ return [
100
+ declaration,
101
+ variables,
102
+ body
103
+ ].filter(Boolean).join("\n");
104
+ }
105
+ //#endregion
106
+ //#region pipeline/analyze-project-args.ts
107
+ /** @internal */
108
+ function buildAnalyzeProjectArgs(inputs) {
109
+ return [
110
+ inputs.filesJson,
111
+ inputs.scalesJson,
112
+ inputs.variableMapJson,
113
+ inputs.contextualVarsJson,
114
+ inputs.propConfigJson,
115
+ inputs.groupRegistryJson,
116
+ inputs.packageResolutionJson,
117
+ inputs.devMode,
118
+ inputs.emitterConfigJson,
119
+ inputs.selectorAliasesJson,
120
+ null,
121
+ inputs.globalStyleBlocksJson,
122
+ inputs.pathAliasesJson,
123
+ inputs.keyframesJson,
124
+ inputs.staticCssJson,
125
+ inputs.conditionAliasesJson,
126
+ inputs.externalDirsJson,
127
+ inputs.transformSourcesJson
128
+ ];
129
+ }
130
+ //#endregion
131
+ //#region pipeline/engine-adapter.ts
132
+ /**
133
+ * Build the engine-agnostic `engineApi()` both plugins call. Returns a function
134
+ * (invoked per call site) so `isV2()` and `loadNativeEngine()` re-evaluate each
135
+ * time — next reads its engine choice and native module dynamically from
136
+ * globalThis.
137
+ */
138
+ function createV2EngineApi(deps) {
139
+ const { label, isV2, loadNativeEngine, store } = deps;
140
+ return () => {
141
+ if (!isV2()) return loadNativeEngine();
142
+ const native = loadNativeEngine();
143
+ return {
144
+ loadSystemModule: (...args) => native.loadSystemModule(...args),
145
+ scanKeyframesExports: (entryPath, rootDir) => native.scanKeyframesExports(entryPath, rootDir) ?? null,
146
+ extractFacts: (filesJson) => native.extractFacts(filesJson),
147
+ analyzeProject: (filesJsonRaw, scalesJson, variableMapJson, contextualVarsJson, propConfigJson, groupRegistryJson, packageResolutionJson, devMode, emitterConfigJson, selectorAliasesJson, _selectorOrderJson, globalStyleBlocksJson, pathAliasesJson, keyframesJson, staticCssJson, conditionAliasesJson, externalDirsJson, transformSourcesJson) => {
148
+ const filesJson = deps.rehydrateFilesJson ? deps.rehydrateFilesJson(filesJsonRaw) : filesJsonRaw;
149
+ const sent = /* @__PURE__ */ new Map();
150
+ for (const entry of JSON.parse(filesJson)) sent.set(entry.path, entry.source);
151
+ store.setSentSources(sent);
152
+ const emitterConfig = emitterConfigJson ? JSON.parse(emitterConfigJson) : {};
153
+ store.setEngine(null);
154
+ const config = {
155
+ runtimeImport: emitterConfig.runtime_import ?? void 0,
156
+ cssModuleId: emitterConfig.css_module_id ?? void 0,
157
+ systemPropsModuleId: emitterConfig.system_props_module_id ?? void 0,
158
+ themeJson: scalesJson,
159
+ variableMapJson,
160
+ contextualVarsJson: contextualVarsJson ?? void 0,
161
+ configJson: propConfigJson,
162
+ groupRegistryJson,
163
+ selectorAliasesJson: selectorAliasesJson ?? void 0,
164
+ conditionAliasesJson: conditionAliasesJson ?? void 0,
165
+ globalStyleBlocksJson: globalStyleBlocksJson ?? void 0,
166
+ keyframesJson: keyframesJson ?? void 0,
167
+ packageResolutionJson: packageResolutionJson ?? void 0,
168
+ pathAliasesJson: pathAliasesJson ?? void 0,
169
+ staticCssJson: staticCssJson ?? void 0,
170
+ externalDirsJson: externalDirsJson ?? void 0,
171
+ transformSourcesJson: transformSourcesJson ?? void 0,
172
+ devMode
173
+ };
174
+ const engine = new native.ExtractEngine(config);
175
+ store.setEngine(engine);
176
+ return engine.analyze(filesJson);
177
+ },
178
+ transformFile: (source, path, _manifest) => {
179
+ const engine = store.getEngine();
180
+ if (!engine) throw new Error(`[${label}] v2 transform before analyze — engine instance not initialized`);
181
+ const sentMap = store.getSentSources();
182
+ if (deps.passThroughUnknownPaths && sentMap && !sentMap.has(path)) return {
183
+ code: source,
184
+ hasComponents: false
185
+ };
186
+ const sent = sentMap?.get(path);
187
+ if (sent !== void 0 && sent !== source && !store.getDriftWarned()) {
188
+ store.setDriftWarned(true);
189
+ console.warn(`[${label}] v2: transform-time source for ${path} differs from analyze-time source — an upstream transform may be reverted`);
190
+ }
191
+ return JSON.parse(engine.transformFile(path));
192
+ },
193
+ clearAnalysisCache: () => {
194
+ const engine = store.getEngine();
195
+ if (engine) engine.clearCache();
196
+ store.setEngine(null);
197
+ }
198
+ };
199
+ };
200
+ }
201
+ //#endregion
202
+ //#region pipeline/engine-retirement.ts
203
+ /**
204
+ * Loud rejection of the retired v1 extraction engine (openspec:
205
+ * retire-extract-v1).
206
+ *
207
+ * v2 is the only engine. Selecting v1 — via a plugin `engine: 'v1'` option or
208
+ * the `ANIMUS_ENGINE=v1` fixture env override — is a build-stopping error, never
209
+ * a silent upgrade to v2 (design D1: a silent flip would let a pinned consumer's
210
+ * build change engines without notice). Both extraction plugins call this before
211
+ * any engine selection so the rejection is uniform and the message is defined
212
+ * once.
213
+ */
214
+ /** The one canonical retirement message, shared verbatim by both plugins and
215
+ * the env path (tasks.md cross-cutting: define once, reuse). */
216
+ const RETIRED_ENGINE_MESSAGE = "animus: extraction engine 'v1' was retired (openspec: retire-extract-v1) — v2 is the only engine; remove the engine option / ANIMUS_ENGINE override";
217
+ /**
218
+ * Throw the canonical retirement error when v1 is selected through either
219
+ * surface. Accepts the raw engine option as a string because the option type no
220
+ * longer admits `'v1'` — callers cast it so a stale `'v1'` config still fails
221
+ * loud at runtime instead of being silently coerced.
222
+ */
223
+ function assertNoRetiredEngineSelection(engineOption) {
224
+ if (engineOption === "v1" || process.env.ANIMUS_ENGINE === "v1") throw new Error(RETIRED_ENGINE_MESSAGE);
225
+ }
226
+ //#endregion
227
+ //#region pipeline/content-hash.ts
228
+ /**
229
+ * MD5 content hash used for file-change detection (HMR diffing) by both
230
+ * extraction plugins, and for content-addressing copied asset bytes. The
231
+ * algorithm/encoding is a cross-plugin contract: cache keys written by one
232
+ * build path must compare equal in the next. Accepts a Buffer directly so
233
+ * binary sources hash without an intermediate string copy.
234
+ */
235
+ function contentHash(source) {
236
+ return (0, crypto.createHash)("md5").update(source).digest("hex");
237
+ }
238
+ //#endregion
239
+ //#region pipeline/external-keyframes.ts
240
+ /** Stable codes for external keyframes discovery. */
241
+ const KEYFRAMES_EXTERNAL_ENTRY_FAILED = "animus.keyframes.external-entry-failed";
242
+ const KEYFRAMES_EXPORT_COLLISION = "animus.keyframes.export-collision";
243
+ /**
244
+ * Merge `Keyframes` collections discovered from external package entries into
245
+ * the consumer system's collections. Keyframes are the sole carve-out from
246
+ * the consumer-config singular-authority rule: nothing but branded
247
+ * collections is read from an entry, an entry that fails to evaluate
248
+ * degrades to a coded diagnostic naming it, and a collection whose export
249
+ * name collides keeps the earlier (consumer-first) collection with a coded
250
+ * diagnostic instead of silently reordering names.
251
+ */
252
+ function mergeExternalKeyframes(scan, consumerKeyframesJson, externalEntries, rootDir) {
253
+ const merged = {};
254
+ if (consumerKeyframesJson) try {
255
+ Object.assign(merged, JSON.parse(consumerKeyframesJson));
256
+ } catch {
257
+ return {
258
+ keyframesJson: consumerKeyframesJson,
259
+ diagnostics: []
260
+ };
261
+ }
262
+ const diagnostics = [];
263
+ const seenEntries = /* @__PURE__ */ new Set();
264
+ for (const entryPath of externalEntries) {
265
+ if (seenEntries.has(entryPath)) continue;
266
+ seenEntries.add(entryPath);
267
+ let scanned;
268
+ try {
269
+ scanned = scan(entryPath, rootDir);
270
+ } catch (error) {
271
+ diagnostics.push({
272
+ file: entryPath,
273
+ component: "keyframes",
274
+ kind: "warn",
275
+ message: `external package entry failed the keyframes scan — its collections are invisible to extraction: ${String(error)}. Keyframe collections must be reachable from the package's definition entry without evaluating framework re-exports: export them (directly or as a named re-export) from the definition entry, and avoid \`export *\` of framework packages there (${KEYFRAMES_EXTERNAL_ENTRY_FAILED})`,
276
+ code: KEYFRAMES_EXTERNAL_ENTRY_FAILED,
277
+ severity: "warn"
278
+ });
279
+ continue;
280
+ }
281
+ if (!scanned) continue;
282
+ let collections;
283
+ try {
284
+ collections = JSON.parse(scanned);
285
+ } catch {
286
+ continue;
287
+ }
288
+ for (const [exportName, collection] of Object.entries(collections)) {
289
+ const existing = merged[exportName];
290
+ if (existing !== void 0) {
291
+ if (JSON.stringify(existing) !== JSON.stringify(collection)) diagnostics.push({
292
+ file: entryPath,
293
+ component: exportName,
294
+ kind: "warn",
295
+ message: `keyframes collection export '${exportName}' collides with an earlier collection of the same name — the earlier one wins (${KEYFRAMES_EXPORT_COLLISION})`,
296
+ code: KEYFRAMES_EXPORT_COLLISION,
297
+ severity: "warn"
298
+ });
299
+ continue;
300
+ }
301
+ merged[exportName] = collection;
302
+ }
303
+ }
304
+ return {
305
+ keyframesJson: Object.keys(merged).length > 0 ? JSON.stringify(merged) : null,
306
+ diagnostics
307
+ };
308
+ }
309
+ //#endregion
310
+ //#region pipeline/core-options.ts
311
+ /** Closed set of driver namespaces a shared config file may carry. */
312
+ const DRIVER_NAMESPACES = [
313
+ "vite",
314
+ "next",
315
+ "cli"
316
+ ];
317
+ /**
318
+ * Structural exclusions applied unconditionally, whether or not the user
319
+ * supplies an `exclude` list. `node_modules` is owned by the external-package
320
+ * collection path (never the source walk), and `.next`/`.animus` are artifact
321
+ * output directories inside the scanned root that must never be re-ingested
322
+ * as source.
323
+ */
324
+ const STRUCTURAL_EXCLUDE = [
325
+ "node_modules",
326
+ ".next",
327
+ ".animus"
328
+ ];
329
+ /**
330
+ * Convenience defaults applied only when the user supplies no `exclude`
331
+ * list — a user list replaces these (but never the structural set).
332
+ */
333
+ const REPLACEABLE_DEFAULT_EXCLUDE = [
334
+ "dist",
335
+ ".test.",
336
+ ".spec."
337
+ ];
338
+ /**
339
+ * Default path patterns excluded from source discovery — the single
340
+ * authoritative set for every driver when no user `exclude` is given.
341
+ * Composed, never hand-listed: a structural addition must not silently
342
+ * miss this union.
343
+ */
344
+ const DEFAULT_EXCLUDE = [...STRUCTURAL_EXCLUDE, ...REPLACEABLE_DEFAULT_EXCLUDE];
345
+ /** Core keys accepted at the top level of any driver's options. */
346
+ const CORE_OPTION_KEYS = new Set([
347
+ "system",
348
+ "exclude",
349
+ "extensions",
350
+ "strict",
351
+ "verbose",
352
+ "prefix",
353
+ "targets",
354
+ "minify",
355
+ "staticCss",
356
+ "layers",
357
+ "engine",
358
+ "mode",
359
+ "root"
360
+ ]);
361
+ /** Configuration errors carry a stable name so drivers can map them to
362
+ * their config-error surface (the CLI's exit code 2). */
363
+ var AnimusConfigError = class extends Error {
364
+ constructor(message) {
365
+ super(message);
366
+ this.name = "AnimusConfigError";
367
+ }
368
+ };
369
+ /**
370
+ * Reject unknown top-level option keys and invalid core values. `ownKeys`
371
+ * is the calling driver's legacy/driver-specific top-level surface (e.g.
372
+ * Vite's `verify`, Next's `cssImportTarget`); driver namespaces are always
373
+ * legal and inert for non-owning drivers. `rejectKeys` names core keys the
374
+ * calling driver does NOT honor — accepting-and-ignoring a key the
375
+ * validator vouches for is the exact silent failure this seam exists to
376
+ * kill, so the driver must reject it with its reason (or, in `'warn'`
377
+ * mode, name it loudly while the key stays inert as it always was).
378
+ */
379
+ function assertKnownOptionKeys(raw, ownKeys = [], rejectKeys = [], opts = {}) {
380
+ const surface = (message) => {
381
+ if (opts.onUnknownKey === "warn") {
382
+ opts.warn(message);
383
+ return;
384
+ }
385
+ throw new AnimusConfigError(message);
386
+ };
387
+ const own = new Set(ownKeys);
388
+ for (const key of Object.keys(raw)) {
389
+ if (raw[key] === void 0) continue;
390
+ const rejected = rejectKeys.find((entry) => entry.key === key);
391
+ if (rejected) {
392
+ surface(`Option "${key}" is not supported by this driver: ${rejected.reason}`);
393
+ continue;
394
+ }
395
+ if (CORE_OPTION_KEYS.has(key) || DRIVER_NAMESPACES.includes(key) || own.has(key)) continue;
396
+ const nearest = suggestNearest(key);
397
+ surface(`Unknown option "${key}".${nearest ? ` Did you mean "${nearest}"?` : ""} Core keys: ${[...CORE_OPTION_KEYS].join(", ")}. Driver namespaces: ${DRIVER_NAMESPACES.join(", ")}.`);
398
+ }
399
+ const mode = raw["mode"];
400
+ if (mode !== void 0 && mode !== "development" && mode !== "production") throw new AnimusConfigError(`Invalid mode "${String(mode)}" — expected "development" or "production".`);
401
+ for (const { key, ok, expected } of CORE_VALUE_GATES) {
402
+ const value = raw[key];
403
+ if (value === void 0 || ok(value)) continue;
404
+ throw new AnimusConfigError(`Invalid value for "${key}" — expected ${expected}, got ${JSON.stringify(value)}.`);
405
+ }
406
+ }
407
+ const isStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
408
+ const CORE_VALUE_GATES = [
409
+ {
410
+ key: "system",
411
+ ok: (v) => typeof v === "string",
412
+ expected: "a string path"
413
+ },
414
+ {
415
+ key: "exclude",
416
+ ok: isStringArray,
417
+ expected: "an array of string patterns"
418
+ },
419
+ {
420
+ key: "extensions",
421
+ ok: isStringArray,
422
+ expected: "an array of string extensions"
423
+ },
424
+ {
425
+ key: "strict",
426
+ ok: (v) => typeof v === "boolean",
427
+ expected: "a boolean"
428
+ },
429
+ {
430
+ key: "verbose",
431
+ ok: (v) => typeof v === "boolean",
432
+ expected: "a boolean"
433
+ },
434
+ {
435
+ key: "minify",
436
+ ok: (v) => typeof v === "boolean",
437
+ expected: "a boolean"
438
+ },
439
+ {
440
+ key: "prefix",
441
+ ok: (v) => typeof v === "string",
442
+ expected: "a string"
443
+ },
444
+ {
445
+ key: "targets",
446
+ ok: (v) => typeof v === "string" || isStringArray(v),
447
+ expected: "a string or an array of strings"
448
+ },
449
+ {
450
+ key: "layers",
451
+ ok: isStringArray,
452
+ expected: "an array of layer names"
453
+ }
454
+ ];
455
+ function suggestNearest(key) {
456
+ const lower = key.toLowerCase();
457
+ let best = null;
458
+ let bestScore = 3;
459
+ for (const candidate of CORE_OPTION_KEYS) {
460
+ const score = editDistance(lower, candidate.toLowerCase());
461
+ if (score < bestScore) {
462
+ bestScore = score;
463
+ best = candidate;
464
+ }
465
+ }
466
+ return best;
467
+ }
468
+ function editDistance(a, b) {
469
+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i]);
470
+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;
471
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
472
+ return dp[a.length][b.length];
473
+ }
474
+ const GLOB_META = /[*?]/;
475
+ /**
476
+ * Compile one exclusion pattern. Glob patterns (containing `*` or `?`)
477
+ * compile to a RegExp over the slash-normalized root-relative path — a
478
+ * match on the path itself OR any ancestor directory excludes it, so a
479
+ * directory-shaped glob (double-star slash "generated") excludes files
480
+ * inside that directory identically for tree discovery (which prunes at
481
+ * the directory) and per-file watch classification (which only ever sees
482
+ * file paths).
483
+ * Plain patterns keep the historical substring semantics over both path
484
+ * forms.
485
+ * A leading `./` is stripped first: relative paths are computed without
486
+ * one, so `./fixtures/**` must mean exactly `fixtures/**` rather than
487
+ * compiling to a regex that can never match.
488
+ */
489
+ function compilePattern(raw) {
490
+ let pattern = raw.split("\\").join("/");
491
+ while (pattern.startsWith("./")) pattern = pattern.slice(2);
492
+ if (pattern === "") return () => false;
493
+ if (!GLOB_META.test(pattern)) return (full, rel) => full.includes(pattern) || rel.includes(pattern);
494
+ const regex = globToRegExp(pattern);
495
+ return (_full, rel) => {
496
+ const normalized = rel.split("\\").join("/");
497
+ if (regex.test(normalized)) return true;
498
+ for (let slash = normalized.indexOf("/"); slash !== -1; slash = normalized.indexOf("/", slash + 1)) if (regex.test(normalized.slice(0, slash))) return true;
499
+ return false;
500
+ };
501
+ }
502
+ /** Minimal glob → RegExp: `**` spans segments, `*`/`?` stay within one. */
503
+ function globToRegExp(glob) {
504
+ let out = "";
505
+ let i = 0;
506
+ const normalized = glob.split("\\").join("/");
507
+ while (i < normalized.length) {
508
+ const ch = normalized[i];
509
+ if (ch === "*") if (normalized[i + 1] === "*") if (normalized[i + 2] === "/") {
510
+ out += "(?:[^/]+/)*";
511
+ i += 3;
512
+ } else {
513
+ out += ".*";
514
+ i += 2;
515
+ }
516
+ else {
517
+ out += "[^/]*";
518
+ i += 1;
519
+ }
520
+ else if (ch === "?") {
521
+ out += "[^/]";
522
+ i += 1;
523
+ } else {
524
+ out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
525
+ i += 1;
526
+ }
527
+ }
528
+ return new RegExp(`^${out}$`);
529
+ }
530
+ /**
531
+ * Build the effective exclusion matcher. A user list REPLACES the
532
+ * replaceable defaults (`dist`, `.test.`, `.spec.`) — the HEAD driver
533
+ * contract (`options.exclude ?? DEFAULT_EXCLUDE`) — while the structural
534
+ * exclusions (`node_modules`, `.next`, `.animus`) always apply: those
535
+ * protect pipeline invariants, not preferences, so no user list can
536
+ * re-admit them. `extraStructural` joins that never-replaceable set — the
537
+ * channel for driver-owned invariants (a CLI outDir inside the root),
538
+ * which must NOT ride the user list: appending there would flip the
539
+ * replace semantics and silently drop the replaceable defaults.
540
+ */
541
+ function createExcludeMatcher(userPatterns, extraStructural = []) {
542
+ const merged = [...STRUCTURAL_EXCLUDE];
543
+ for (const pattern of extraStructural) if (!merged.includes(pattern)) merged.push(pattern);
544
+ for (const pattern of userPatterns ?? REPLACEABLE_DEFAULT_EXCLUDE) if (!merged.includes(pattern)) merged.push(pattern);
545
+ const compiled = merged.map((pattern) => [pattern, compilePattern(pattern)]);
546
+ const hits = new Map(merged.map((p) => [p, 0]));
547
+ const explain = (full, rel) => {
548
+ for (const [pattern, test] of compiled) if (test(full, rel)) {
549
+ hits.set(pattern, (hits.get(pattern) ?? 0) + 1);
550
+ return pattern;
551
+ }
552
+ return null;
553
+ };
554
+ return {
555
+ patterns: merged,
556
+ matches: (full, rel) => explain(full, rel) !== null,
557
+ explain,
558
+ stats: () => hits
559
+ };
560
+ }
561
+ /**
562
+ * Resolve the effective mode: the explicit `mode` key wins over every
563
+ * environment-derived signal; otherwise the driver's documented default
564
+ * applies.
565
+ */
566
+ function resolveMode(explicit, driverDefault) {
567
+ if (explicit === "development" || explicit === "production") return {
568
+ mode: explicit,
569
+ provenance: "explicit"
570
+ };
571
+ return {
572
+ mode: driverDefault(),
573
+ provenance: "driver-default"
574
+ };
575
+ }
576
+ //#endregion
577
+ //#region pipeline/discover-files.ts
578
+ /**
579
+ * Recursively discover source files under `dir`, skipping excluded paths
580
+ * (an `ExcludeMatcher` — see core-options, the one pattern authority — or
581
+ * undefined for NO exclusion at all: the dist-package walks deliberately
582
+ * run under node_modules, which `createExcludeMatcher`'s structural set
583
+ * would prune) and keeping files whose extension is in `extensionsSet`.
584
+ *
585
+ * Single authoritative copy for both extraction plugins.
586
+ */
587
+ function discoverFiles(dir, rootDir, exclude, extensionsSet) {
588
+ const results = [];
589
+ let entries;
590
+ try {
591
+ entries = (0, fs.readdirSync)(dir, { encoding: "utf8" });
592
+ } catch {
593
+ return results;
594
+ }
595
+ entries.sort();
596
+ const isExcluded = exclude ? (full, rel) => exclude.matches(full, rel) : () => false;
597
+ for (const entry of entries) {
598
+ const fullPath = (0, path.join)(dir, entry);
599
+ if (isExcluded(fullPath, (0, path.relative)(rootDir, fullPath))) continue;
600
+ let stat;
601
+ try {
602
+ stat = (0, fs.statSync)(fullPath);
603
+ } catch {
604
+ continue;
605
+ }
606
+ if (stat.isDirectory()) results.push(...discoverFiles(fullPath, rootDir, exclude, extensionsSet));
607
+ else if (extensionsSet.has((0, path.extname)(entry))) results.push(fullPath);
608
+ }
609
+ return results;
610
+ }
611
+ //#endregion
612
+ //#region pipeline/source-identity.ts
613
+ /**
614
+ * SourceId derivation authority + allowlist membership (openspec:
615
+ * external-source-watch-ingestion, design D1/D2/D5).
616
+ *
617
+ * One shared derivation produces the canonical source identity consumed by
618
+ * discovery, watch ingestion, ownership, deletion pruning, and diagnostics
619
+ * — raw event paths are lookup INPUTS only, so event spelling (symlink
620
+ * alias vs canonical, lexical vs realpath) can never fork identity.
621
+ *
622
+ * The containment and volume helpers are pure and path-API-injectable so
623
+ * Windows semantics are unit-testable via `path.win32` on any host; runtime
624
+ * callers use the ambient platform implementation.
625
+ */
626
+ /**
627
+ * Structural containment: `target` is the root itself or a descendant of it,
628
+ * decided by `relative()` shape — never by string prefixing, so `/ui` can
629
+ * never claim `/ui-old`, and a cross-drive win32 target (whose relative()
630
+ * result is absolute) is never contained.
631
+ */
632
+ function isPathWithinRoot(root, target, pathApi = node_path.default) {
633
+ const rel = pathApi.relative(root, target);
634
+ return rel === "" || !pathApi.isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + pathApi.sep);
635
+ }
636
+ /**
637
+ * Cross-volume gate (design D5): two paths share a platform path root
638
+ * (win32 drive letter or UNC share; always true on posix). Compared
639
+ * case-insensitively — win32 drive letters are case-insensitive.
640
+ */
641
+ function sharesVolumeRoot(a, b, pathApi = node_path.default) {
642
+ const volumeOf = (p) => pathApi.parse(pathApi.resolve(p)).root.toLowerCase();
643
+ return volumeOf(a) === volumeOf(b);
644
+ }
645
+ function canonicalize(p) {
646
+ try {
647
+ return (0, node_fs.realpathSync)(p);
648
+ } catch {
649
+ return null;
650
+ }
651
+ }
652
+ function createSourceIdentity(rootDir) {
653
+ const normalizedRootDir = node_path.default.normalize(rootDir);
654
+ const canonicalRootDir = canonicalize(normalizedRootDir) ?? normalizedRootDir;
655
+ const roots = [];
656
+ const aliases = /* @__PURE__ */ new Map();
657
+ const owningRecord = (canonicalPath) => {
658
+ let owner = null;
659
+ for (const record of roots) {
660
+ if (!isPathWithinRoot(record.canonical, canonicalPath)) continue;
661
+ if (!owner || record.canonical.length > owner.canonical.length) owner = record;
662
+ }
663
+ return owner;
664
+ };
665
+ return {
666
+ rootDir: normalizedRootDir,
667
+ canonicalRootDir,
668
+ registerExternalRoot(root) {
669
+ const asRegistered = node_path.default.normalize(root);
670
+ const canonical = canonicalize(asRegistered) ?? asRegistered;
671
+ const existing = roots.find((record) => record.canonical === canonical);
672
+ if (existing) return existing.canonical;
673
+ roots.push({
674
+ asRegistered,
675
+ canonical
676
+ });
677
+ return canonical;
678
+ },
679
+ externalRoots() {
680
+ return roots.map((record) => record.canonical);
681
+ },
682
+ resolveSourceId(inputPath) {
683
+ const lexical = node_path.default.normalize(inputPath);
684
+ const canonical = canonicalize(lexical);
685
+ if (canonical === null) return null;
686
+ const owner = owningRecord(canonical);
687
+ const ownedBy = (record) => {
688
+ const pathInRoot = node_path.default.relative(record.canonical, canonical);
689
+ return {
690
+ sourceKey: node_path.default.relative(normalizedRootDir, node_path.default.join(record.asRegistered, pathInRoot)),
691
+ owningRoot: record.canonical,
692
+ pathInRoot
693
+ };
694
+ };
695
+ const ownerIsMoreSpecific = owner !== null && owner.canonical.length > canonicalRootDir.length;
696
+ let resolved;
697
+ if (!ownerIsMoreSpecific && isPathWithinRoot(canonicalRootDir, canonical)) {
698
+ const key = node_path.default.relative(canonicalRootDir, canonical);
699
+ resolved = {
700
+ sourceKey: key,
701
+ owningRoot: null,
702
+ pathInRoot: key
703
+ };
704
+ } else if (owner) resolved = ownedBy(owner);
705
+ else return null;
706
+ aliases.set(lexical, resolved);
707
+ aliases.set(canonical, resolved);
708
+ return resolved;
709
+ },
710
+ resolveDeletedSourceId(inputPath) {
711
+ return aliases.get(node_path.default.normalize(inputPath)) ?? null;
712
+ },
713
+ containingExternalRoot(inputPath) {
714
+ const lexical = node_path.default.normalize(inputPath);
715
+ let owner = null;
716
+ for (const record of roots) {
717
+ if (!(isPathWithinRoot(record.canonical, lexical) || isPathWithinRoot(record.asRegistered, lexical))) continue;
718
+ if (!owner || record.canonical.length > owner.canonical.length) owner = record;
719
+ }
720
+ if (owner) return owner.canonical;
721
+ const canonical = canonicalize(lexical);
722
+ if (canonical === null) return null;
723
+ for (const record of roots) {
724
+ if (!isPathWithinRoot(record.canonical, canonical)) continue;
725
+ if (!owner || record.canonical.length > owner.canonical.length) owner = record;
726
+ }
727
+ return owner?.canonical ?? null;
728
+ }
729
+ };
730
+ }
731
+ //#endregion
732
+ //#region pipeline/discover-packages.ts
733
+ /**
734
+ * Walk up from a resolved package entry file to the nearest directory
735
+ * containing a package.json (the package root). Stops at the filesystem
736
+ * root and returns it if no package.json is found on the way up.
737
+ */
738
+ function findPackageRoot(absEntryPath) {
739
+ let pkgRoot = (0, path.dirname)(absEntryPath);
740
+ while (pkgRoot !== (0, path.dirname)(pkgRoot) && !(0, fs.existsSync)((0, path.join)(pkgRoot, "package.json"))) pkgRoot = (0, path.dirname)(pkgRoot);
741
+ return pkgRoot;
742
+ }
743
+ /**
744
+ * Exclusion fragments for discovery inside an external package's src/,
745
+ * matched against paths RELATIVE TO the src dir. Per spec
746
+ * external-package-file-discovery, the filters apply "within the package" —
747
+ * an npm-installed package whose own location is under node_modules (or a
748
+ * repo path containing 'dist') must still have its sources discovered.
749
+ */
750
+ const PACKAGE_SRC_EXCLUDES = [
751
+ "dist",
752
+ "node_modules",
753
+ ".test.",
754
+ ".spec."
755
+ ];
756
+ /** True when a PACKAGE-RELATIVE path matches a package-source exclusion
757
+ * fragment (the "within the package" filter — see PACKAGE_SRC_EXCLUDES). */
758
+ function isExcludedPackageRelativePath(rel) {
759
+ return PACKAGE_SRC_EXCLUDES.some((pattern) => rel.includes(pattern));
760
+ }
761
+ /**
762
+ * THE package-source walk (guardrail G1 — one policy): shared discovery with
763
+ * no consumer patterns, then exclusion by package-relative path so fragments
764
+ * in the package's own location can't blank out its sources. Used by the
765
+ * collector, hosts' dirty-root rewalks, and watch-path classification alike.
766
+ */
767
+ function walkPackageSources(packageDir, extensionsSet) {
768
+ return discoverFiles(packageDir, packageDir, void 0, extensionsSet).filter((absPath) => !isExcludedPackageRelativePath((0, path.relative)(packageDir, absPath)));
769
+ }
770
+ /** Exclusions for the compiled-output fallback when a package does not ship src/. */
771
+ const PACKAGE_OUTPUT_EXCLUDES = [
772
+ "node_modules",
773
+ ".test.",
774
+ ".spec.",
775
+ ".d.ts",
776
+ ".map"
777
+ ];
778
+ const isFile = (path$3) => {
779
+ try {
780
+ return (0, fs.statSync)(path$3).isFile();
781
+ } catch {
782
+ return false;
783
+ }
784
+ };
785
+ /**
786
+ * Resolve an absolute-path specifier (a relative `includes` entry already
787
+ * resolved against the system file) without a bundler: the path itself when it
788
+ * is a file, otherwise the extension and directory-index candidates built from
789
+ * the caller's extension set. Used only as a fallback — a bundler resolver that
790
+ * answers first still wins, since it also knows aliases and `.js`→`.ts` mapping.
791
+ */
792
+ function resolveAbsolutePathSpecifier(absSpecifier, extensionsSet) {
793
+ return [
794
+ absSpecifier,
795
+ ...Array.from(extensionsSet, (ext) => absSpecifier + ext),
796
+ ...Array.from(extensionsSet, (ext) => (0, path.join)(absSpecifier, `index${ext}`))
797
+ ].find(isFile) ?? null;
798
+ }
799
+ /** The package-name half of a bare specifier (`@scope/name/sub` → `@scope/name`). */
800
+ function bareSpecifierPackageName(specifier) {
801
+ const segments = specifier.split("/");
802
+ return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
803
+ }
804
+ function sourceEntryForSpecifier(specifier, srcDir, extensionsSet) {
805
+ if ((0, path.isAbsolute)(specifier)) {
806
+ const resolved = resolveAbsolutePathSpecifier(specifier, extensionsSet);
807
+ if (!resolved) return null;
808
+ return isPathWithinRoot(srcDir, resolved) ? resolved : null;
809
+ }
810
+ const packageName = bareSpecifierPackageName(specifier);
811
+ return resolveAbsolutePathSpecifier((0, path.join)(srcDir, specifier.slice(packageName.length + 1) || "index"), extensionsSet);
812
+ }
813
+ /**
814
+ * The D13 dist-freshness check: applicable only when a specifier has BOTH a
815
+ * walked src/ tree and a resolved dist entry that exists on disk outside that
816
+ * tree; stale when the dist entry's mtime is older than the newest walked
817
+ * source file's. Not applicable (never stale) when the entry resolves inside
818
+ * src/ (no dist to skew), when the entry file is missing, or when no source
819
+ * file's mtime is readable. Detection only — reporting is the caller's policy.
820
+ */
821
+ function distEntryIsStale(absEntry, srcDir, srcFiles) {
822
+ if (isPathWithinRoot(srcDir, absEntry)) return false;
823
+ let distMtime;
824
+ try {
825
+ distMtime = (0, fs.statSync)(absEntry).mtimeMs;
826
+ } catch {
827
+ return false;
828
+ }
829
+ let newestSrcMtime = -Infinity;
830
+ for (const srcFile of srcFiles) try {
831
+ newestSrcMtime = Math.max(newestSrcMtime, (0, fs.statSync)(srcFile).mtimeMs);
832
+ } catch {}
833
+ return distMtime < newestSrcMtime;
834
+ }
835
+ /**
836
+ * Shared external-package source collection (spec:
837
+ * external-package-file-discovery), consumed by both extraction plugins.
838
+ * For each specifier: resolve to an absolute entry (null/throw → silently
839
+ * skip; an absolute-path specifier falls back to a filesystem probe), walk up
840
+ * to the package root, then either discover sources under src/ (redirecting
841
+ * module resolution to src/index.ts when present) or fall back to ingesting
842
+ * the resolved entry file itself.
843
+ *
844
+ * The only bundler-specific seams are callbacks: specifier resolution,
845
+ * dedup against already-ingested files, per-file preprocessing (MDX), and
846
+ * the unreadable-file warning. Hashing and caching stay in the plugins —
847
+ * their cache policies legitimately differ.
848
+ *
849
+ * Alongside the aggregates, one `ExternalPackageOutcome` per declared
850
+ * specifier records what that specifier produced. Collection never reports on
851
+ * them — any warning or gate is the caller's policy.
852
+ */
853
+ async function collectExternalPackageSources(opts) {
854
+ const { specifiers, resolveSpecifier, rootDir, extensionsSet, hasEntry, onSourceRead, onUnreadable, onPackageResolved } = opts;
855
+ const entries = [];
856
+ const pushed = /* @__PURE__ */ new Set();
857
+ const packageMap = {};
858
+ const sourceEntries = /* @__PURE__ */ new Map();
859
+ const keyframesScanEntries = /* @__PURE__ */ new Map();
860
+ const packageDirs = [];
861
+ const dirOwnerSets = {};
862
+ const dirExtensions = {};
863
+ const fileOwners = {};
864
+ const outcomes = [];
865
+ const claimDir = (dir, specifier) => {
866
+ (dirOwnerSets[dir] ??= []).push(specifier);
867
+ };
868
+ const alreadyIngested = (relPath) => hasEntry(relPath) || pushed.has(relPath);
869
+ for (const specifier of specifiers) {
870
+ let absEntry;
871
+ try {
872
+ absEntry = await resolveSpecifier(specifier);
873
+ } catch {
874
+ absEntry = null;
875
+ }
876
+ if (!absEntry && (0, path.isAbsolute)(specifier)) absEntry = resolveAbsolutePathSpecifier(specifier, extensionsSet);
877
+ if (!absEntry) {
878
+ outcomes.push({
879
+ specifier,
880
+ outcome: "unresolvable",
881
+ fileCount: 0
882
+ });
883
+ continue;
884
+ }
885
+ const srcDir = (0, path.join)(findPackageRoot(absEntry), "src");
886
+ let fileCount = 0;
887
+ let staleDist = false;
888
+ if ((0, fs.existsSync)(srcDir)) {
889
+ packageDirs.push(srcDir);
890
+ claimDir(srcDir, specifier);
891
+ dirExtensions[srcDir] = [...extensionsSet];
892
+ onPackageResolved?.(specifier, srcDir);
893
+ const srcEntry = sourceEntryForSpecifier(specifier, srcDir, extensionsSet);
894
+ if (srcEntry) {
895
+ packageMap[specifier] = (0, path.relative)(rootDir, srcEntry);
896
+ sourceEntries.set(specifier, srcEntry);
897
+ } else packageMap[specifier] = (0, path.relative)(rootDir, absEntry);
898
+ keyframesScanEntries.set(specifier, srcEntry ?? absEntry);
899
+ if (!(0, path.isAbsolute)(specifier)) {
900
+ const packageName = bareSpecifierPackageName(specifier);
901
+ if (packageName !== specifier && !(packageName in packageMap)) {
902
+ const rootEntry = sourceEntryForSpecifier(packageName, srcDir, extensionsSet);
903
+ if (rootEntry) {
904
+ packageMap[packageName] = (0, path.relative)(rootDir, rootEntry);
905
+ sourceEntries.set(packageName, rootEntry);
906
+ keyframesScanEntries.set(packageName, rootEntry);
907
+ }
908
+ }
909
+ }
910
+ const pkgFiles = walkPackageSources(srcDir, extensionsSet);
911
+ staleDist = distEntryIsStale(absEntry, srcDir, pkgFiles);
912
+ for (const pkgFile of pkgFiles) {
913
+ const relPath = (0, path.relative)(rootDir, pkgFile);
914
+ if (alreadyIngested(relPath)) {
915
+ fileCount++;
916
+ continue;
917
+ }
918
+ let source;
919
+ try {
920
+ source = (0, fs.readFileSync)(pkgFile, "utf-8");
921
+ } catch (err) {
922
+ onUnreadable(relPath, err);
923
+ continue;
924
+ }
925
+ onSourceRead?.(source, relPath, pkgFile);
926
+ entries.push({
927
+ path: relPath,
928
+ source
929
+ });
930
+ pushed.add(relPath);
931
+ fileOwners[relPath] ??= specifier;
932
+ fileCount++;
933
+ }
934
+ } else {
935
+ const outputDir = (0, path.dirname)(absEntry);
936
+ packageDirs.push(outputDir);
937
+ claimDir(outputDir, specifier);
938
+ onPackageResolved?.(specifier, outputDir);
939
+ packageMap[specifier] = (0, path.relative)(rootDir, absEntry);
940
+ keyframesScanEntries.set(specifier, absEntry);
941
+ const outputExtensions = new Set(extensionsSet);
942
+ outputExtensions.add((0, path.extname)(absEntry));
943
+ dirExtensions[outputDir] = [...outputExtensions];
944
+ const outputFiles = discoverFiles(outputDir, outputDir, void 0, outputExtensions).filter((file) => {
945
+ const relToOutput = (0, path.relative)(outputDir, file);
946
+ return !PACKAGE_OUTPUT_EXCLUDES.some((pattern) => relToOutput.includes(pattern));
947
+ });
948
+ if (!outputFiles.includes(absEntry)) outputFiles.unshift(absEntry);
949
+ for (const outputFile of outputFiles) {
950
+ const outputRelPath = (0, path.relative)(rootDir, outputFile);
951
+ if (alreadyIngested(outputRelPath)) {
952
+ fileCount++;
953
+ continue;
954
+ }
955
+ let source;
956
+ try {
957
+ source = (0, fs.readFileSync)(outputFile, "utf-8");
958
+ } catch (err) {
959
+ onUnreadable(outputRelPath, err);
960
+ continue;
961
+ }
962
+ onSourceRead?.(source, outputRelPath, outputFile);
963
+ entries.push({
964
+ path: outputRelPath,
965
+ source
966
+ });
967
+ pushed.add(outputRelPath);
968
+ fileOwners[outputRelPath] ??= specifier;
969
+ fileCount++;
970
+ }
971
+ }
972
+ outcomes.push({
973
+ specifier,
974
+ outcome: staleDist ? "stale-dist" : fileCount > 0 ? "resolved" : "empty",
975
+ fileCount
976
+ });
977
+ }
978
+ return {
979
+ entries,
980
+ packageMap,
981
+ sourceEntries,
982
+ keyframesScanEntries,
983
+ packageDirs,
984
+ dirOwnerSets,
985
+ dirExtensions,
986
+ fileOwners,
987
+ outcomes
988
+ };
989
+ }
990
+ /** First-declared specifier per package dir — the single-value ownership
991
+ * view correlation consumers key on, derived from `dirOwnerSets`. */
992
+ function firstOwners(dirOwnerSets) {
993
+ const owners = {};
994
+ for (const [dir, specifiers] of Object.entries(dirOwnerSets)) if (specifiers.length > 0) owners[dir] = specifiers[0];
995
+ return owners;
996
+ }
997
+ /**
998
+ * Excise a set of rejected specifiers from a collection result ATOMICALLY
999
+ * (openspec: external-source-watch-ingestion, design D5): the returned copy
1000
+ * carries no entries, package-map targets, source entries, package dirs, or
1001
+ * ownership for the rejected packages — a package dir is removed only when
1002
+ * EVERY specifier that claimed it is rejected (a dir-level rejection, such
1003
+ * as the cross-volume gate, always rejects them together). Outcome records
1004
+ * are reporting inputs, not membership, and pass through untouched.
1005
+ */
1006
+ function excludeCollectedPackages(collected, rejectedSpecifiers, rootDir) {
1007
+ if (rejectedSpecifiers.size === 0) return collected;
1008
+ const rejectedDirs = Object.entries(collected.dirOwnerSets).filter(([, specs]) => specs.every((s) => rejectedSpecifiers.has(s))).map(([dir]) => dir);
1009
+ const underRejectedDir = (absPath) => rejectedDirs.some((dir) => isPathWithinRoot(dir, absPath));
1010
+ const targetRejected = (specifier, absTarget) => rejectedSpecifiers.has(specifier) || underRejectedDir(absTarget);
1011
+ const packageMap = {};
1012
+ for (const [specifier, relTarget] of Object.entries(collected.packageMap)) {
1013
+ if (targetRejected(specifier, (0, path.resolve)(rootDir, relTarget))) continue;
1014
+ packageMap[specifier] = relTarget;
1015
+ }
1016
+ const sourceEntries = /* @__PURE__ */ new Map();
1017
+ for (const [specifier, absEntry] of collected.sourceEntries) {
1018
+ if (targetRejected(specifier, absEntry)) continue;
1019
+ sourceEntries.set(specifier, absEntry);
1020
+ }
1021
+ const keyframesScanEntries = /* @__PURE__ */ new Map();
1022
+ for (const [specifier, absEntry] of collected.keyframesScanEntries) {
1023
+ if (targetRejected(specifier, absEntry)) continue;
1024
+ keyframesScanEntries.set(specifier, absEntry);
1025
+ }
1026
+ const dirOwnerSets = {};
1027
+ for (const [dir, specs] of Object.entries(collected.dirOwnerSets)) {
1028
+ const kept = specs.filter((s) => !rejectedSpecifiers.has(s));
1029
+ if (kept.length === 0) continue;
1030
+ dirOwnerSets[dir] = kept;
1031
+ }
1032
+ const dirExtensions = {};
1033
+ for (const [dir, exts] of Object.entries(collected.dirExtensions)) {
1034
+ if (rejectedDirs.includes(dir)) continue;
1035
+ dirExtensions[dir] = exts;
1036
+ }
1037
+ const fileOwners = {};
1038
+ for (const [relPath, owner] of Object.entries(collected.fileOwners)) {
1039
+ if (rejectedSpecifiers.has(owner)) continue;
1040
+ fileOwners[relPath] = owner;
1041
+ }
1042
+ return {
1043
+ entries: collected.entries.filter((entry) => !rejectedSpecifiers.has(collected.fileOwners[entry.path])),
1044
+ packageMap,
1045
+ sourceEntries,
1046
+ keyframesScanEntries,
1047
+ packageDirs: collected.packageDirs.filter((dir) => !rejectedDirs.includes(dir)),
1048
+ dirOwnerSets,
1049
+ dirExtensions,
1050
+ fileOwners,
1051
+ outcomes: collected.outcomes
1052
+ };
1053
+ }
1054
+ /**
1055
+ * Extract external DS package names from inheritance declarations in the
1056
+ * system file.
1057
+ *
1058
+ * Supports four forms:
1059
+ * - Primary: `createSystem(...).extend(identifier)` chain calls
1060
+ * (repeatable, mixable with `.from()` links; each call
1061
+ * contributes one source; a library-bundle identifier
1062
+ * traces its base import)
1063
+ * - Deprecated chain: `createSystem(...).from(identifier)` chain calls
1064
+ * - Deprecated alias: `createSystem({ includes: [identifier, ...] })`
1065
+ * - Legacy: `.includes([identifier, ...])` chain method (RC
1066
+ * migration fallback)
1067
+ *
1068
+ * For each identifier found, traces back to its import declaration and returns
1069
+ * the import specifier: a bare specifier normalized to its package name, a
1070
+ * relative specifier resolved against the system file's directory into an
1071
+ * absolute path (so a sibling package referenced by path contributes discovery
1072
+ * too). Only packages explicitly declared through one of these forms are
1073
+ * treated as external DS dependencies.
1074
+ *
1075
+ * Falls back to empty array if no declaration is found.
1076
+ */
1077
+ /**
1078
+ * The message for the strict/warn gate over unresolvable includes, or null
1079
+ * when every declared specifier resolved (external-package-file-discovery:
1080
+ * silence is never an outcome — non-strict consumers warn with this line,
1081
+ * strict consumers throw it).
1082
+ */
1083
+ function unresolvableIncludesMessage(outcomes) {
1084
+ const unresolvable = outcomes.filter((record) => record.outcome === "unresolvable").map((record) => record.specifier);
1085
+ if (unresolvable.length === 0) return null;
1086
+ return `[animus-extract] unresolvable include specifier(s): ${unresolvable.join(", ")}`;
1087
+ }
1088
+ /**
1089
+ * The message for the strict/warn gate over stale dist entries
1090
+ * (first-class-extension D13), or null when no declared specifier is stale.
1091
+ * A stale dist silently skews merged registry content while discovery
1092
+ * compiles the fresh sources, so it surfaces like an unresolvable specifier:
1093
+ * non-strict consumers warn with this line, strict consumers throw it.
1094
+ */
1095
+ function staleDistIncludesMessage(outcomes) {
1096
+ const stale = outcomes.filter((record) => record.outcome === "stale-dist").map((record) => record.specifier);
1097
+ if (stale.length === 0) return null;
1098
+ return `[animus-extract] stale dist for include specifier(s): ${stale.join(", ")} — dist entry is older than the newest src/ file; rebuild the package(s) before extracting`;
1099
+ }
1100
+ function extractSystemFilePackages(systemFilePath) {
1101
+ let source;
1102
+ try {
1103
+ source = (0, fs.readFileSync)(systemFilePath, "utf-8");
1104
+ } catch {
1105
+ return [];
1106
+ }
1107
+ const identifiers = /* @__PURE__ */ new Set();
1108
+ const constructorRegex = /createSystem\s*\(\s*\{[^}]*?\bincludes\s*:\s*\[([^\]]*)\]/gs;
1109
+ const chainRegex = /\.includes\s*\(\s*\[([^\]]*)\]\s*\)/gs;
1110
+ const collectIdentifiers = (regex) => {
1111
+ let match;
1112
+ while ((match = regex.exec(source)) !== null) {
1113
+ const inner = match[1];
1114
+ for (const token of inner.split(",")) {
1115
+ const id = token.trim();
1116
+ if (id && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(id)) identifiers.add(id);
1117
+ }
1118
+ }
1119
+ };
1120
+ collectIdentifiers(constructorRegex);
1121
+ collectIdentifiers(chainRegex);
1122
+ const IDENT_START_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*/;
1123
+ /** Position after any run of whitespace, line comments, block comments. */
1124
+ const skipTrivia = (from) => {
1125
+ let pos = from;
1126
+ for (;;) {
1127
+ while (pos < source.length && /\s/.test(source[pos])) pos++;
1128
+ if (source.startsWith("//", pos)) {
1129
+ const newline = source.indexOf("\n", pos);
1130
+ pos = newline === -1 ? source.length : newline + 1;
1131
+ continue;
1132
+ }
1133
+ if (source.startsWith("/*", pos)) {
1134
+ const close = source.indexOf("*/", pos + 2);
1135
+ pos = close === -1 ? source.length : close + 2;
1136
+ continue;
1137
+ }
1138
+ return pos;
1139
+ }
1140
+ };
1141
+ /**
1142
+ * Consume consecutive extend/from links starting at `from`, collecting
1143
+ * each link's base identifier; tolerates trivia between tokens and a
1144
+ * trailing comma in the argument list. Returns the position after the
1145
+ * last consumed link (`from` itself when none matched).
1146
+ */
1147
+ const consumeChainLinks = (from) => {
1148
+ let pos = from;
1149
+ for (;;) {
1150
+ let cursor = skipTrivia(pos);
1151
+ if (source[cursor] !== ".") return pos;
1152
+ cursor = skipTrivia(cursor + 1);
1153
+ const method = IDENT_START_RE.exec(source.slice(cursor))?.[0];
1154
+ if (method !== "extend" && method !== "from") return pos;
1155
+ cursor = skipTrivia(cursor + method.length);
1156
+ if (source[cursor] !== "(") return pos;
1157
+ cursor = skipTrivia(cursor + 1);
1158
+ const base = IDENT_START_RE.exec(source.slice(cursor))?.[0];
1159
+ if (!base) return pos;
1160
+ cursor = skipTrivia(cursor + base.length);
1161
+ while (source[cursor] === ".") {
1162
+ const afterDot = skipTrivia(cursor + 1);
1163
+ const segment = IDENT_START_RE.exec(source.slice(afterDot))?.[0];
1164
+ if (!segment) break;
1165
+ cursor = skipTrivia(afterDot + segment.length);
1166
+ }
1167
+ if (source[cursor] === ",") cursor = skipTrivia(cursor + 1);
1168
+ if (source[cursor] !== ")") return pos;
1169
+ identifiers.add(base);
1170
+ pos = cursor + 1;
1171
+ }
1172
+ };
1173
+ /** Identifier assigned directly before `index` (`const x = <here>`), if any. */
1174
+ const boundIdentifierBefore = (index) => {
1175
+ const match = /([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*$/.exec(source.slice(0, index));
1176
+ return match ? match[1] : null;
1177
+ };
1178
+ const chainRootIdentifiers = /* @__PURE__ */ new Set();
1179
+ const createSystemAnchor = /createSystem\s*\(/g;
1180
+ let anchorMatch;
1181
+ while ((anchorMatch = createSystemAnchor.exec(source)) !== null) {
1182
+ let pos = anchorMatch.index + anchorMatch[0].length;
1183
+ let depth = 1;
1184
+ while (pos < source.length && depth > 0) {
1185
+ const ch = source[pos];
1186
+ if (ch === "(") depth++;
1187
+ else if (ch === ")") depth--;
1188
+ pos++;
1189
+ }
1190
+ consumeChainLinks(pos);
1191
+ const bound = boundIdentifierBefore(anchorMatch.index);
1192
+ if (bound) chainRootIdentifiers.add(bound);
1193
+ }
1194
+ const scannedRoots = /* @__PURE__ */ new Set();
1195
+ for (;;) {
1196
+ const pendingRoots = [...chainRootIdentifiers].filter((root) => !scannedRoots.has(root));
1197
+ if (pendingRoots.length === 0) break;
1198
+ for (const root of pendingRoots) {
1199
+ scannedRoots.add(root);
1200
+ const rootUse = new RegExp(`(?<![a-zA-Z0-9_$])${root.replace(/\$/g, "\\$")}(?![a-zA-Z0-9_$])`, "g");
1201
+ let useMatch;
1202
+ while ((useMatch = rootUse.exec(source)) !== null) {
1203
+ const afterIdentifier = useMatch.index + useMatch[0].length;
1204
+ if (consumeChainLinks(afterIdentifier) === afterIdentifier) continue;
1205
+ const bound = boundIdentifierBefore(useMatch.index);
1206
+ if (bound) chainRootIdentifiers.add(bound);
1207
+ }
1208
+ }
1209
+ }
1210
+ if (identifiers.size === 0) return [];
1211
+ const importMap = /* @__PURE__ */ new Map();
1212
+ const importRegex = /^\s*import\s+(?:([a-zA-Z_$][a-zA-Z0-9_$]*)\s*,\s*)?(?:\{([^}]*)\}|([a-zA-Z_$][a-zA-Z0-9_$]*))\s+from\s+['"]([^'"]+)['"]/gm;
1213
+ let importMatch;
1214
+ while ((importMatch = importRegex.exec(source)) !== null) {
1215
+ const [, comboDefault, namedImports, defaultImport, specifier] = importMatch;
1216
+ if (comboDefault) importMap.set(comboDefault, specifier);
1217
+ if (defaultImport) importMap.set(defaultImport, specifier);
1218
+ if (namedImports) for (const binding of namedImports.split(",")) {
1219
+ const parts = binding.trim().split(/\s+as\s+/);
1220
+ const localName = (parts[1] || parts[0]).trim();
1221
+ if (localName) importMap.set(localName, specifier);
1222
+ }
1223
+ }
1224
+ const systemFileDir = (0, path.dirname)(systemFilePath);
1225
+ const packages = /* @__PURE__ */ new Set();
1226
+ for (const id of identifiers) {
1227
+ const specifier = importMap.get(id);
1228
+ if (!specifier) continue;
1229
+ if (specifier.startsWith(".")) packages.add((0, path.resolve)(systemFileDir, specifier));
1230
+ else packages.add(specifier);
1231
+ }
1232
+ return Array.from(packages);
1233
+ }
1234
+ //#endregion
1235
+ //#region pipeline/svelte-source-adapter.ts
1236
+ function isNode(value) {
1237
+ return typeof value === "object" && value !== null && typeof value.type === "string" && typeof value.start === "number" && typeof value.end === "number";
1238
+ }
1239
+ function childNode(value) {
1240
+ return isNode(value) ? value : null;
1241
+ }
1242
+ function nodeName(node) {
1243
+ return node?.type === "Identifier" && typeof node.name === "string" ? node.name : null;
1244
+ }
1245
+ /** Adaptation touches one source at a time, so a last-value memo makes the
1246
+ * all-ASCII check O(n) once per file instead of per span endpoint. */
1247
+ let asciiMemoSource = null;
1248
+ let asciiMemoValue = false;
1249
+ function isAsciiOnly(source) {
1250
+ if (asciiMemoSource !== source) {
1251
+ asciiMemoSource = source;
1252
+ asciiMemoValue = Buffer.byteLength(source) === source.length;
1253
+ }
1254
+ return asciiMemoValue;
1255
+ }
1256
+ function byteOffset(source, characterOffset) {
1257
+ if (isAsciiOnly(source)) return characterOffset;
1258
+ return Buffer.byteLength(source.slice(0, characterOffset));
1259
+ }
1260
+ function byteSpan(source, node) {
1261
+ return {
1262
+ start: byteOffset(source, node.start),
1263
+ end: byteOffset(source, node.end)
1264
+ };
1265
+ }
1266
+ function sourcePosition(source, characterOffset) {
1267
+ let line = 1;
1268
+ let lineStart = 0;
1269
+ for (let index = 0; index < characterOffset; index += 1) {
1270
+ const code = source.charCodeAt(index);
1271
+ if (code === 13) {
1272
+ if (index + 1 < characterOffset && source.charCodeAt(index + 1) === 10) index += 1;
1273
+ line += 1;
1274
+ lineStart = index + 1;
1275
+ } else if (code === 10 || code === 8232 || code === 8233) {
1276
+ line += 1;
1277
+ lineStart = index + 1;
1278
+ }
1279
+ }
1280
+ return {
1281
+ line,
1282
+ column: characterOffset - lineStart
1283
+ };
1284
+ }
1285
+ function sourceLocation(source, node) {
1286
+ return {
1287
+ start: sourcePosition(source, node.start),
1288
+ end: sourcePosition(source, node.end)
1289
+ };
1290
+ }
1291
+ function createsNestedBindingScope(node) {
1292
+ return node.type === "BlockStatement" || node.type === "CatchClause" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassExpression" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "StaticBlock" || node.type === "SwitchStatement" || node.type === "TSModuleBlock";
1293
+ }
1294
+ function walk(node, visit, nestedScopeDepth = 0) {
1295
+ visit(node, nestedScopeDepth);
1296
+ const childScopeDepth = nestedScopeDepth + (createsNestedBindingScope(node) ? 1 : 0);
1297
+ for (const [key, value] of Object.entries(node)) {
1298
+ if (key === "loc" || key === "start" || key === "end") continue;
1299
+ if (Array.isArray(value)) {
1300
+ for (const item of value) if (isNode(item)) walk(item, visit, childScopeDepth);
1301
+ } else if (isNode(value)) walk(value, visit, childScopeDepth);
1302
+ }
1303
+ }
1304
+ /**
1305
+ * Fragment traversal: Svelte `Fragment` containers (the template root and
1306
+ * every block body) carry no `start`/`end`, so the script walker's isNode
1307
+ * gate would stop at each one. Descend through every plain object/array,
1308
+ * visit only span-carrying nodes, and guard against metadata back-references.
1309
+ */
1310
+ function walkFragment(value, visit) {
1311
+ const seen = /* @__PURE__ */ new WeakSet();
1312
+ const descend = (current) => {
1313
+ if (Array.isArray(current)) {
1314
+ for (const item of current) descend(item);
1315
+ return;
1316
+ }
1317
+ if (typeof current !== "object" || current === null) return;
1318
+ if (seen.has(current)) return;
1319
+ seen.add(current);
1320
+ if (isNode(current)) visit(current);
1321
+ for (const [key, child] of Object.entries(current)) {
1322
+ if (key === "loc" || key === "start" || key === "end" || key === "metadata" || key === "parent") continue;
1323
+ descend(child);
1324
+ }
1325
+ };
1326
+ descend(value);
1327
+ }
1328
+ function importBindings(program) {
1329
+ const bindings = /* @__PURE__ */ new Map();
1330
+ for (const declaration of program.body) {
1331
+ if (declaration.type !== "ImportDeclaration" || declaration.importKind === "type" || !Array.isArray(declaration.specifiers)) continue;
1332
+ for (const value of declaration.specifiers) {
1333
+ if (!isNode(value) || value.importKind === "type") continue;
1334
+ const local = childNode(value.local);
1335
+ const localName = nodeName(local);
1336
+ if (!local || !localName) continue;
1337
+ const sourceNode = childNode(declaration.source);
1338
+ const importSource = sourceNode && typeof sourceNode.value === "string" ? sourceNode.value : null;
1339
+ if (!importSource) continue;
1340
+ const namedImported = importedName(value);
1341
+ if (value.type === "ImportSpecifier" && namedImported === null) continue;
1342
+ const importedNode = childNode(value.imported);
1343
+ const kind = value.type === "ImportSpecifier" ? importedNode?.type === "Literal" ? "string-named" : namedImported === "default" ? "named-default" : "named" : value.type === "ImportDefaultSpecifier" ? "default" : value.type === "ImportNamespaceSpecifier" ? "namespace" : null;
1344
+ if (kind) bindings.set(localName, {
1345
+ kind,
1346
+ source: importSource,
1347
+ imported: kind === "default" || kind === "named-default" ? "default" : kind === "namespace" ? "*" : namedImported,
1348
+ declaration,
1349
+ specifier: value,
1350
+ local
1351
+ });
1352
+ }
1353
+ }
1354
+ return bindings;
1355
+ }
1356
+ function diagnostic(code, message, originalPath, source, node, location) {
1357
+ return {
1358
+ code,
1359
+ message,
1360
+ originalPath,
1361
+ ...node ? {
1362
+ span: byteSpan(source, node),
1363
+ location: location ?? sourceLocation(source, node)
1364
+ } : {}
1365
+ };
1366
+ }
1367
+ function compilerParseErrorRange(error, source) {
1368
+ if (typeof error !== "object" || error === null) return null;
1369
+ const candidate = error;
1370
+ const positions = Array.isArray(candidate.position) ? candidate.position : [];
1371
+ const startCharacter = typeof candidate.start?.character === "number" ? candidate.start.character : typeof positions[0] === "number" ? positions[0] : null;
1372
+ const endCharacter = typeof candidate.end?.character === "number" ? candidate.end.character : typeof positions[1] === "number" ? positions[1] : startCharacter;
1373
+ if (startCharacter === null || endCharacter === null || startCharacter < 0 || endCharacter < startCharacter || endCharacter > source.length) return null;
1374
+ const node = {
1375
+ type: "SvelteParseError",
1376
+ start: startCharacter,
1377
+ end: endCharacter
1378
+ };
1379
+ const fallback = sourceLocation(source, node);
1380
+ const point = (value, fallbackPoint) => ({
1381
+ line: typeof value?.line === "number" ? value.line : fallbackPoint.line,
1382
+ column: typeof value?.column === "number" ? value.column : fallbackPoint.column
1383
+ });
1384
+ return {
1385
+ node,
1386
+ location: {
1387
+ start: point(candidate.start, fallback.start),
1388
+ end: point(candidate.end, fallback.end)
1389
+ }
1390
+ };
1391
+ }
1392
+ function calleeParts(node) {
1393
+ if (node.type !== "CallExpression") return null;
1394
+ const callee = childNode(node.callee);
1395
+ if (!callee || callee.type !== "MemberExpression") return null;
1396
+ const object = childNode(callee.object);
1397
+ const property = childNode(callee.property);
1398
+ if (!object || !property) return null;
1399
+ if ((nodeName(property) ?? (property.type === "Literal" && property.value === "attrs" ? "attrs" : null)) !== "attrs") return null;
1400
+ return {
1401
+ object,
1402
+ property,
1403
+ computed: callee.computed === true,
1404
+ optional: callee.optional === true || node.optional === true
1405
+ };
1406
+ }
1407
+ function resolverImportAccess(receiver, bindings) {
1408
+ const directName = nodeName(receiver);
1409
+ if (directName) {
1410
+ const binding = bindings.get(directName);
1411
+ if (!binding) return null;
1412
+ return {
1413
+ binding,
1414
+ resolver: receiver,
1415
+ displayName: directName,
1416
+ request: {
1417
+ source: binding.source,
1418
+ imported: binding.imported,
1419
+ local: directName,
1420
+ access: {
1421
+ kind: "direct",
1422
+ importKind: binding.kind
1423
+ }
1424
+ }
1425
+ };
1426
+ }
1427
+ if (receiver.type !== "MemberExpression" || receiver.computed === true || receiver.optional === true) return null;
1428
+ const namespaceNode = childNode(receiver.object);
1429
+ const memberNode = childNode(receiver.property);
1430
+ const namespaceName = nodeName(namespaceNode);
1431
+ const memberName = nodeName(memberNode) ?? (memberNode?.type === "Literal" && typeof memberNode.value === "string" ? memberNode.value : null);
1432
+ if (!namespaceNode || !namespaceName || !memberName) return null;
1433
+ const binding = bindings.get(namespaceName);
1434
+ if (!binding || binding.kind !== "namespace") return null;
1435
+ return {
1436
+ binding,
1437
+ resolver: receiver,
1438
+ displayName: `${namespaceName}.${memberName}`,
1439
+ request: {
1440
+ source: binding.source,
1441
+ imported: memberName,
1442
+ local: namespaceName,
1443
+ access: {
1444
+ kind: "namespace-member",
1445
+ importKind: "namespace"
1446
+ }
1447
+ }
1448
+ };
1449
+ }
1450
+ function isSupportedResolverAccess(access) {
1451
+ return access.binding.kind === "named" && access.request.access.kind === "direct";
1452
+ }
1453
+ function resolverCallSite(node, bindings) {
1454
+ if (node.type !== "CallExpression") return null;
1455
+ const parts = calleeParts(node);
1456
+ if (parts) {
1457
+ const access = resolverImportAccess(parts.object, bindings);
1458
+ if (!access) return null;
1459
+ return {
1460
+ access,
1461
+ form: "attrs",
1462
+ computed: parts.computed,
1463
+ optional: parts.optional
1464
+ };
1465
+ }
1466
+ const callee = childNode(node.callee);
1467
+ if (!callee) return null;
1468
+ const access = resolverImportAccess(callee, bindings);
1469
+ if (!access) return null;
1470
+ return {
1471
+ access,
1472
+ form: "callable",
1473
+ computed: callee.type === "MemberExpression" && callee.computed === true,
1474
+ optional: node.optional === true || callee.type === "MemberExpression" && callee.optional === true
1475
+ };
1476
+ }
1477
+ function argumentSpan(argumentsList, fallback) {
1478
+ if (argumentsList.length === 0) return fallback;
1479
+ return {
1480
+ type: "ArgumentRange",
1481
+ start: argumentsList[0].start,
1482
+ end: argumentsList[argumentsList.length - 1].end
1483
+ };
1484
+ }
1485
+ function propertyName(node) {
1486
+ const key = childNode(node.key);
1487
+ if (!key) return null;
1488
+ if (key.type === "Identifier" && typeof key.name === "string") return key.name;
1489
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
1490
+ return null;
1491
+ }
1492
+ function isJsxAttributeName(name) {
1493
+ return /^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(name);
1494
+ }
1495
+ function tsxIncompatibleValue(value) {
1496
+ let incompatible = null;
1497
+ walk(value, (node) => {
1498
+ if (incompatible) return;
1499
+ if (node.type === "TSTypeAssertion" || node.type === "ArrowFunctionExpression" && childNode(node.typeParameters) !== null) incompatible = node;
1500
+ });
1501
+ return incompatible;
1502
+ }
1503
+ function readProperties(argument, source, originalPath) {
1504
+ if (!Array.isArray(argument.properties)) return diagnostic("SVELTE_ATTRS_ARGUMENT_UNRESOLVED", "Resolver .attrs() requires an object literal with statically named properties.", originalPath, source, argument);
1505
+ const properties = [];
1506
+ for (const value of argument.properties) {
1507
+ if (!isNode(value)) continue;
1508
+ if (value.type === "SpreadElement") return diagnostic("SVELTE_ATTRS_SPREAD_UNRESOLVED", "Resolver .attrs() object spreads are unresolved; enumerate properties explicitly.", originalPath, source, value);
1509
+ if (value.type !== "Property") return diagnostic("SVELTE_ATTRS_PROPERTY_UNSUPPORTED", "Resolver .attrs() accepts ordinary object properties only.", originalPath, source, value);
1510
+ if (value.computed === true) return diagnostic("SVELTE_ATTRS_COMPUTED_KEY", "Resolver .attrs() computed property names cannot be attributed safely.", originalPath, source, value);
1511
+ if (value.method === true || value.kind !== "init") return diagnostic("SVELTE_ATTRS_PROPERTY_UNSUPPORTED", "Resolver .attrs() methods and accessors cannot be projected as attributes.", originalPath, source, value);
1512
+ const key = childNode(value.key);
1513
+ const propertyValue = childNode(value.value);
1514
+ const name = propertyName(value);
1515
+ if (!key || !propertyValue || !name || !isJsxAttributeName(name)) return diagnostic("SVELTE_ATTRS_PROPERTY_UNSUPPORTED", "Resolver .attrs() property names must be JSX-compatible identifier or string names.", originalPath, source, value);
1516
+ const incompatibleValue = tsxIncompatibleValue(propertyValue);
1517
+ if (incompatibleValue) return diagnostic("SVELTE_ATTRS_VALUE_UNSUPPORTED", "Resolver .attrs() values using angle-bracket type assertions or generic arrow parameters cannot be projected into TSX safely.", originalPath, source, incompatibleValue);
1518
+ properties.push({
1519
+ name,
1520
+ property: value,
1521
+ key,
1522
+ value: propertyValue
1523
+ });
1524
+ }
1525
+ return properties;
1526
+ }
1527
+ var VirtualSourceBuilder = class {
1528
+ chunks = [];
1529
+ bytes = 0;
1530
+ mappings = [];
1531
+ constructor(originalSource) {
1532
+ this.originalSource = originalSource;
1533
+ }
1534
+ append(text) {
1535
+ this.chunks.push(text);
1536
+ this.bytes += Buffer.byteLength(text);
1537
+ }
1538
+ appendMapped(text, kind, original) {
1539
+ const start = this.bytes;
1540
+ this.append(text);
1541
+ this.mappings.push({
1542
+ kind,
1543
+ generated: {
1544
+ start,
1545
+ end: this.bytes
1546
+ },
1547
+ original: byteSpan(this.originalSource, original)
1548
+ });
1549
+ }
1550
+ toString() {
1551
+ return this.chunks.join("");
1552
+ }
1553
+ };
1554
+ function importedName(specifier) {
1555
+ const imported = childNode(specifier.imported);
1556
+ if (!imported) return null;
1557
+ if (imported.type === "Identifier" && typeof imported.name === "string") return imported.name;
1558
+ if (imported.type === "Literal" && typeof imported.value === "string") return imported.value;
1559
+ return null;
1560
+ }
1561
+ function renderImport(declaration, witnessedBindings, source) {
1562
+ if (!Array.isArray(declaration.specifiers)) return null;
1563
+ const names = [];
1564
+ const locals = [];
1565
+ for (const value of declaration.specifiers) {
1566
+ if (!isNode(value) || value.type !== "ImportSpecifier") continue;
1567
+ const localName = nodeName(childNode(value.local));
1568
+ if (!localName || !witnessedBindings.has(localName)) continue;
1569
+ names.push(source.slice(value.start, value.end));
1570
+ locals.push(localName);
1571
+ }
1572
+ if (names.length === 0) return null;
1573
+ const sourceNode = childNode(declaration.source);
1574
+ const sourceText = sourceNode && typeof sourceNode.raw === "string" ? sourceNode.raw : sourceNode && typeof sourceNode.value === "string" ? JSON.stringify(sourceNode.value) : null;
1575
+ return sourceText ? {
1576
+ text: `import { ${names.join(", ")} } from ${sourceText};\n`,
1577
+ locals
1578
+ } : null;
1579
+ }
1580
+ /** Memoizes success only: a missing optional peer retries per file, so
1581
+ * installing `svelte` mid-session recovers without a process restart. */
1582
+ let compilerMemo = null;
1583
+ async function loadCompiler() {
1584
+ if (compilerMemo) return compilerMemo;
1585
+ compilerMemo = await import("svelte/compiler").catch(() => null);
1586
+ return compilerMemo;
1587
+ }
1588
+ function projectScope(script, scope, source, originalPath, options, inherited, precomputedOwnBindings) {
1589
+ const ownBindings = precomputedOwnBindings ?? importBindings(script.content);
1590
+ const bindings = inherited ? new Map([...inherited.bindings, ...ownBindings]) : ownBindings;
1591
+ const witnesses = [];
1592
+ const diagnostics = [];
1593
+ if (bindings.size > 0) walk(script.content, (node, nestedScopeDepth) => {
1594
+ const site = resolverCallSite(node, bindings);
1595
+ if (!site) return;
1596
+ const { access, form } = site;
1597
+ const attribution = options.attributeResolver(access.request);
1598
+ if (attribution === "other") return;
1599
+ const resolverName = access.displayName;
1600
+ const callDisplay = form === "attrs" ? `${resolverName}.attrs()` : `${resolverName}()`;
1601
+ if (attribution === "unsupported-resolver-form" || !isSupportedResolverAccess(access)) {
1602
+ diagnostics.push(diagnostic("SVELTE_ATTRS_IMPORT_UNSUPPORTED", `Resolver '${resolverName}' uses an import/access form that the extraction engine cannot attribute to its exported .asClass() binding.`, originalPath, source, access.resolver));
1603
+ return;
1604
+ }
1605
+ if (nestedScopeDepth > 0) {
1606
+ diagnostics.push(diagnostic("SVELTE_ATTRS_SCOPE_UNSUPPORTED", `Resolver '${callDisplay}' is inside a nested binding scope; move the call to the top-level script scope so its import identity is unambiguous.`, originalPath, source, access.resolver));
1607
+ return;
1608
+ }
1609
+ if (site.computed || site.optional) {
1610
+ diagnostics.push(diagnostic("SVELTE_ATTRS_CALLEE_UNSUPPORTED", `Resolver '${resolverName}' must be called directly as ${resolverName}(...) or ${resolverName}.attrs(...).`, originalPath, source, node));
1611
+ return;
1612
+ }
1613
+ const argumentsList = Array.isArray(node.arguments) ? node.arguments.filter(isNode) : [];
1614
+ if (argumentsList.length === 0) {
1615
+ witnesses.push({
1616
+ binding: access.binding,
1617
+ resolver: access.resolver,
1618
+ properties: []
1619
+ });
1620
+ return;
1621
+ }
1622
+ if (argumentsList.length !== 1 || argumentsList[0].type !== "ObjectExpression") {
1623
+ diagnostics.push(diagnostic("SVELTE_ATTRS_ARGUMENT_UNRESOLVED", `Resolver '${callDisplay}' accepts no argument or one object literal in Svelte projection.`, originalPath, source, argumentSpan(argumentsList, node)));
1624
+ return;
1625
+ }
1626
+ const properties = readProperties(argumentsList[0], source, originalPath);
1627
+ if (!Array.isArray(properties)) {
1628
+ diagnostics.push(properties);
1629
+ return;
1630
+ }
1631
+ witnesses.push({
1632
+ binding: access.binding,
1633
+ resolver: access.resolver,
1634
+ properties
1635
+ });
1636
+ });
1637
+ if (diagnostics.length > 0 || witnesses.length === 0) return { diagnostics };
1638
+ const witnessedBindings = new Set(witnesses.map((witness) => nodeName(witness.binding.local)));
1639
+ const builder = new VirtualSourceBuilder(source);
1640
+ const pendingNames = new Set(witnessedBindings);
1641
+ const renderDeclarations = (declarations) => {
1642
+ for (const declaration of declarations) {
1643
+ if (declaration.type !== "ImportDeclaration") continue;
1644
+ const rendered = renderImport(declaration, pendingNames, source);
1645
+ if (!rendered) continue;
1646
+ builder.append(rendered.text);
1647
+ for (const local of rendered.locals) pendingNames.delete(local);
1648
+ }
1649
+ };
1650
+ renderDeclarations(script.content.body);
1651
+ if (inherited) renderDeclarations(inherited.importDeclarations);
1652
+ for (const witness of witnesses) {
1653
+ const resolverName = nodeName(witness.resolver);
1654
+ builder.append("<");
1655
+ builder.appendMapped(resolverName, "resolver", witness.resolver);
1656
+ for (const property of witness.properties) {
1657
+ builder.append(" ");
1658
+ builder.appendMapped(property.name, "attribute", property.key);
1659
+ builder.append("={");
1660
+ builder.appendMapped(source.slice(property.value.start, property.value.end), "value", property.value);
1661
+ builder.append("}");
1662
+ }
1663
+ builder.append(" />;\n");
1664
+ }
1665
+ return {
1666
+ diagnostics: [],
1667
+ entry: {
1668
+ scope,
1669
+ path: `${originalPath}.${scope}.tsx`,
1670
+ source: builder.toString(),
1671
+ mappings: builder.mappings
1672
+ }
1673
+ };
1674
+ }
1675
+ /**
1676
+ * Project native Svelte script scopes into parser-only TSX witnesses.
1677
+ *
1678
+ * This adapter parses source, never compiler-generated runtime JavaScript.
1679
+ * Module and instance scripts project separately (module bindings are in
1680
+ * scope for the instance script, per Svelte semantics) and contribute only
1681
+ * witnessed named imports plus synthetic JSX attributes for direct resolver
1682
+ * `.attrs()` and callable-string calls. Caller-owned metadata attributes
1683
+ * candidate imports; unsupported call shapes — including resolver calls
1684
+ * written in the template fragment — fail the whole source closed.
1685
+ */
1686
+ async function adaptSvelteSource(source, originalPath, options) {
1687
+ const original = {
1688
+ path: originalPath,
1689
+ hash: contentHash(source)
1690
+ };
1691
+ const compiler = await loadCompiler();
1692
+ if (!compiler) return {
1693
+ kind: "missing-dep",
1694
+ original,
1695
+ dependency: "svelte/compiler"
1696
+ };
1697
+ let ast;
1698
+ try {
1699
+ ast = compiler.parse(source, {
1700
+ filename: originalPath,
1701
+ modern: true
1702
+ });
1703
+ } catch (error) {
1704
+ const range = compilerParseErrorRange(error, source);
1705
+ return {
1706
+ kind: "error",
1707
+ original,
1708
+ diagnostics: [diagnostic("SVELTE_PARSE_ERROR", error instanceof Error ? error.message : String(error), originalPath, source, range?.node, range?.location)]
1709
+ };
1710
+ }
1711
+ const projections = [];
1712
+ const moduleBindings = ast.module ? importBindings(ast.module.content) : void 0;
1713
+ const instanceBindings = ast.instance ? importBindings(ast.instance.content) : void 0;
1714
+ const moduleScope = ast.module && moduleBindings ? {
1715
+ bindings: moduleBindings,
1716
+ importDeclarations: ast.module.content.body.filter((declaration) => declaration.type === "ImportDeclaration")
1717
+ } : void 0;
1718
+ if (ast.module) projections.push(projectScope(ast.module, "module", source, originalPath, options, void 0, moduleBindings));
1719
+ if (ast.instance) projections.push(projectScope(ast.instance, "instance", source, originalPath, options, moduleScope, instanceBindings));
1720
+ const diagnostics = projections.flatMap((projection) => projection.diagnostics);
1721
+ if (ast.fragment) {
1722
+ const scriptBindings = instanceBindings ?? /* @__PURE__ */ new Map();
1723
+ const fragmentBindings = moduleScope ? new Map([...moduleScope.bindings, ...scriptBindings]) : scriptBindings;
1724
+ if (fragmentBindings.size > 0) walkFragment(ast.fragment, (node) => {
1725
+ const site = resolverCallSite(node, fragmentBindings);
1726
+ if (!site) return;
1727
+ if (options.attributeResolver(site.access.request) === "other") return;
1728
+ diagnostics.push(diagnostic("SVELTE_ATTRS_TEMPLATE_UNSUPPORTED", `Resolver '${site.access.displayName}' is called inside the template; assign the result to a const in the instance script and spread that instead.`, originalPath, source, node));
1729
+ });
1730
+ }
1731
+ if (diagnostics.length > 0) return {
1732
+ kind: "error",
1733
+ original,
1734
+ diagnostics
1735
+ };
1736
+ return {
1737
+ kind: "ok",
1738
+ original,
1739
+ entries: projections.flatMap((projection) => projection.entry ? [projection.entry] : [])
1740
+ };
1741
+ }
1742
+ //#endregion
1743
+ //#region pipeline/mdx-preprocessor.ts
1744
+ /**
1745
+ * MDX source preprocessor for the extraction pipeline.
1746
+ *
1747
+ * MDX files are first-class consumers of ds-built components but are not
1748
+ * directly parseable by OXC (which the scanner uses for .tsx/.jsx). This
1749
+ * module compiles MDX sources to scanner-consumable JSX using @mdx-js/mdx.
1750
+ *
1751
+ * @mdx-js/mdx is declared as `peerDependenciesMeta.optional` on the
1752
+ * plugin packages that import this module. The dynamic import with
1753
+ * .catch() ensures non-MDX consumers (who configure `extensions` to
1754
+ * exclude .mdx) never trigger the resolution — zero install-footprint
1755
+ * cost for them.
1756
+ *
1757
+ * The `DEFAULT_EXTENSIONS` constant is the shared source of truth for
1758
+ * both `@animus-ui/vite-plugin` and `@animus-ui/next-plugin`. Each plugin
1759
+ * imports it directly; independent redeclaration of default extensions
1760
+ * is considered a regression.
1761
+ */
1762
+ const DEFAULT_EXTENSIONS = [
1763
+ ".ts",
1764
+ ".tsx",
1765
+ ".js",
1766
+ ".jsx",
1767
+ ".mdx"
1768
+ ];
1769
+ /**
1770
+ * Extensions the ENGINE TRANSFORM may rewrite (distinct from
1771
+ * `DEFAULT_EXTENSIONS`, the discovery set: `.mjs` is here so dist-entry
1772
+ * kits reach the engine, `.mdx` is not — MDX is preprocessed to `.tsx`
1773
+ * before the engine sees it). The single source for the Turbopack rule
1774
+ * glob and the unplugin transform gate; independent redeclaration of this
1775
+ * set is considered a regression — a missed copy silently skips a whole
1776
+ * file class on one bundler family.
1777
+ */
1778
+ const ENGINE_TRANSFORM_EXTENSIONS = [
1779
+ "ts",
1780
+ "tsx",
1781
+ "js",
1782
+ "jsx",
1783
+ "mjs"
1784
+ ];
1785
+ /**
1786
+ * Preprocess an MDX source string into scanner-consumable JSX.
1787
+ *
1788
+ * - Returns `{ kind: 'ok', source }` with JSX-compiled output on success.
1789
+ * - Returns `{ kind: 'missing-dep' }` if @mdx-js/mdx is not resolvable
1790
+ * (consumer needs to install it).
1791
+ * - Returns `{ kind: 'error', error }` on compile failure (e.g. malformed
1792
+ * MDX syntax). Plugins SHALL warn + skip affected files; the build
1793
+ * continues with remaining files.
1794
+ */
1795
+ async function preprocessMdx(source, filename) {
1796
+ const mdxMod = await import("@mdx-js/mdx").catch(() => null);
1797
+ if (mdxMod === null) return { kind: "missing-dep" };
1798
+ try {
1799
+ const vfile = await mdxMod.compile(source, {
1800
+ outputFormat: "program",
1801
+ development: false,
1802
+ jsx: true
1803
+ });
1804
+ return {
1805
+ kind: "ok",
1806
+ source: `/* @mdx-source: ${filename} */\n${String(vfile)}`
1807
+ };
1808
+ } catch (err) {
1809
+ return {
1810
+ kind: "error",
1811
+ error: err instanceof Error ? err.message : String(err)
1812
+ };
1813
+ }
1814
+ }
1815
+ //#endregion
1816
+ //#region pipeline/source-ingestion.ts
1817
+ /**
1818
+ * Advisory diagnostics surface as warnings in EVERY mode and never
1819
+ * quarantine their file. OXC reports recovered parse diagnostics for
1820
+ * sources the consumer's own toolchain may accept (`.js` now parses
1821
+ * JSX-enabled, so genuinely malformed code is the remaining producer),
1822
+ * and the engine still analyzes whatever the recovered AST carries —
1823
+ * failing the build for that would make extraction stricter than the
1824
+ * host bundler, which surfaces its own error for the same file. Everything
1825
+ * else stays fatal: strict throws, non-strict warns and quarantines.
1826
+ */
1827
+ function isAdvisorySourceDiagnostic(diagnostic) {
1828
+ return diagnostic.code === "SOURCE_NATIVE_PARSE_ERROR";
1829
+ }
1830
+ const RELATIVE_PROBE_SUFFIXES = [
1831
+ "",
1832
+ ".ts",
1833
+ ".tsx",
1834
+ ".js",
1835
+ ".jsx",
1836
+ "/index.ts",
1837
+ "/index.tsx",
1838
+ "/index.js",
1839
+ "/index.jsx"
1840
+ ];
1841
+ function extension(path) {
1842
+ const basename = node_path.posix.basename(path);
1843
+ const dot = basename.lastIndexOf(".");
1844
+ return dot === -1 ? "" : basename.slice(dot).toLowerCase();
1845
+ }
1846
+ function canonicalResolverPath(path) {
1847
+ return node_path.posix.normalize(path.replaceAll("\\", "/"));
1848
+ }
1849
+ /** NodeNext-style relative specifiers carry the EMITTED extension
1850
+ * (`./definition.js` for `definition.ts`); map each back to its source
1851
+ * forms. The exact spelling is probed first by the suffix loop's empty
1852
+ * suffix, so a literal `.js` neighbor still wins. */
1853
+ const NODE_NEXT_EXTENSION_MAP = {
1854
+ ".js": [
1855
+ ".ts",
1856
+ ".tsx",
1857
+ ".jsx"
1858
+ ],
1859
+ ".mjs": [".mts"],
1860
+ ".cjs": [".cts"]
1861
+ };
1862
+ function resolveRelativeSource(importerPath, specifier, files) {
1863
+ if (!specifier.startsWith(".")) return null;
1864
+ const base = node_path.posix.normalize(node_path.posix.join(node_path.posix.dirname(canonicalResolverPath(importerPath)), specifier));
1865
+ for (const suffix of RELATIVE_PROBE_SUFFIXES) {
1866
+ const candidate = `${base}${suffix}`;
1867
+ const actualPath = files.get(candidate);
1868
+ if (actualPath !== void 0) return actualPath;
1869
+ }
1870
+ const explicitExtension = extension(base);
1871
+ for (const sourceExtension of NODE_NEXT_EXTENSION_MAP[explicitExtension] ?? []) {
1872
+ const candidate = `${base.slice(0, -explicitExtension.length)}${sourceExtension}`;
1873
+ const actualPath = files.get(candidate);
1874
+ if (actualPath !== void 0) return actualPath;
1875
+ }
1876
+ return null;
1877
+ }
1878
+ var ResolverExportIndex = class {
1879
+ collisions;
1880
+ files;
1881
+ resolverBindings = /* @__PURE__ */ new Map();
1882
+ /** The same (importer, request) pair repeats for every call site of one
1883
+ * resolver in one file; the index is rebuilt per ingest, so neither memo
1884
+ * needs invalidation. */
1885
+ attributionMemo = /* @__PURE__ */ new Map();
1886
+ resolveMemo = /* @__PURE__ */ new Map();
1887
+ constructor(facts, analysisPaths) {
1888
+ this.facts = facts;
1889
+ const pathsByCanonical = /* @__PURE__ */ new Map();
1890
+ for (const path of analysisPaths) {
1891
+ const canonicalPath = canonicalResolverPath(path);
1892
+ const paths = pathsByCanonical.get(canonicalPath) ?? [];
1893
+ paths.push(path);
1894
+ pathsByCanonical.set(canonicalPath, paths);
1895
+ }
1896
+ this.collisions = [...pathsByCanonical].filter(([, paths]) => paths.length > 1).map(([canonicalPath, paths]) => ({
1897
+ canonicalPath,
1898
+ paths
1899
+ }));
1900
+ const factPathsByCanonical = /* @__PURE__ */ new Map();
1901
+ for (const path of Object.keys(facts.files)) {
1902
+ const canonicalPath = canonicalResolverPath(path);
1903
+ const paths = factPathsByCanonical.get(canonicalPath) ?? [];
1904
+ paths.push(path);
1905
+ factPathsByCanonical.set(canonicalPath, paths);
1906
+ }
1907
+ const files = /* @__PURE__ */ new Map();
1908
+ for (const [canonicalPath, paths] of pathsByCanonical) {
1909
+ const factPaths = factPathsByCanonical.get(canonicalPath) ?? [];
1910
+ if (paths.length === 1 && factPaths.length === 1) files.set(canonicalPath, factPaths[0]);
1911
+ }
1912
+ this.files = files;
1913
+ for (const [path, file] of Object.entries(facts.files)) this.resolverBindings.set(path, new Set(file.chains.filter((chain) => chain.descriptor.terminal === "asClass" && chain.descriptor.extractable && chain.fatalError === null).map((chain) => chain.descriptor.binding)));
1914
+ }
1915
+ attribute(importerPath, request) {
1916
+ const memoKey = `${importerPath}\0${request.source}\0${request.imported}\0${request.access.kind}\0${request.access.importKind}`;
1917
+ const memoized = this.attributionMemo.get(memoKey);
1918
+ if (memoized !== void 0) return memoized;
1919
+ const attribution = this.attributeUncached(importerPath, request);
1920
+ this.attributionMemo.set(memoKey, attribution);
1921
+ return attribution;
1922
+ }
1923
+ attributeUncached(importerPath, request) {
1924
+ const importedFile = this.resolveSource(importerPath, request.source);
1925
+ if (!importedFile) return "other";
1926
+ if (this.resolveClassExport(importedFile, request.imported, /* @__PURE__ */ new Set()) === null) return "other";
1927
+ return request.access.kind === "direct" && request.access.importKind === "named" ? "resolver" : "unsupported-resolver-form";
1928
+ }
1929
+ resolveSource(importerPath, specifier) {
1930
+ const key = `${importerPath}\0${specifier}`;
1931
+ let resolved = this.resolveMemo.get(key);
1932
+ if (resolved === void 0) {
1933
+ resolved = resolveRelativeSource(importerPath, specifier, this.files);
1934
+ this.resolveMemo.set(key, resolved);
1935
+ }
1936
+ return resolved;
1937
+ }
1938
+ resolveClassExport(path, exportedName, seen) {
1939
+ const identity = `${path}\0${exportedName}`;
1940
+ if (seen.has(identity)) return null;
1941
+ seen.add(identity);
1942
+ const file = this.facts.files[path];
1943
+ const exported = file?.exports.find((candidate) => candidate.exported === exportedName);
1944
+ if (!file || !exported) return null;
1945
+ if (exported.source === null) {
1946
+ if (exported.local === null) return null;
1947
+ if (this.resolverBindings.get(path)?.has(exported.local)) return exported.local;
1948
+ const imported = file.imports.find((candidate) => candidate.local === exported.local);
1949
+ if (!imported) return null;
1950
+ const importedFile = this.resolveSource(path, imported.source);
1951
+ return importedFile ? this.resolveClassExport(importedFile, imported.imported, seen) : null;
1952
+ }
1953
+ if (exported.original === null) return null;
1954
+ const nextFile = this.resolveSource(path, exported.source);
1955
+ return nextFile ? this.resolveClassExport(nextFile, exported.original, seen) : null;
1956
+ }
1957
+ };
1958
+ /**
1959
+ * Convert raw source identities into parser-ready analysis entries once.
1960
+ *
1961
+ * Native and MDX entries establish the resolver-export index through the
1962
+ * native fact collector before any Svelte projection. Svelte calls are then
1963
+ * attributed by exact relative import/export identity and parsed once. Bare
1964
+ * package and configured-alias sources deliberately remain `other`; callers
1965
+ * must not guess those identities.
1966
+ */
1967
+ async function ingestSourceEntries(rawEntries, options) {
1968
+ const mdxAdapter = options.preprocessMdx ?? preprocessMdx;
1969
+ const svelteAdapter = options.adaptSvelte ?? adaptSvelteSource;
1970
+ const originalEntries = rawEntries.map((entry) => ({
1971
+ ...entry,
1972
+ hash: entry.hash ?? contentHash(entry.source)
1973
+ }));
1974
+ const rawOriginalPaths = new Set(originalEntries.map((entry) => entry.path));
1975
+ const analysisEntries = [];
1976
+ const ownership = {};
1977
+ const analysisOwner = /* @__PURE__ */ new Map();
1978
+ const diagnostics = [];
1979
+ const svelteEntries = [];
1980
+ const addAnalysisEntry = (originalPath, path, source, hash) => {
1981
+ analysisEntries.push({
1982
+ path,
1983
+ source,
1984
+ hash: hash ?? contentHash(source)
1985
+ });
1986
+ ownership[originalPath].analysisPaths.push(path);
1987
+ analysisOwner.set(path, originalPath);
1988
+ };
1989
+ const addAdaptedEntries = (originalPath, entries) => {
1990
+ const pendingPaths = /* @__PURE__ */ new Set();
1991
+ for (const entry of entries) {
1992
+ const conflictingOriginalPath = rawOriginalPaths.has(entry.path) ? entry.path : analysisOwner.get(entry.path) ?? (pendingPaths.has(entry.path) ? originalPath : null);
1993
+ if (conflictingOriginalPath !== null) {
1994
+ diagnostics.push({
1995
+ code: "SOURCE_ANALYSIS_PATH_COLLISION",
1996
+ message: `Generated analysis path '${entry.path}' collides with '${conflictingOriginalPath}'. Rename one of the source files so adapted analysis paths remain unique.`,
1997
+ originalPath,
1998
+ analysisPath: entry.path,
1999
+ conflictingOriginalPath
2000
+ });
2001
+ return;
2002
+ }
2003
+ pendingPaths.add(entry.path);
2004
+ }
2005
+ for (const entry of entries) addAnalysisEntry(originalPath, entry.path, entry.source);
2006
+ };
2007
+ for (const original of originalEntries) {
2008
+ ownership[original.path] = {
2009
+ originalPath: original.path,
2010
+ originalHash: original.hash,
2011
+ analysisPaths: []
2012
+ };
2013
+ const kind = extension(original.path);
2014
+ if (kind === ".svelte") {
2015
+ svelteEntries.push(original);
2016
+ continue;
2017
+ }
2018
+ if (kind !== ".mdx") {
2019
+ addAnalysisEntry(original.path, original.path, original.source, original.hash);
2020
+ continue;
2021
+ }
2022
+ const result = await mdxAdapter(original.source, original.path);
2023
+ if (result.kind === "missing-dep") {
2024
+ diagnostics.push({
2025
+ code: "SOURCE_MDX_DEPENDENCY_MISSING",
2026
+ message: "Install optional peer dependency '@mdx-js/mdx' to analyze opted-in MDX source.",
2027
+ originalPath: original.path
2028
+ });
2029
+ continue;
2030
+ }
2031
+ if (result.kind === "error" || result.source === void 0) {
2032
+ diagnostics.push({
2033
+ code: "SOURCE_MDX_PARSE_ERROR",
2034
+ message: result.error ?? "MDX preprocessing produced no source.",
2035
+ originalPath: original.path
2036
+ });
2037
+ continue;
2038
+ }
2039
+ addAdaptedEntries(original.path, [{
2040
+ path: `${original.path}.tsx`,
2041
+ source: result.source
2042
+ }]);
2043
+ }
2044
+ const facts = collectFileFacts(analysisEntries, options);
2045
+ for (const [analysisPath, file] of Object.entries(facts.files)) {
2046
+ const originalPath = analysisOwner.get(analysisPath) ?? analysisPath;
2047
+ for (const message of file.parseDiagnostics) diagnostics.push({
2048
+ code: "SOURCE_NATIVE_PARSE_ERROR",
2049
+ message,
2050
+ originalPath,
2051
+ analysisPath
2052
+ });
2053
+ }
2054
+ const resolvers = new ResolverExportIndex(facts, analysisEntries.map((entry) => entry.path));
2055
+ for (const { canonicalPath, paths } of resolvers.collisions) for (let index = 0; index < paths.length; index += 1) {
2056
+ const path = paths[index];
2057
+ const conflictingPath = paths[(index + 1) % paths.length];
2058
+ diagnostics.push({
2059
+ code: "SOURCE_RESOLVER_IDENTITY_COLLISION",
2060
+ message: `Resolver lookup paths '${path}' and '${conflictingPath}' normalize to the same private identity '${canonicalPath}'. Rename one of the source files so resolver identities remain unique.`,
2061
+ originalPath: analysisOwner.get(path) ?? path,
2062
+ canonicalPath,
2063
+ conflictingOriginalPath: analysisOwner.get(conflictingPath) ?? conflictingPath
2064
+ });
2065
+ }
2066
+ for (const original of svelteEntries) {
2067
+ const result = await svelteAdapter(original.source, original.path, { attributeResolver: (request) => resolvers.attribute(original.path, request) });
2068
+ if (result.kind === "missing-dep") {
2069
+ diagnostics.push({
2070
+ code: "SOURCE_SVELTE_DEPENDENCY_MISSING",
2071
+ message: "Install optional peer dependency 'svelte' to analyze opted-in Svelte source.",
2072
+ originalPath: original.path
2073
+ });
2074
+ continue;
2075
+ }
2076
+ if (result.kind === "error") {
2077
+ diagnostics.push(...result.diagnostics);
2078
+ continue;
2079
+ }
2080
+ addAdaptedEntries(original.path, result.entries);
2081
+ }
2082
+ return {
2083
+ originalEntries,
2084
+ analysisEntries,
2085
+ ownership,
2086
+ diagnostics
2087
+ };
2088
+ }
2089
+ /**
2090
+ * Run the native fact collector, re-extracting only changed entries when the
2091
+ * caller supplies a `factsCache`. `parseCount` keeps its meaning — parses
2092
+ * performed by THIS call — so a fully-memoized pass reports zero.
2093
+ */
2094
+ function collectFileFacts(analysisEntries, options) {
2095
+ const cache = options.factsCache;
2096
+ if (!cache) return JSON.parse(options.extractFacts(JSON.stringify(analysisEntries)));
2097
+ const pending = analysisEntries.filter((entry) => cache.get(entry.path)?.hash !== entry.hash);
2098
+ let parseCount = 0;
2099
+ if (pending.length > 0) {
2100
+ const fresh = JSON.parse(options.extractFacts(JSON.stringify(pending)));
2101
+ parseCount = fresh.parseCount;
2102
+ for (const entry of pending) {
2103
+ const facts = fresh.files[entry.path];
2104
+ if (facts) cache.set(entry.path, {
2105
+ hash: entry.hash,
2106
+ facts
2107
+ });
2108
+ else cache.delete(entry.path);
2109
+ }
2110
+ }
2111
+ const currentPaths = new Set(analysisEntries.map((entry) => entry.path));
2112
+ for (const path of [...cache.keys()]) if (!currentPaths.has(path)) cache.delete(path);
2113
+ const files = {};
2114
+ for (const entry of analysisEntries) {
2115
+ const cached = cache.get(entry.path);
2116
+ if (cached) files[entry.path] = cached.facts;
2117
+ }
2118
+ return {
2119
+ files,
2120
+ parseCount
2121
+ };
2122
+ }
2123
+ /**
2124
+ * The per-file quarantine: drop every original a diagnostic named — and the
2125
+ * analysis children it owns — so one invalid source never aborts the rest
2126
+ * of the corpus. Shared by buildStart AND every incremental path in both
2127
+ * hosts; asymmetry here is how a permanently-diagnosable file (an `.mdx`
2128
+ * with the optional peer absent, an unsupported `.svelte` shape) froze all
2129
+ * re-analysis for the life of the dev server.
2130
+ */
2131
+ function withoutInvalidOriginals(result, invalidOriginals) {
2132
+ if (invalidOriginals.size === 0) return result;
2133
+ const ownership = Object.fromEntries(Object.entries(result.ownership).filter(([originalPath]) => !invalidOriginals.has(originalPath)));
2134
+ const analysisPaths = new Set(Object.values(ownership).flatMap((owner) => owner.analysisPaths));
2135
+ return {
2136
+ ...result,
2137
+ originalEntries: result.originalEntries.filter((entry) => !invalidOriginals.has(entry.path)),
2138
+ analysisEntries: result.analysisEntries.filter((entry) => analysisPaths.has(entry.path)),
2139
+ ownership
2140
+ };
2141
+ }
2142
+ /**
2143
+ * The one source-ingestion policy point shared by every host (vite-plugin,
2144
+ * next-plugin, cli, unplugin). Hosts hold exactly their prefix, strict flag,
2145
+ * and warn sink; the capability guard, facts memo, and warn-dedupe lifecycle
2146
+ * live here so the plugins cannot fork (precedent: pkg-collection
2147
+ * divergences; see also `enforceExternalTokenContracts`).
2148
+ */
2149
+ function createSourceIngestor(host) {
2150
+ const factsCache = /* @__PURE__ */ new Map();
2151
+ /** Non-strict warn dedupe: a quarantined-but-retained original re-ingests
2152
+ * on every later corpus pass, and re-warning each save is noise. Keyed by
2153
+ * original path; cleared when that original publishes clean again. */
2154
+ const warnedByOriginal = /* @__PURE__ */ new Map();
2155
+ return {
2156
+ async ingest(entries) {
2157
+ const extractFacts = host.engineApi().extractFacts;
2158
+ if (typeof extractFacts !== "function") throw new Error(`${host.prefix} native engine does not expose extractFacts required for source adaptation`);
2159
+ return ingestSourceEntries(entries, {
2160
+ extractFacts,
2161
+ factsCache
2162
+ });
2163
+ },
2164
+ surfaceDiagnostics(diagnostics) {
2165
+ const fatal = diagnostics.filter((diagnostic) => !isAdvisorySourceDiagnostic(diagnostic));
2166
+ const invalidOriginals = new Set(fatal.map((diagnostic) => diagnostic.originalPath));
2167
+ if (diagnostics.length === 0) return invalidOriginals;
2168
+ if (host.strict() && fatal.length > 0) {
2169
+ const lines = fatal.map((diagnostic) => `${diagnostic.code} ${diagnostic.originalPath}: ${diagnostic.message}`);
2170
+ throw new Error(`${host.prefix} ${lines.join(`\n${host.prefix} `)}`);
2171
+ }
2172
+ for (const diagnostic of diagnostics) {
2173
+ const line = `${diagnostic.code} ${diagnostic.originalPath}: ${diagnostic.message}`;
2174
+ let warned = warnedByOriginal.get(diagnostic.originalPath);
2175
+ if (!warned) {
2176
+ warned = /* @__PURE__ */ new Set();
2177
+ warnedByOriginal.set(diagnostic.originalPath, warned);
2178
+ }
2179
+ if (warned.has(line)) continue;
2180
+ warned.add(line);
2181
+ host.warn(`${host.prefix} ${line}`);
2182
+ }
2183
+ return invalidOriginals;
2184
+ },
2185
+ markPublished(result) {
2186
+ for (const originalPath of Object.keys(result.ownership)) warnedByOriginal.delete(originalPath);
2187
+ }
2188
+ };
2189
+ }
2190
+ //#endregion
2191
+ //#region pipeline/asset-placeholders.ts
2192
+ /**
2193
+ * Host-side handling of `asset()` placeholders (global-styles-system):
2194
+ * `animus-asset:<specifier>` markers ride through the sandbox and the
2195
+ * emitter byte-exact; each HOST plugin substitutes them with its bundler's
2196
+ * resolved asset URL after extraction. This module owns the shared scanning
2197
+ * and replacement mechanics — resolution and strict gating stay at the
2198
+ * plugin call sites.
2199
+ */
2200
+ /** Mirrors the producer-side constant in `@animus-ui/system`'s `asset.ts`
2201
+ * (extract must not take a runtime dependency on system); the pairing is
2202
+ * pinned by a contract test in `tests/asset-placeholders.test.ts`. */
2203
+ const ASSET_PLACEHOLDER_PREFIX = "animus-asset:";
2204
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2205
+ const PREFIX_RE = escapeRegExp(ASSET_PLACEHOLDER_PREFIX);
2206
+ /**
2207
+ * Quoted `url('animus-asset:<specifier>')` form — the emitter always quotes
2208
+ * `url()` values, so a quoted match carries the FULL specifier, including
2209
+ * whitespace and parentheses (D5 pins the placeholder as specifier-verbatim,
2210
+ * so scanning fidelity is the only place such characters can be honored).
2211
+ */
2212
+ const QUOTED_PLACEHOLDER_RE = new RegExp(`(['"])${PREFIX_RE}([^'"]*?)\\1`, "g");
2213
+ /** Bare-form fallback: a placeholder up to CSS url()/quote/whitespace. */
2214
+ const BARE_PLACEHOLDER_RE = new RegExp(`${PREFIX_RE}([^'")\\s]+)`, "g");
2215
+ /** Unique asset specifiers referenced by placeholders, in appearance order. */
2216
+ function findAssetSpecifiers(css) {
2217
+ if (!css.includes("animus-asset:")) return [];
2218
+ const seen = /* @__PURE__ */ new Set();
2219
+ const remainder = css.replace(QUOTED_PLACEHOLDER_RE, (_match, _quote, specifier) => {
2220
+ seen.add(specifier);
2221
+ return "";
2222
+ });
2223
+ for (const match of remainder.matchAll(BARE_PLACEHOLDER_RE)) seen.add(match[1]);
2224
+ return [...seen];
2225
+ }
2226
+ /**
2227
+ * Replace each specifier's placeholder with its substitution. Specifiers
2228
+ * absent from the map keep their placeholder — the caller decides whether
2229
+ * that is a strict failure or a warn-and-emit-literally. A substitution may
2230
+ * itself be a bundler marker (e.g. Vite's `__VITE_ASSET__<ref>__`) that the
2231
+ * host's own asset pipeline resolves to a hashed file name later.
2232
+ *
2233
+ * Each replacement is anchored to a following delimiter (quote, `)`,
2234
+ * whitespace, or end of input) so a specifier that textually prefixes a
2235
+ * longer one can never clobber the longer placeholder; longest-first
2236
+ * ordering additionally lets the longer of two mapped specifiers claim its
2237
+ * occurrences before the shorter runs.
2238
+ */
2239
+ function substituteAssetPlaceholders(css, urlBySpecifier) {
2240
+ if (urlBySpecifier.size === 0) return css;
2241
+ if (!css.includes("animus-asset:")) return css;
2242
+ const specifiers = [...urlBySpecifier.keys()].sort((a, b) => b.length - a.length);
2243
+ let out = css;
2244
+ for (const specifier of specifiers) {
2245
+ const placeholder = new RegExp(escapeRegExp(ASSET_PLACEHOLDER_PREFIX + specifier) + String.raw`(?=['")\s]|$)`, "g");
2246
+ out = out.replace(placeholder, () => urlBySpecifier.get(specifier));
2247
+ }
2248
+ return out;
2249
+ }
2250
+ //#endregion
2251
+ //#region pipeline/resolve-asset.ts
2252
+ /**
2253
+ * Node-side asset specifier resolution shared by the host plugins (the
2254
+ * asset() contract, global-styles-system): host path aliases apply FIRST —
2255
+ * an alias such as `@fonts` works in application modules, so
2256
+ * `asset('@fonts/inter.woff2')` must resolve identically — then direct Node
2257
+ * resolution, then the package-root fallback (exports maps rarely list
2258
+ * asset subpaths). Bundler-native resolution (Vite's `this.resolve`) is
2259
+ * still preferred where available; this resolver covers the paths that have
2260
+ * no bundler hook (Next's session, Vite's dev re-analysis).
2261
+ */
2262
+ const requireByRoot = /* @__PURE__ */ new Map();
2263
+ function requireAnchoredAt(rootDir) {
2264
+ let req = requireByRoot.get(rootDir);
2265
+ if (!req) {
2266
+ req = (0, module$1.createRequire)((0, path.join)(rootDir, "package.json"));
2267
+ requireByRoot.set(rootDir, req);
2268
+ }
2269
+ return req;
2270
+ }
2271
+ function packageRootFromEntry(entry) {
2272
+ let current = (0, path.dirname)(entry);
2273
+ while (true) {
2274
+ if ((0, fs.existsSync)((0, path.join)(current, "package.json"))) return current;
2275
+ const parent = (0, path.dirname)(current);
2276
+ if (parent === current) return null;
2277
+ current = parent;
2278
+ }
2279
+ }
2280
+ const aliasTableCache = /* @__PURE__ */ new Map();
2281
+ function parseAliasTable(pathAliasesJson) {
2282
+ const cached = aliasTableCache.get(pathAliasesJson);
2283
+ if (cached) return cached;
2284
+ let aliases;
2285
+ try {
2286
+ aliases = JSON.parse(pathAliasesJson).aliases ?? [];
2287
+ } catch {
2288
+ aliases = [];
2289
+ }
2290
+ aliasTableCache.set(pathAliasesJson, aliases);
2291
+ return aliases;
2292
+ }
2293
+ /**
2294
+ * Map a specifier through the harvested host alias table (the same
2295
+ * `pathAliasesJson` wire the engine consumes — entries pre-sorted longest
2296
+ * pattern first by `buildPathAliasesJson`). Returns an absolute path to an
2297
+ * EXISTING file, or null when no alias claims the specifier.
2298
+ */
2299
+ function resolveThroughPathAliases(specifier, rootDir, pathAliasesJson) {
2300
+ if (!pathAliasesJson) return null;
2301
+ const aliases = parseAliasTable(pathAliasesJson);
2302
+ for (const alias of aliases) {
2303
+ let mapped = null;
2304
+ if (alias.type === "exact") {
2305
+ if (alias.pattern === specifier) mapped = alias.replacement;
2306
+ } else if (specifier.startsWith(alias.pattern)) mapped = alias.replacement + specifier.slice(alias.pattern.length);
2307
+ if (mapped === null) continue;
2308
+ const absolute = (0, path.isAbsolute)(mapped) ? mapped : (0, path.join)(rootDir, mapped);
2309
+ if ((0, fs.existsSync)(absolute)) return absolute;
2310
+ }
2311
+ return null;
2312
+ }
2313
+ /**
2314
+ * Resolve an asset specifier to an absolute file: host aliases, then direct
2315
+ * Node resolution anchored at `rootDir`, then the package-root fallback.
2316
+ * Returns null when nothing matches — strict gating stays at the caller.
2317
+ */
2318
+ function resolveAssetFile(specifier, rootDir, pathAliasesJson) {
2319
+ const aliased = resolveThroughPathAliases(specifier, rootDir, pathAliasesJson);
2320
+ if (aliased) return aliased;
2321
+ const requireFromRoot = requireAnchoredAt(rootDir);
2322
+ try {
2323
+ return requireFromRoot.resolve(specifier);
2324
+ } catch {}
2325
+ const segments = specifier.split("/");
2326
+ const packageName = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
2327
+ const subpath = specifier.slice(packageName.length + 1);
2328
+ if (!subpath) return null;
2329
+ for (const modulesDir of requireFromRoot.resolve.paths(packageName) ?? []) {
2330
+ const packageRoot = (0, path.join)(modulesDir, packageName);
2331
+ if (!(0, fs.existsSync)((0, path.join)(packageRoot, "package.json"))) continue;
2332
+ const candidate = (0, path.join)(packageRoot, subpath);
2333
+ if ((0, fs.existsSync)(candidate)) return candidate;
2334
+ }
2335
+ try {
2336
+ const packageRoot = packageRootFromEntry(requireFromRoot.resolve(packageName));
2337
+ if (!packageRoot) return null;
2338
+ const candidate = (0, path.join)(packageRoot, subpath);
2339
+ return (0, fs.existsSync)(candidate) ? candidate : null;
2340
+ } catch {
2341
+ return null;
2342
+ }
2343
+ }
2344
+ //#endregion
2345
+ //#region pipeline/correlate-external-tokens.ts
2346
+ /**
2347
+ * Index the loader-captured theme manifests by owning specifier. Module paths
2348
+ * are canonical absolute paths (symlinks resolved), so each package dir is
2349
+ * realpath'd before prefix-matching; a module outside every known package dir
2350
+ * (typically the consumer's own theme) contributes nothing.
2351
+ */
2352
+ function buildSourceTokenIndex(opts) {
2353
+ const index = /* @__PURE__ */ new Map();
2354
+ if (!opts.sourceThemeManifestsJson) return index;
2355
+ let manifests;
2356
+ try {
2357
+ manifests = JSON.parse(opts.sourceThemeManifestsJson);
2358
+ } catch {
2359
+ return index;
2360
+ }
2361
+ const realDirOwners = [];
2362
+ const addOwnerDir = (dir, specifier) => {
2363
+ if (!realDirOwners.some((entry) => entry.dir === dir)) realDirOwners.push({
2364
+ dir,
2365
+ specifier
2366
+ });
2367
+ };
2368
+ for (const [dir, specifier] of Object.entries(opts.dirOwners)) {
2369
+ let real = dir;
2370
+ try {
2371
+ real = (0, fs.realpathSync)(dir);
2372
+ } catch {}
2373
+ addOwnerDir(real, specifier);
2374
+ let packageRoot = real;
2375
+ while (packageRoot !== (0, path.dirname)(packageRoot) && !(0, fs.existsSync)((0, path.join)(packageRoot, "package.json"))) packageRoot = (0, path.dirname)(packageRoot);
2376
+ if ((0, fs.existsSync)((0, path.join)(packageRoot, "package.json"))) addOwnerDir(packageRoot, specifier);
2377
+ }
2378
+ for (const [modulePath, exports] of Object.entries(manifests)) {
2379
+ const owner = realDirOwners.find(({ dir }) => isPathWithinRoot(dir, modulePath));
2380
+ if (!owner) continue;
2381
+ let tokens = index.get(owner.specifier);
2382
+ if (!tokens) {
2383
+ tokens = /* @__PURE__ */ new Set();
2384
+ index.set(owner.specifier, tokens);
2385
+ }
2386
+ for (const paths of Object.values(exports)) for (const token of paths) tokens.add(token);
2387
+ }
2388
+ return index;
2389
+ }
2390
+ /**
2391
+ * The correlation join. Returns one teaching-error message per distinct
2392
+ * (component, token, specifier) whose file belongs to a discovered source AND
2393
+ * whose token that source's manifest defines. The messages follow the
2394
+ * standard severity routing at the CALLER (throw under `strict`, warn
2395
+ * otherwise) — this join never reports on its own.
2396
+ */
2397
+ function correlateExternalTokenDiagnostics(opts) {
2398
+ const messages = [];
2399
+ const seen = /* @__PURE__ */ new Set();
2400
+ for (const diagnostic of opts.diagnostics ?? []) {
2401
+ if (diagnostic.kind !== "external-token-candidate" || !diagnostic.token) continue;
2402
+ const specifier = opts.fileOwners[diagnostic.file];
2403
+ if (!specifier) continue;
2404
+ if (!opts.sourceTokens.get(specifier)?.has(diagnostic.token)) continue;
2405
+ const key = `${diagnostic.component}\u0000${diagnostic.token}\u0000${specifier}`;
2406
+ if (seen.has(key)) continue;
2407
+ seen.add(key);
2408
+ messages.push(`${diagnostic.component} (from '${specifier}') references token '${diagnostic.token}', which the consumer theme does not define — inherit the source's tokens with createTheme().extend(...) using the tokens (or bundle) export of '${specifier}'`);
2409
+ }
2410
+ return messages;
2411
+ }
2412
+ const indexCache = /* @__PURE__ */ new WeakMap();
2413
+ /**
2414
+ * The complete cross-source token-contract gate both plugins share
2415
+ * (extraction-diagnostics): index the loader-captured source manifests,
2416
+ * join them against the engine's candidates, and route the resulting
2417
+ * teaching errors — throw under `strict`, warn otherwise. One entry point
2418
+ * so the two hosts cannot drift on wiring or severity semantics.
2419
+ */
2420
+ function enforceExternalTokenContracts(opts) {
2421
+ const manifestsJson = opts.sourceThemeManifestsJson ?? "";
2422
+ const cached = indexCache.get(opts.dirOwners);
2423
+ let sourceTokens;
2424
+ if (cached && cached.manifestsJson === manifestsJson) sourceTokens = cached.index;
2425
+ else {
2426
+ sourceTokens = buildSourceTokenIndex({
2427
+ sourceThemeManifestsJson: opts.sourceThemeManifestsJson,
2428
+ dirOwners: opts.dirOwners
2429
+ });
2430
+ indexCache.set(opts.dirOwners, {
2431
+ manifestsJson,
2432
+ index: sourceTokens
2433
+ });
2434
+ }
2435
+ const messages = correlateExternalTokenDiagnostics({
2436
+ diagnostics: opts.diagnostics,
2437
+ fileOwners: opts.fileOwners,
2438
+ sourceTokens
2439
+ });
2440
+ if (messages.length === 0) return;
2441
+ if (opts.strict) throw new Error(`${opts.prefix} ${messages.join("\n")}`);
2442
+ for (const message of messages) opts.warn(message);
2443
+ }
2444
+ //#endregion
2445
+ //#region pipeline/path-aliases.ts
2446
+ /**
2447
+ * Normalize alias pairs: strip a `rootDir` prefix from targets, classify
2448
+ * exact (file) vs prefix (directory) matches, force trailing slashes on
2449
+ * prefix entries, and sort longest pattern first for correct matching
2450
+ * priority. Returns null when no entries survive.
2451
+ */
2452
+ function buildPathAliasesJson(pairs, rootDir) {
2453
+ const entries = [];
2454
+ for (const { pattern, target, kind } of pairs) {
2455
+ const replacement = target.startsWith(rootDir) ? target.slice(rootDir.length + 1) : target;
2456
+ if (kind ? kind === "exact" : /\.\w+$/.test(replacement)) entries.push({
2457
+ pattern,
2458
+ replacement,
2459
+ type: "exact"
2460
+ });
2461
+ else entries.push({
2462
+ pattern: pattern.endsWith("/") ? pattern : pattern + "/",
2463
+ replacement: replacement.endsWith("/") ? replacement : replacement + "/",
2464
+ type: "prefix"
2465
+ });
2466
+ }
2467
+ entries.sort((a, b) => b.pattern.length - a.pattern.length);
2468
+ if (entries.length === 0) return null;
2469
+ return {
2470
+ json: JSON.stringify({ aliases: entries }),
2471
+ count: entries.length
2472
+ };
2473
+ }
2474
+ //#endregion
2475
+ //#region pipeline/post-process-css.ts
2476
+ /**
2477
+ * CSS post-processing (spec: css-post-processing) — Lightning CSS
2478
+ * autoprefixing, syntax lowering, and optional minification against
2479
+ * browserslist targets. The single implementation consumed by both the
2480
+ * Vite plugin (virtual-module serve time) and the Next.js plugin
2481
+ * (ExtractionSession artifact emission).
2482
+ */
2483
+ /**
2484
+ * Resolve browser targets for Lightning CSS.
2485
+ * Priority: explicit config → project browserslist → 'defaults' fallback.
2486
+ */
2487
+ function resolveLightningTargets(explicitTargets, rootDir) {
2488
+ let queries;
2489
+ if (explicitTargets) queries = Array.isArray(explicitTargets) ? explicitTargets : [explicitTargets];
2490
+ else {
2491
+ const detected = (0, browserslist.default)(void 0, { path: rootDir });
2492
+ queries = detected.length > 0 ? detected : (0, browserslist.default)("defaults");
2493
+ }
2494
+ return (0, lightningcss.browserslistToTargets)(Array.isArray(queries) && typeof queries[0] === "string" && queries[0].includes(" ") ? (0, browserslist.default)(queries) : queries);
2495
+ }
2496
+ /**
2497
+ * Post-process CSS with Lightning CSS: autoprefixing + optional minification.
2498
+ * On failure, returns the original CSS and logs a warning.
2499
+ */
2500
+ function postProcessCss(css, opts) {
2501
+ if (!css) return css;
2502
+ try {
2503
+ return (0, lightningcss.transform)({
2504
+ filename: "animus-extracted.css",
2505
+ code: Buffer.from(css),
2506
+ minify: opts.minify,
2507
+ targets: opts.targets
2508
+ }).code.toString();
2509
+ } catch (e) {
2510
+ const msg = e instanceof Error ? e.message : String(e);
2511
+ (opts.warnFn ?? console.warn)(`[animus] Lightning CSS post-processing failed: ${msg}`);
2512
+ return css;
2513
+ }
2514
+ }
2515
+ //#endregion
2516
+ //#region pipeline/manifest-diagnostics.ts
2517
+ /** Stable code for selector forms with no substitutable subject.
2518
+ * Mirrors the Rust constant in `extract-v2/src/eval.rs`. */
2519
+ const SELECTOR_UNSUPPORTED_SUBJECT = "animus.selector.unsupported-subject";
2520
+ /** Unresolved-parent chain-drop message (mirrors the Rust diagnostic in
2521
+ * `extract-v2` — the ONE encoding of this message shape; consumers match
2522
+ * through the helpers below, never their own regex copies). */
2523
+ const UNRESOLVED_PARENT_RE = /chain dropped: could not resolve parent component '([^']+)'/;
2524
+ /** True when the diagnostic reports a chain dropped for an unresolved
2525
+ * parent component. */
2526
+ function isUnresolvedParentDrop(diagnostic) {
2527
+ return typeof diagnostic?.message === "string" && UNRESOLVED_PARENT_RE.test(diagnostic.message);
2528
+ }
2529
+ /** The parent binding named by an unresolved-parent drop, or null when the
2530
+ * diagnostic is not one. */
2531
+ function unresolvedParentName(diagnostic) {
2532
+ if (typeof diagnostic?.message !== "string") return null;
2533
+ return UNRESOLVED_PARENT_RE.exec(diagnostic.message)?.[1] ?? null;
2534
+ }
2535
+ /** True when the selector string carries at least one substitutable `&`
2536
+ * subject outside quoted text (mirrors the Rust `selector_subject` walk —
2537
+ * ancestor, leading, and repeated subjects all count; a `&` inside a
2538
+ * quoted attribute value does not). */
2539
+ function hasSelectorSubject(value) {
2540
+ let quote = null;
2541
+ let escaped = false;
2542
+ for (const c of value) {
2543
+ if (escaped) {
2544
+ escaped = false;
2545
+ continue;
2546
+ }
2547
+ if (c === "\\") {
2548
+ escaped = true;
2549
+ continue;
2550
+ }
2551
+ if (quote !== null) {
2552
+ if (c === quote) quote = null;
2553
+ } else if (c === "\"" || c === "'") quote = c;
2554
+ else if (c === "&") return true;
2555
+ }
2556
+ return false;
2557
+ }
2558
+ /**
2559
+ * Synthesize coded diagnostics for registered selector-alias values that
2560
+ * look selector-shaped (`&` present) but carry no substitutable subject —
2561
+ * every `&` sits inside quoted text, so there is nothing to anchor the
2562
+ * class to. Ancestor-prefixed and repeated subjects are supported and pass
2563
+ * validation. The system-config boundary is where these must fail loud
2564
+ * (alias values never reach the evaluator's key guard).
2565
+ */
2566
+ function collectSelectorAliasDiagnostics(selectorAliasesJson) {
2567
+ if (!selectorAliasesJson) return [];
2568
+ let aliases;
2569
+ try {
2570
+ aliases = JSON.parse(selectorAliasesJson);
2571
+ } catch {
2572
+ return [];
2573
+ }
2574
+ const diagnostics = [];
2575
+ for (const [name, value] of Object.entries(aliases)) {
2576
+ if (typeof value !== "string") continue;
2577
+ if (value.includes("&") && !hasSelectorSubject(value)) diagnostics.push({
2578
+ file: "system",
2579
+ component: name,
2580
+ kind: "warn",
2581
+ message: `selector alias '${name}' value '${value}' has no substitutable '&' subject outside quoted text (${SELECTOR_UNSUPPORTED_SUBJECT})`,
2582
+ code: SELECTOR_UNSUPPORTED_SUBJECT,
2583
+ severity: "error"
2584
+ });
2585
+ }
2586
+ return diagnostics;
2587
+ }
2588
+ /**
2589
+ * Surface extraction-manifest diagnostics through a plugin's warn channel.
2590
+ *
2591
+ * Single authoritative copy for both extraction plugins — and the single
2592
+ * strict-escalation policy point: error-severity diagnostics throw one
2593
+ * Error naming every offender when `policy.strict`, and print as warnings
2594
+ * otherwise. Surfaces `bail` (component not extracted), `skip` (component
2595
+ * skipped), and `warn` kinds; unknown kinds stay silent. Printed lines
2596
+ * include the diagnostic code when the message doesn't already carry it.
2597
+ */
2598
+ function surfaceManifestDiagnostics(manifest, warn, policy = {}) {
2599
+ const errors = [];
2600
+ const diagnostics = policy.prepend?.length ? [...policy.prepend, ...manifest.diagnostics ?? []] : manifest.diagnostics ?? [];
2601
+ for (const diagnostic of diagnostics) {
2602
+ let line = null;
2603
+ if (diagnostic.kind === "bail") line = `⚠ ${diagnostic.component} not extracted: ${diagnostic.message}`;
2604
+ else if (diagnostic.kind === "skip") line = `⚠ ${diagnostic.component}: skipped ${diagnostic.message}`;
2605
+ else if (diagnostic.kind === "warn") line = `⚠ ${diagnostic.file}: ${diagnostic.component}: ${diagnostic.message}`;
2606
+ if (line === null) continue;
2607
+ if (diagnostic.code && !diagnostic.message.includes(diagnostic.code)) line += ` [${diagnostic.code}]`;
2608
+ if (policy.strict && diagnostic.severity === "error") {
2609
+ errors.push(`${diagnostic.code ?? "error"} — ${diagnostic.component}: ${diagnostic.message}`);
2610
+ continue;
2611
+ }
2612
+ warn(line);
2613
+ }
2614
+ if (errors.length > 0) throw new Error(`[animus] strict: ${errors.length} error diagnostic(s):\n${errors.join("\n")}`);
2615
+ }
2616
+ //#endregion
2617
+ //#region pipeline/unit-fallback.ts
2618
+ /**
2619
+ * Append `px` to bare numeric values in CSS declarations for properties
2620
+ * that expect length units. Unitless properties are preserved as-is.
2621
+ * Numbers inside CSS function calls (cubic-bezier, rgb, calc, etc.) are skipped.
2622
+ */
2623
+ function applyUnitFallback(css) {
2624
+ return css.replace(/([a-z-]+)\s*:\s*([^;{}]+);/g, (match, prop, value) => {
2625
+ if ((0, _animus_ui_properties.isUnitlessProperty)(prop)) return match;
2626
+ let depth = 0;
2627
+ let fixed = "";
2628
+ let i = 0;
2629
+ while (i < value.length) if (value[i] === "(") {
2630
+ depth++;
2631
+ fixed += value[i];
2632
+ i++;
2633
+ } else if (value[i] === ")") {
2634
+ depth--;
2635
+ fixed += value[i];
2636
+ i++;
2637
+ } else if (depth > 0) {
2638
+ fixed += value[i];
2639
+ i++;
2640
+ } else {
2641
+ const numMatch = value.slice(i).match(/^(-?\d+\.?\d*)/);
2642
+ if (numMatch) {
2643
+ const num = numMatch[1];
2644
+ const after = value[i + num.length];
2645
+ if (after && /[a-z%]/i.test(after)) fixed += num;
2646
+ else fixed += num + "px";
2647
+ i += num.length;
2648
+ } else {
2649
+ fixed += value[i];
2650
+ i++;
2651
+ }
2652
+ }
2653
+ return fixed !== value ? `${prop}:${fixed};` : match;
2654
+ });
2655
+ }
2656
+ //#endregion
2657
+ //#region pipeline/run-analysis.ts
2658
+ /**
2659
+ * Build the named `analyzeProject` input set from analysis options. Also
2660
+ * the persistence shape for `.animus/analysis-inputs.json` — an isolated
2661
+ * process can replay the analysis from exactly this object
2662
+ * (spec: next-turbopack-integration).
2663
+ */
2664
+ function buildAnalysisInputs(opts) {
2665
+ return {
2666
+ filesJson: JSON.stringify(opts.fileEntries),
2667
+ scalesJson: opts.system.scalesJson,
2668
+ variableMapJson: opts.system.variableMapJson,
2669
+ contextualVarsJson: opts.system.contextualVarsJson,
2670
+ propConfigJson: opts.system.propConfigJson,
2671
+ groupRegistryJson: opts.system.groupRegistryJson,
2672
+ packageResolutionJson: JSON.stringify(opts.packageMap),
2673
+ devMode: opts.devMode,
2674
+ emitterConfigJson: JSON.stringify({
2675
+ runtime_import: opts.emitter.runtimeImport,
2676
+ css_module_id: opts.emitter.cssModuleId,
2677
+ ...opts.emitter.systemPropsModuleId ? { system_props_module_id: opts.emitter.systemPropsModuleId } : {}
2678
+ }),
2679
+ selectorAliasesJson: opts.system.selectorAliasesJson,
2680
+ globalStyleBlocksJson: opts.system.globalStyleBlocksJson,
2681
+ pathAliasesJson: opts.pathAliasesJson,
2682
+ keyframesJson: opts.system.keyframesJson,
2683
+ staticCssJson: opts.staticCssJson ?? null,
2684
+ conditionAliasesJson: opts.system.conditionAliasesJson ?? null,
2685
+ transformSourcesJson: opts.system.transformSourcesJson ?? null,
2686
+ externalDirsJson: opts.externalDirs?.length && hasSourceThemeManifests(opts.system) ? JSON.stringify(opts.externalDirs) : null
2687
+ };
2688
+ }
2689
+ /** Whether the loader captured at least one source built-theme manifest. */
2690
+ function hasSourceThemeManifests(system) {
2691
+ const json = system.sourceThemeManifestsJson;
2692
+ return typeof json === "string" && json.length > 0 && json !== "{}";
2693
+ }
2694
+ /**
2695
+ * The one analysis invocation both plugins share: build the emitter
2696
+ * config, serialize inputs, call the NAPI `analyzeProject`, parse the
2697
+ * manifest, surface its diagnostics, and resolve the CSS outputs.
2698
+ *
2699
+ * Error handling stays at the call site (strict-mode throw vs warn).
2700
+ */
2701
+ function runProjectAnalysis(engineApi, opts) {
2702
+ const { analyzeProject } = engineApi();
2703
+ let t = performance.now();
2704
+ const inputs = buildAnalysisInputs(opts);
2705
+ const serializeMs = Math.round(performance.now() - t);
2706
+ t = performance.now();
2707
+ const manifestJson = analyzeProject(...buildAnalyzeProjectArgs(inputs));
2708
+ const extractMs = Math.round(performance.now() - t);
2709
+ t = performance.now();
2710
+ const manifest = JSON.parse(manifestJson);
2711
+ surfaceManifestDiagnostics(manifest, opts.warn, {
2712
+ strict: opts.strict,
2713
+ prepend: [...collectSelectorAliasDiagnostics(opts.system.selectorAliasesJson), ...opts.extraDiagnostics ?? []]
2714
+ });
2715
+ const parseMs = Math.round(performance.now() - t);
2716
+ return {
2717
+ manifest,
2718
+ manifestJson,
2719
+ globalCss: manifest?.sheets?.global || "",
2720
+ componentCss: applyUnitFallback(manifest?.css || ""),
2721
+ inputs,
2722
+ timings: {
2723
+ serializeMs,
2724
+ extractMs,
2725
+ parseMs
2726
+ }
2727
+ };
2728
+ }
2729
+ /**
2730
+ * Clear the engine's per-file analysis cache so stale results from a prior
2731
+ * build never bleed into a fresh run. Tolerates engines without the
2732
+ * capability (older builds) — the probe is benign.
2733
+ */
2734
+ function clearEngineCache(engineApi) {
2735
+ try {
2736
+ const { clearAnalysisCache } = engineApi();
2737
+ clearAnalysisCache();
2738
+ } catch {}
2739
+ }
2740
+ //#endregion
2741
+ //#region pipeline/static-css.ts
2742
+ /** Key-sorted stringify so semantically identical configs serialize
2743
+ * identically (stable analysis-inputs hashing). */
2744
+ function stableStringify(value) {
2745
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
2746
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
2747
+ return JSON.stringify(value);
2748
+ }
2749
+ /** Serialize a staticCss option for the engine; null when absent/empty. */
2750
+ function serializeStaticCss(config) {
2751
+ if (!config) return null;
2752
+ const json = stableStringify(config);
2753
+ return json === "{}" ? null : json;
2754
+ }
2755
+ //#endregion
2756
+ //#region pipeline/prefix.ts
2757
+ /**
2758
+ * Apply namespace prefix to a variable map, CSS variable declarations, and theme JSON.
2759
+ *
2760
+ * Variable map: `{ "colors.ember": "--color-ember" }` -> `{ "colors.ember": "--prefix-color-ember" }`
2761
+ * Variable CSS: `--color-ember: #FF2800` -> `--prefix-color-ember: #FF2800`
2762
+ * `var(--color-ember)` -> `var(--prefix-color-ember)`
2763
+ * Theme JSON: `{ "colors.ember": "var(--color-ember)" }` -> `{ "colors.ember": "var(--prefix-color-ember)" }`
2764
+ */
2765
+ function applyPrefix(prefix, variableMapJson, variableCss, themeJson, contextualVarsJson) {
2766
+ if (!prefix) return {
2767
+ variableMapJson,
2768
+ variableCss,
2769
+ themeJson,
2770
+ contextualVarsJson
2771
+ };
2772
+ const varRefRe = /var\(--([a-zA-Z][\w-]*)\)/g;
2773
+ const map = JSON.parse(variableMapJson);
2774
+ const prefixed = {};
2775
+ for (const [key, varName] of Object.entries(map)) prefixed[key] = varName.startsWith("--") ? `--${prefix}-${varName.slice(2)}` : varName;
2776
+ let css = variableCss;
2777
+ css = css.replace(/--([a-zA-Z][\w-]*)\s*:/g, `--${prefix}-$1:`);
2778
+ css = css.replace(varRefRe, `var(--${prefix}-$1)`);
2779
+ const result = {
2780
+ variableMapJson: JSON.stringify(prefixed),
2781
+ variableCss: css
2782
+ };
2783
+ if (themeJson) result.themeJson = themeJson.replace(varRefRe, `var(--${prefix}-$1)`);
2784
+ if (contextualVarsJson) {
2785
+ const ctxVars = JSON.parse(contextualVarsJson);
2786
+ const prefixedCtx = {};
2787
+ for (const [scale, names] of Object.entries(ctxVars)) prefixedCtx[scale] = names.map((name) => `${prefix}-${name}`);
2788
+ result.contextualVarsJson = JSON.stringify(prefixedCtx);
2789
+ }
2790
+ return result;
2791
+ }
2792
+ //#endregion
2793
+ //#region pipeline/system-config.ts
2794
+ /**
2795
+ * Load a SystemInstance via the engine's `loadSystemModule` and normalize
2796
+ * it into a SystemConfig. When `prefix` is set, CSS variable names in the
2797
+ * variable map/css (and theme + contextual vars when affected) are
2798
+ * namespaced via the shared `applyPrefix`.
2799
+ *
2800
+ * Error handling stays at the call site — the Vite plugin warns (or throws
2801
+ * in strict mode) and keeps its previous config, the Next plugin lets the
2802
+ * failure propagate.
2803
+ */
2804
+ function loadSystemConfig(engineApi, opts) {
2805
+ const { loadSystemModule } = engineApi();
2806
+ const config = loadSystemModule(opts.systemPath, opts.rootDir);
2807
+ let scalesJson = config.scalesJson;
2808
+ let variableMapJson = config.variableMapJson;
2809
+ let variableCss = config.variableCss;
2810
+ let contextualVarsJson = config.contextualVarsJson || null;
2811
+ if (opts.prefix) {
2812
+ const prefixed = applyPrefix(opts.prefix, variableMapJson, variableCss, scalesJson, contextualVarsJson || void 0);
2813
+ variableMapJson = prefixed.variableMapJson;
2814
+ variableCss = prefixed.variableCss;
2815
+ if (prefixed.themeJson) scalesJson = prefixed.themeJson;
2816
+ if (prefixed.contextualVarsJson) contextualVarsJson = prefixed.contextualVarsJson;
2817
+ }
2818
+ return {
2819
+ propConfigJson: config.propConfig,
2820
+ groupRegistryJson: config.groupRegistry,
2821
+ scalesJson,
2822
+ variableMapJson,
2823
+ variableCss,
2824
+ contextualVarsJson,
2825
+ selectorAliasesJson: config.selectorAliases || null,
2826
+ conditionAliasesJson: config.conditionAliases || null,
2827
+ transformSourcesJson: config.transformSources || null,
2828
+ globalStyleBlocksJson: config.globalStyleBlocks || null,
2829
+ keyframesJson: config.keyframesBlocks || null,
2830
+ dependencies: config.dependencies ?? [],
2831
+ sourceThemeManifestsJson: config.sourceThemeManifests || null
2832
+ };
2833
+ }
2834
+ //#endregion
2835
+ //#region pipeline/structural-self-check.ts
2836
+ /**
2837
+ * Structural self-check over an emitted extraction result — the affirmative
2838
+ * post-condition against silent-empty output (openspec:
2839
+ * standalone-extraction-cli, "Silent-empty success is impossible").
2840
+ *
2841
+ * One shared implementation for every driver: the Vite plugin's `verify`
2842
+ * option and the standalone CLI (default-on) both call this; the caller
2843
+ * owns the failure POLICY (warn vs throw vs exit code), never the checks.
2844
+ */
2845
+ /** Run every structural check; returns human-readable failure lines
2846
+ * (empty = pass). */
2847
+ function runStructuralSelfCheck(input) {
2848
+ const failures = [];
2849
+ if (input.componentCount === 0) failures.push("No component CSS produced — check the system file and its includes list");
2850
+ else if (input.assembledCss !== void 0 ? !/@layer\s+anm-base\s*\{/.test(input.assembledCss) : input.componentCss.trim().length === 0) failures.push(`${input.componentCount} component(s) discovered but the emitted component CSS is empty`);
2851
+ for (const { specifier, outcome } of input.externalOutcomes ?? []) if (outcome === "empty") failures.push(`include '${specifier}' resolved but discovered no component sources`);
2852
+ else if (outcome === "unresolvable") failures.push(`include '${specifier}' could not be resolved`);
2853
+ if (!input.variableCss.includes(":root")) failures.push("No :root variable block found in variable CSS");
2854
+ if ((input.assembledCss ?? `${input.variableCss}\n${input.globalCss}\n${input.componentCss}`).includes("__TRANSFORM__")) failures.push("Unresolved __TRANSFORM__ placeholders found in CSS output");
2855
+ if (input.componentCount > 0 && (input.componentCss.length > 0 || input.assembledCss !== void 0)) {
2856
+ const assembled = input.assembledCss ?? assembleStylesheet({
2857
+ layers: input.layers,
2858
+ variableCss: input.variableCss,
2859
+ globalCss: input.globalCss,
2860
+ componentCss: input.componentCss
2861
+ });
2862
+ const baseIdx = assembled.search(/@layer\s+anm-base\s*\{/);
2863
+ const variantsIdx = assembled.search(/@layer\s+anm-variants\s*\{/);
2864
+ if (baseIdx !== -1 && variantsIdx !== -1 && baseIdx >= variantsIdx) failures.push(`CSS layer ordering violated — @layer anm-base (offset ${baseIdx}) must precede @layer anm-variants (offset ${variantsIdx})`);
2865
+ }
2866
+ return failures;
2867
+ }
2868
+ //#endregion
2869
+ //#region pipeline/dynamic-prop-config.ts
2870
+ function buildDynamicPropConfig(dynamicProps) {
2871
+ const configEntries = {};
2872
+ for (const [propName, meta] of Object.entries(dynamicProps)) {
2873
+ if (!meta.varName || !meta.slotClass) throw new Error(`buildDynamicPropConfig: dynamic prop '${propName}' carries no slot metadata — expected varName and slotClass, got keys [${Object.keys(meta).join(", ")}].`);
2874
+ const entry = {
2875
+ varName: meta.varName,
2876
+ slotClass: meta.slotClass
2877
+ };
2878
+ if (meta.property) entry.property = meta.property;
2879
+ if (meta.properties && meta.properties.length > 0) entry.properties = meta.properties;
2880
+ if (meta.transformName) entry.transformName = meta.transformName;
2881
+ if (meta.scaleValues && Object.keys(meta.scaleValues).length > 0) entry.scaleValues = meta.scaleValues;
2882
+ configEntries[propName] = entry;
2883
+ }
2884
+ return configEntries;
2885
+ }
2886
+ //#endregion
2887
+ //#region pipeline/system-props-module.ts
2888
+ /**
2889
+ * Build the source of the runtime system-props module — served as
2890
+ * `virtual:animus/system-props` by the Vite plugin and written as the
2891
+ * session-scoped `system-props.js` artifact by the extraction session
2892
+ * (`@animus-ui/extract/session`). One generator so the runtimes can never
2893
+ * drift.
2894
+ *
2895
+ * Runtime transform functions for dynamic props are not yet supported
2896
+ * (transforms are resolved at extraction time via boa_engine in Rust), so
2897
+ * `transforms` defaults to an empty object literal.
2898
+ *
2899
+ * `dynamicPropConfig` entries carry the CSS property the slot class declares
2900
+ * — the runtime's unit-fallback decision. Their field order and omission
2901
+ * rules belong to buildDynamicPropConfig.
2902
+ */
2903
+ function buildSystemPropsModule(opts) {
2904
+ const dynamicPropConfig = buildDynamicPropConfig(opts.dynamicProps);
2905
+ return `export const systemPropMap = ${opts.systemPropMapJson};\nexport const systemPropGroups = ${opts.groupRegistryJson};\nexport const dynamicPropConfig = ${JSON.stringify(dynamicPropConfig)};\nexport const transforms = ${opts.transformsSource ?? "{}"};\n`;
2906
+ }
2907
+ //#endregion
2908
+ //#region pipeline/timing-waterfall.ts
2909
+ /**
2910
+ * Rust-side timing phases as reported in `manifest.timing`, in waterfall
2911
+ * order, with their display labels. Mirrors the timing struct in the
2912
+ * extract-v2 crate — a renamed or added Rust phase is updated here once,
2913
+ * not per plugin.
2914
+ */
2915
+ const RUST_TIMING_PHASES = [
2916
+ ["parseAndWalk", "parse+walk"],
2917
+ ["importResolution", "imports"],
2918
+ ["extensionProvenance", "provenance"],
2919
+ ["topologicalSort", "topo-sort"],
2920
+ ["chainEvaluation", "chains"],
2921
+ ["jsxScanning", "jsx-scan"],
2922
+ ["systemPropAggregation", "sys-props"],
2923
+ ["usageLedger", "usage"],
2924
+ ["reconciliation", "reconcile"],
2925
+ ["cssGeneration", "css-gen"],
2926
+ ["manifestSerialization", "serialize"]
2927
+ ];
2928
+ /**
2929
+ * Format the Rust timing waterfall as log lines. `indent` and `labelWidth`
2930
+ * let each plugin keep its established column layout; the phase table and
2931
+ * the `(N files, M cached)` suffix are shared.
2932
+ */
2933
+ function formatRustTimingWaterfall(timing, opts) {
2934
+ const lines = [];
2935
+ for (const [key, label] of RUST_TIMING_PHASES) {
2936
+ const ms = timing[key] ?? 0;
2937
+ const pad = " ".repeat(Math.max(0, opts.labelWidth - label.length));
2938
+ const extra = key === "parseAndWalk" ? ` (${timing.fileCount ?? 0} files, ${timing.cacheHits ?? 0} cached)` : "";
2939
+ lines.push(`${opts.indent}${label}${pad}${String(ms).padStart(5)}ms${extra}`);
2940
+ }
2941
+ return lines;
2942
+ }
2943
+ //#endregion
2944
+ //#region pipeline/tsconfig-paths.ts
2945
+ /**
2946
+ * tsconfig `paths` → alias pairs for the Rust `pathAliasesJson` contract
2947
+ * (via `buildPathAliasesJson`). Used by drivers that cannot harvest aliases
2948
+ * from a live bundler config — Turbopack exposes none.
2949
+ *
2950
+ * Semantics (deliberately the TypeScript subset that matters for import
2951
+ * provenance): JSONC tolerated (comments + trailing commas); `extends`
2952
+ * chains followed (string or array; missing parents and cycles skipped);
2953
+ * the NEAREST config declaring `paths` wins wholesale (TS replaces the
2954
+ * object, never merges); targets resolve against the nearest `baseUrl`
2955
+ * (resolved from its declaring config's directory) or, absent one, the
2956
+ * directory of the config declaring `paths`; first target per pattern.
2957
+ * `x/*` patterns become prefix pairs, non-wildcard patterns exact pairs,
2958
+ * bare `*` catch-alls and mid-pattern wildcards are skipped.
2959
+ */
2960
+ /** String-aware JSONC → JSON: strips // and block comments + trailing commas. */
2961
+ function stripJsonc(text) {
2962
+ let out = "";
2963
+ let inString = false;
2964
+ let inLine = false;
2965
+ let inBlock = false;
2966
+ for (let i = 0; i < text.length; i++) {
2967
+ const ch = text[i];
2968
+ const next = text[i + 1];
2969
+ if (inLine) {
2970
+ if (ch === "\n") {
2971
+ inLine = false;
2972
+ out += ch;
2973
+ }
2974
+ continue;
2975
+ }
2976
+ if (inBlock) {
2977
+ if (ch === "*" && next === "/") {
2978
+ inBlock = false;
2979
+ i++;
2980
+ }
2981
+ continue;
2982
+ }
2983
+ if (inString) {
2984
+ out += ch;
2985
+ if (ch === "\\") {
2986
+ out += next ?? "";
2987
+ i++;
2988
+ } else if (ch === "\"") inString = false;
2989
+ continue;
2990
+ }
2991
+ if (ch === "\"") {
2992
+ inString = true;
2993
+ out += ch;
2994
+ continue;
2995
+ }
2996
+ if (ch === "/" && next === "/") {
2997
+ inLine = true;
2998
+ i++;
2999
+ continue;
3000
+ }
3001
+ if (ch === "/" && next === "*") {
3002
+ inBlock = true;
3003
+ i++;
3004
+ continue;
3005
+ }
3006
+ out += ch;
3007
+ }
3008
+ return out.replace(/,(\s*[}\]])/g, "$1");
3009
+ }
3010
+ function readConfig(path$2) {
3011
+ let raw;
3012
+ try {
3013
+ raw = (0, fs.readFileSync)(path$2, "utf-8");
3014
+ } catch {
3015
+ return null;
3016
+ }
3017
+ try {
3018
+ const json = JSON.parse(stripJsonc(raw));
3019
+ return {
3020
+ dir: (0, path.dirname)(path$2),
3021
+ compilerOptions: json.compilerOptions ?? {},
3022
+ extends: json.extends
3023
+ };
3024
+ } catch {
3025
+ return null;
3026
+ }
3027
+ }
3028
+ function resolveExtendsTarget(specifier, fromDir) {
3029
+ if (specifier.startsWith(".") || (0, path.isAbsolute)(specifier)) {
3030
+ const base = (0, path.resolve)(fromDir, specifier);
3031
+ for (const candidate of [
3032
+ base,
3033
+ `${base}.json`,
3034
+ (0, path.join)(base, "tsconfig.json")
3035
+ ]) if ((0, fs.existsSync)(candidate)) return candidate;
3036
+ return null;
3037
+ }
3038
+ try {
3039
+ return require.resolve(specifier.endsWith(".json") ? specifier : `${specifier}/tsconfig.json`, { paths: [fromDir] });
3040
+ } catch {
3041
+ try {
3042
+ return require.resolve(specifier, { paths: [fromDir] });
3043
+ } catch {
3044
+ return null;
3045
+ }
3046
+ }
3047
+ }
3048
+ /** Child-first flattened extends chain starting at `entryPath`. */
3049
+ function loadChain(entryPath) {
3050
+ const chain = [];
3051
+ const visited = /* @__PURE__ */ new Set();
3052
+ const queue = [entryPath];
3053
+ while (queue.length > 0) {
3054
+ const key = (0, path.resolve)(queue.shift());
3055
+ if (visited.has(key)) continue;
3056
+ visited.add(key);
3057
+ const node = readConfig(key);
3058
+ if (!node) continue;
3059
+ chain.push(node);
3060
+ const parents = Array.isArray(node.extends) ? node.extends : node.extends !== void 0 ? [node.extends] : [];
3061
+ for (const parent of parents) {
3062
+ if (typeof parent !== "string") continue;
3063
+ const resolved = resolveExtendsTarget(parent, node.dir);
3064
+ if (resolved) queue.push(resolved);
3065
+ }
3066
+ }
3067
+ return chain;
3068
+ }
3069
+ /**
3070
+ * Read the project's tsconfig path aliases as pairs consumable by
3071
+ * `buildPathAliasesJson`. Returns an empty array when no readable tsconfig
3072
+ * (or no usable `paths`) exists.
3073
+ */
3074
+ function readTsconfigAliasPairs(rootDir) {
3075
+ const chain = loadChain((0, path.join)(rootDir, "tsconfig.json"));
3076
+ if (chain.length === 0) return [];
3077
+ const pathsOwner = chain.find((node) => node.compilerOptions.paths && typeof node.compilerOptions.paths === "object");
3078
+ if (!pathsOwner) return [];
3079
+ const paths = pathsOwner.compilerOptions.paths;
3080
+ const baseOwner = chain.find((node) => typeof node.compilerOptions.baseUrl === "string");
3081
+ const base = baseOwner ? (0, path.resolve)(baseOwner.dir, baseOwner.compilerOptions.baseUrl) : pathsOwner.dir;
3082
+ const pairs = [];
3083
+ for (const [pattern, targets] of Object.entries(paths)) {
3084
+ const target = Array.isArray(targets) ? targets[0] : void 0;
3085
+ if (typeof target !== "string") continue;
3086
+ const patternStars = pattern.split("*").length - 1;
3087
+ const targetStars = target.split("*").length - 1;
3088
+ if (pattern === "*" || patternStars > 1 || targetStars > 1) continue;
3089
+ if (pattern.endsWith("/*")) {
3090
+ if (!target.endsWith("/*")) continue;
3091
+ pairs.push({
3092
+ pattern: pattern.slice(0, -2),
3093
+ target: (0, path.resolve)(base, target.slice(0, -2)),
3094
+ kind: "prefix"
3095
+ });
3096
+ continue;
3097
+ }
3098
+ if (patternStars > 0 || targetStars > 0) continue;
3099
+ pairs.push({
3100
+ pattern,
3101
+ target: (0, path.resolve)(base, target),
3102
+ kind: "exact"
3103
+ });
3104
+ }
3105
+ return pairs;
3106
+ }
3107
+ //#endregion
3108
+ //#region pipeline/error-diagnostics.ts
3109
+ /**
3110
+ * Throw when the diagnostics carry any `kind: "error"` entry — one
3111
+ * aggregated `Error` naming EVERY offender (component, file, message — one
3112
+ * line per entry, each prefixed `[animus]`). Warning-only diagnostics
3113
+ * (`bail`/`skip`/`warn`, any severity) never trip this gate; their routing
3114
+ * stays with `surfaceManifestDiagnostics`. Callers accept the manifest only
3115
+ * past this point, so no stylesheet from a failing analysis is published.
3116
+ */
3117
+ function assertNoErrorDiagnostics(diagnostics) {
3118
+ const errors = (diagnostics ?? []).filter((diagnostic) => diagnostic.kind === "error");
3119
+ if (errors.length === 0) return;
3120
+ const lines = [...new Set(errors.map((diagnostic) => `[animus] ${diagnostic.component || "<unknown component>"} (${diagnostic.file || "<unknown file>"}): ${diagnostic.message || "<no message>"}`))];
3121
+ throw new Error(lines.join("\n"));
3122
+ }
3123
+ //#endregion
3124
+ //#region pipeline/replacement-plans.ts
3125
+ const snapshotByManifest = /* @__PURE__ */ new WeakMap();
3126
+ function snapshotFilePlans(manifest) {
3127
+ const memoKey = manifest !== null && typeof manifest === "object" ? manifest : null;
3128
+ if (memoKey) {
3129
+ const cached = snapshotByManifest.get(memoKey);
3130
+ if (cached) return cached;
3131
+ }
3132
+ const entriesByFile = /* @__PURE__ */ new Map();
3133
+ for (const [id, desc] of Object.entries(manifest?.components ?? {})) {
3134
+ const file = desc.file;
3135
+ if (!file) continue;
3136
+ const list = entriesByFile.get(file) ?? [];
3137
+ list.push([id, desc.replacement ?? ""]);
3138
+ entriesByFile.set(file, list);
3139
+ }
3140
+ const snapshot = /* @__PURE__ */ new Map();
3141
+ for (const [file, entries] of entriesByFile) {
3142
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
3143
+ snapshot.set(file, JSON.stringify(entries));
3144
+ }
3145
+ if (memoKey) snapshotByManifest.set(memoKey, snapshot);
3146
+ return snapshot;
3147
+ }
3148
+ /**
3149
+ * Rel paths whose plan changed between two snapshots: absent→present,
3150
+ * present→absent, and any change to membership or replacement content.
3151
+ * `exclude` drops one path (the changed file itself on the edit path — its
3152
+ * own modules are already in the update set).
3153
+ */
3154
+ function diffFilePlans(prev, next, opts) {
3155
+ const changed = /* @__PURE__ */ new Set();
3156
+ for (const [file, plan] of next) if (prev.get(file) !== plan) changed.add(file);
3157
+ for (const file of prev.keys()) if (!next.has(file)) changed.add(file);
3158
+ if (opts?.exclude) changed.delete(opts.exclude);
3159
+ return [...changed].sort();
3160
+ }
3161
+ /** Domain prefix keeping the epoch hash disjoint from every other
3162
+ * contentHash use in the pipeline (design D5). */
3163
+ const REPLACEMENT_PLANS_DOMAIN = "animus-replacement-plans-v1\0";
3164
+ /** Section marker for the served-dependency witness. Leads with NUL: every
3165
+ * plan entry ends `…\0` and neither file paths nor plan JSON contain NUL,
3166
+ * so `\0\0` is unreachable from entry serialization alone — a snapshot can
3167
+ * never forge the witness section. */
3168
+ const SERVED_DEPENDENCY_DOMAIN = "\0animus-served-dependency-v1\0";
3169
+ /**
3170
+ * Canonical replacement epoch: contentHash over the domain-prefixed, sorted
3171
+ * canonical serialization of a file-plan snapshot — each entry contributes
3172
+ * `file + '\0' + plan + '\0'` (unambiguous: neither file paths nor the
3173
+ * JSON plan strings contain NUL). Byte-identical plans → identical epoch;
3174
+ * any membership/replacement/absent↔present change moves it.
3175
+ *
3176
+ * `servedDependencyWitness` extends the epoch to content the plans cannot
3177
+ * see but restored modules depend on: transformed modules import the
3178
+ * session's served system-props artifact, so a consumer passes that
3179
+ * artifact's content here and an offline change to it moves the epoch —
3180
+ * invalidating persistent-cache snapshots that reference the old epoch
3181
+ * artifact. Absence and empty-string are distinct values.
3182
+ *
3183
+ * This is THE epoch definition — integrations consume this hash (or the
3184
+ * snapshot diff) and never define their own. Epoch values compare only for
3185
+ * equality (a moved value invalidates), so the serialization is free to
3186
+ * evolve with a domain bump: sessions running different serializations
3187
+ * simply disagree once and rebuild.
3188
+ */
3189
+ function hashReplacementPlans(snapshot, servedDependencyWitness) {
3190
+ const entries = [...snapshot.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
3191
+ let serialized = REPLACEMENT_PLANS_DOMAIN;
3192
+ for (const [file, plan] of entries) serialized += file + "\0" + plan + "\0";
3193
+ if (servedDependencyWitness !== void 0) serialized += SERVED_DEPENDENCY_DOMAIN + servedDependencyWitness;
3194
+ return contentHash(serialized);
3195
+ }
3196
+ //#endregion
3197
+ //#region pipeline/utils.ts
3198
+ /** Convert camelCase CSS property names to kebab-case. */
3199
+ function camelToKebab(str) {
3200
+ return str.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
3201
+ }
3202
+ //#endregion
3203
+ //#region pipeline/watch-keys.ts
3204
+ /**
3205
+ * Membership keys for a filesystem path in the system-dependency watch set.
3206
+ *
3207
+ * The loader reports symlink-resolved canonical paths; watcher events carry
3208
+ * lexical absolute paths that may traverse symlinks (bun workspace links) and
3209
+ * — for deletions — may no longer exist, so `realpathSync` on the event path
3210
+ * alone cannot produce the canonical form. Both insertion and lookup go
3211
+ * through this one normalizer: the lexical form plus a canonical form
3212
+ * reconstructed through the nearest existing ancestor.
3213
+ */
3214
+ function toWatchKeys(input) {
3215
+ const lexical = (0, node_path.normalize)(input);
3216
+ const canonical = realpathThroughNearestExistingAncestor(lexical);
3217
+ return canonical === lexical ? [lexical] : [lexical, canonical];
3218
+ }
3219
+ /**
3220
+ * Canonicalize a path that may not exist: walk up to the nearest existing
3221
+ * ancestor, realpath it, and re-append the missing suffix. Handles deleted
3222
+ * files under still-existing (possibly symlinked) directories and atomic
3223
+ * unlink/rename saves. Falls back to the input when no ancestor resolves.
3224
+ *
3225
+ * Known limit: a symlink retargeted AFTER the system load canonicalizes to
3226
+ * the new target, which cannot match the recorded (old-target) dependency —
3227
+ * the membership test then fails open (no reset), identical to not having
3228
+ * this reconstruction at all. Retarget sensitivity is a resolution-input
3229
+ * concern, deliberately out of scope for the watch set.
3230
+ */
3231
+ function realpathThroughNearestExistingAncestor(path) {
3232
+ try {
3233
+ return (0, node_fs.realpathSync)(path);
3234
+ } catch {}
3235
+ const suffix = [];
3236
+ let current = path;
3237
+ for (;;) {
3238
+ const parent = (0, node_path.dirname)(current);
3239
+ if (parent === current) return path;
3240
+ suffix.unshift((0, node_path.basename)(current));
3241
+ current = parent;
3242
+ try {
3243
+ return (0, node_path.join)((0, node_fs.realpathSync)(current), ...suffix);
3244
+ } catch {}
3245
+ }
3246
+ }
3247
+ //#endregion
3248
+ Object.defineProperty(exports, "ANIMUS_LAYERS", {
3249
+ enumerable: true,
3250
+ get: function() {
3251
+ return ANIMUS_LAYERS;
3252
+ }
3253
+ });
3254
+ Object.defineProperty(exports, "AnimusConfigError", {
3255
+ enumerable: true,
3256
+ get: function() {
3257
+ return AnimusConfigError;
3258
+ }
3259
+ });
3260
+ Object.defineProperty(exports, "CORE_OPTION_KEYS", {
3261
+ enumerable: true,
3262
+ get: function() {
3263
+ return CORE_OPTION_KEYS;
3264
+ }
3265
+ });
3266
+ Object.defineProperty(exports, "DEFAULT_EXCLUDE", {
3267
+ enumerable: true,
3268
+ get: function() {
3269
+ return DEFAULT_EXCLUDE;
3270
+ }
3271
+ });
3272
+ Object.defineProperty(exports, "DEFAULT_EXTENSIONS", {
3273
+ enumerable: true,
3274
+ get: function() {
3275
+ return DEFAULT_EXTENSIONS;
3276
+ }
3277
+ });
3278
+ Object.defineProperty(exports, "DRIVER_NAMESPACES", {
3279
+ enumerable: true,
3280
+ get: function() {
3281
+ return DRIVER_NAMESPACES;
3282
+ }
3283
+ });
3284
+ Object.defineProperty(exports, "ENGINE_TRANSFORM_EXTENSIONS", {
3285
+ enumerable: true,
3286
+ get: function() {
3287
+ return ENGINE_TRANSFORM_EXTENSIONS;
3288
+ }
3289
+ });
3290
+ Object.defineProperty(exports, "KEYFRAMES_EXPORT_COLLISION", {
3291
+ enumerable: true,
3292
+ get: function() {
3293
+ return KEYFRAMES_EXPORT_COLLISION;
3294
+ }
3295
+ });
3296
+ Object.defineProperty(exports, "KEYFRAMES_EXTERNAL_ENTRY_FAILED", {
3297
+ enumerable: true,
3298
+ get: function() {
3299
+ return KEYFRAMES_EXTERNAL_ENTRY_FAILED;
3300
+ }
3301
+ });
3302
+ Object.defineProperty(exports, "REPLACEABLE_DEFAULT_EXCLUDE", {
3303
+ enumerable: true,
3304
+ get: function() {
3305
+ return REPLACEABLE_DEFAULT_EXCLUDE;
3306
+ }
3307
+ });
3308
+ Object.defineProperty(exports, "RETIRED_ENGINE_MESSAGE", {
3309
+ enumerable: true,
3310
+ get: function() {
3311
+ return RETIRED_ENGINE_MESSAGE;
3312
+ }
3313
+ });
3314
+ Object.defineProperty(exports, "STRUCTURAL_EXCLUDE", {
3315
+ enumerable: true,
3316
+ get: function() {
3317
+ return STRUCTURAL_EXCLUDE;
3318
+ }
3319
+ });
3320
+ Object.defineProperty(exports, "__toESM", {
3321
+ enumerable: true,
3322
+ get: function() {
3323
+ return __toESM;
3324
+ }
3325
+ });
3326
+ Object.defineProperty(exports, "adaptSvelteSource", {
3327
+ enumerable: true,
3328
+ get: function() {
3329
+ return adaptSvelteSource;
3330
+ }
3331
+ });
3332
+ Object.defineProperty(exports, "applyPrefix", {
3333
+ enumerable: true,
3334
+ get: function() {
3335
+ return applyPrefix;
3336
+ }
3337
+ });
3338
+ Object.defineProperty(exports, "applyUnitFallback", {
3339
+ enumerable: true,
3340
+ get: function() {
3341
+ return applyUnitFallback;
3342
+ }
3343
+ });
3344
+ Object.defineProperty(exports, "assembleStylesheet", {
3345
+ enumerable: true,
3346
+ get: function() {
3347
+ return assembleStylesheet;
3348
+ }
3349
+ });
3350
+ Object.defineProperty(exports, "assertKnownOptionKeys", {
3351
+ enumerable: true,
3352
+ get: function() {
3353
+ return assertKnownOptionKeys;
3354
+ }
3355
+ });
3356
+ Object.defineProperty(exports, "assertNoErrorDiagnostics", {
3357
+ enumerable: true,
3358
+ get: function() {
3359
+ return assertNoErrorDiagnostics;
3360
+ }
3361
+ });
3362
+ Object.defineProperty(exports, "assertNoRetiredEngineSelection", {
3363
+ enumerable: true,
3364
+ get: function() {
3365
+ return assertNoRetiredEngineSelection;
3366
+ }
3367
+ });
3368
+ Object.defineProperty(exports, "buildAnalysisInputs", {
3369
+ enumerable: true,
3370
+ get: function() {
3371
+ return buildAnalysisInputs;
3372
+ }
3373
+ });
3374
+ Object.defineProperty(exports, "buildAnalyzeProjectArgs", {
3375
+ enumerable: true,
3376
+ get: function() {
3377
+ return buildAnalyzeProjectArgs;
3378
+ }
3379
+ });
3380
+ Object.defineProperty(exports, "buildDynamicPropConfig", {
3381
+ enumerable: true,
3382
+ get: function() {
3383
+ return buildDynamicPropConfig;
3384
+ }
3385
+ });
3386
+ Object.defineProperty(exports, "buildPathAliasesJson", {
3387
+ enumerable: true,
3388
+ get: function() {
3389
+ return buildPathAliasesJson;
3390
+ }
3391
+ });
3392
+ Object.defineProperty(exports, "buildSystemPropsModule", {
3393
+ enumerable: true,
3394
+ get: function() {
3395
+ return buildSystemPropsModule;
3396
+ }
3397
+ });
3398
+ Object.defineProperty(exports, "camelToKebab", {
3399
+ enumerable: true,
3400
+ get: function() {
3401
+ return camelToKebab;
3402
+ }
3403
+ });
3404
+ Object.defineProperty(exports, "clearEngineCache", {
3405
+ enumerable: true,
3406
+ get: function() {
3407
+ return clearEngineCache;
3408
+ }
3409
+ });
3410
+ Object.defineProperty(exports, "collectExternalPackageSources", {
3411
+ enumerable: true,
3412
+ get: function() {
3413
+ return collectExternalPackageSources;
3414
+ }
3415
+ });
3416
+ Object.defineProperty(exports, "contentHash", {
3417
+ enumerable: true,
3418
+ get: function() {
3419
+ return contentHash;
3420
+ }
3421
+ });
3422
+ Object.defineProperty(exports, "createExcludeMatcher", {
3423
+ enumerable: true,
3424
+ get: function() {
3425
+ return createExcludeMatcher;
3426
+ }
3427
+ });
3428
+ Object.defineProperty(exports, "createSourceIdentity", {
3429
+ enumerable: true,
3430
+ get: function() {
3431
+ return createSourceIdentity;
3432
+ }
3433
+ });
3434
+ Object.defineProperty(exports, "createSourceIngestor", {
3435
+ enumerable: true,
3436
+ get: function() {
3437
+ return createSourceIngestor;
3438
+ }
3439
+ });
3440
+ Object.defineProperty(exports, "createV2EngineApi", {
3441
+ enumerable: true,
3442
+ get: function() {
3443
+ return createV2EngineApi;
3444
+ }
3445
+ });
3446
+ Object.defineProperty(exports, "diffFilePlans", {
3447
+ enumerable: true,
3448
+ get: function() {
3449
+ return diffFilePlans;
3450
+ }
3451
+ });
3452
+ Object.defineProperty(exports, "discoverFiles", {
3453
+ enumerable: true,
3454
+ get: function() {
3455
+ return discoverFiles;
3456
+ }
3457
+ });
3458
+ Object.defineProperty(exports, "enforceExternalTokenContracts", {
3459
+ enumerable: true,
3460
+ get: function() {
3461
+ return enforceExternalTokenContracts;
3462
+ }
3463
+ });
3464
+ Object.defineProperty(exports, "excludeCollectedPackages", {
3465
+ enumerable: true,
3466
+ get: function() {
3467
+ return excludeCollectedPackages;
3468
+ }
3469
+ });
3470
+ Object.defineProperty(exports, "extractSystemFilePackages", {
3471
+ enumerable: true,
3472
+ get: function() {
3473
+ return extractSystemFilePackages;
3474
+ }
3475
+ });
3476
+ Object.defineProperty(exports, "findAssetSpecifiers", {
3477
+ enumerable: true,
3478
+ get: function() {
3479
+ return findAssetSpecifiers;
3480
+ }
3481
+ });
3482
+ Object.defineProperty(exports, "findPackageRoot", {
3483
+ enumerable: true,
3484
+ get: function() {
3485
+ return findPackageRoot;
3486
+ }
3487
+ });
3488
+ Object.defineProperty(exports, "firstOwners", {
3489
+ enumerable: true,
3490
+ get: function() {
3491
+ return firstOwners;
3492
+ }
3493
+ });
3494
+ Object.defineProperty(exports, "formatRustTimingWaterfall", {
3495
+ enumerable: true,
3496
+ get: function() {
3497
+ return formatRustTimingWaterfall;
3498
+ }
3499
+ });
3500
+ Object.defineProperty(exports, "hashReplacementPlans", {
3501
+ enumerable: true,
3502
+ get: function() {
3503
+ return hashReplacementPlans;
3504
+ }
3505
+ });
3506
+ Object.defineProperty(exports, "ingestSourceEntries", {
3507
+ enumerable: true,
3508
+ get: function() {
3509
+ return ingestSourceEntries;
3510
+ }
3511
+ });
3512
+ Object.defineProperty(exports, "isAdvisorySourceDiagnostic", {
3513
+ enumerable: true,
3514
+ get: function() {
3515
+ return isAdvisorySourceDiagnostic;
3516
+ }
3517
+ });
3518
+ Object.defineProperty(exports, "isExcludedPackageRelativePath", {
3519
+ enumerable: true,
3520
+ get: function() {
3521
+ return isExcludedPackageRelativePath;
3522
+ }
3523
+ });
3524
+ Object.defineProperty(exports, "isPathWithinRoot", {
3525
+ enumerable: true,
3526
+ get: function() {
3527
+ return isPathWithinRoot;
3528
+ }
3529
+ });
3530
+ Object.defineProperty(exports, "isUnresolvedParentDrop", {
3531
+ enumerable: true,
3532
+ get: function() {
3533
+ return isUnresolvedParentDrop;
3534
+ }
3535
+ });
3536
+ Object.defineProperty(exports, "loadSystemConfig", {
3537
+ enumerable: true,
3538
+ get: function() {
3539
+ return loadSystemConfig;
3540
+ }
3541
+ });
3542
+ Object.defineProperty(exports, "mergeExternalKeyframes", {
3543
+ enumerable: true,
3544
+ get: function() {
3545
+ return mergeExternalKeyframes;
3546
+ }
3547
+ });
3548
+ Object.defineProperty(exports, "postProcessCss", {
3549
+ enumerable: true,
3550
+ get: function() {
3551
+ return postProcessCss;
3552
+ }
3553
+ });
3554
+ Object.defineProperty(exports, "preprocessMdx", {
3555
+ enumerable: true,
3556
+ get: function() {
3557
+ return preprocessMdx;
3558
+ }
3559
+ });
3560
+ Object.defineProperty(exports, "readTsconfigAliasPairs", {
3561
+ enumerable: true,
3562
+ get: function() {
3563
+ return readTsconfigAliasPairs;
3564
+ }
3565
+ });
3566
+ Object.defineProperty(exports, "resolveAbsolutePathSpecifier", {
3567
+ enumerable: true,
3568
+ get: function() {
3569
+ return resolveAbsolutePathSpecifier;
3570
+ }
3571
+ });
3572
+ Object.defineProperty(exports, "resolveAssetFile", {
3573
+ enumerable: true,
3574
+ get: function() {
3575
+ return resolveAssetFile;
3576
+ }
3577
+ });
3578
+ Object.defineProperty(exports, "resolveLightningTargets", {
3579
+ enumerable: true,
3580
+ get: function() {
3581
+ return resolveLightningTargets;
3582
+ }
3583
+ });
3584
+ Object.defineProperty(exports, "resolveMode", {
3585
+ enumerable: true,
3586
+ get: function() {
3587
+ return resolveMode;
3588
+ }
3589
+ });
3590
+ Object.defineProperty(exports, "resolveThroughPathAliases", {
3591
+ enumerable: true,
3592
+ get: function() {
3593
+ return resolveThroughPathAliases;
3594
+ }
3595
+ });
3596
+ Object.defineProperty(exports, "runProjectAnalysis", {
3597
+ enumerable: true,
3598
+ get: function() {
3599
+ return runProjectAnalysis;
3600
+ }
3601
+ });
3602
+ Object.defineProperty(exports, "runStructuralSelfCheck", {
3603
+ enumerable: true,
3604
+ get: function() {
3605
+ return runStructuralSelfCheck;
3606
+ }
3607
+ });
3608
+ Object.defineProperty(exports, "serializeStaticCss", {
3609
+ enumerable: true,
3610
+ get: function() {
3611
+ return serializeStaticCss;
3612
+ }
3613
+ });
3614
+ Object.defineProperty(exports, "sharesVolumeRoot", {
3615
+ enumerable: true,
3616
+ get: function() {
3617
+ return sharesVolumeRoot;
3618
+ }
3619
+ });
3620
+ Object.defineProperty(exports, "snapshotFilePlans", {
3621
+ enumerable: true,
3622
+ get: function() {
3623
+ return snapshotFilePlans;
3624
+ }
3625
+ });
3626
+ Object.defineProperty(exports, "staleDistIncludesMessage", {
3627
+ enumerable: true,
3628
+ get: function() {
3629
+ return staleDistIncludesMessage;
3630
+ }
3631
+ });
3632
+ Object.defineProperty(exports, "stripLeadingLayerDeclaration", {
3633
+ enumerable: true,
3634
+ get: function() {
3635
+ return stripLeadingLayerDeclaration;
3636
+ }
3637
+ });
3638
+ Object.defineProperty(exports, "substituteAssetPlaceholders", {
3639
+ enumerable: true,
3640
+ get: function() {
3641
+ return substituteAssetPlaceholders;
3642
+ }
3643
+ });
3644
+ Object.defineProperty(exports, "surfaceManifestDiagnostics", {
3645
+ enumerable: true,
3646
+ get: function() {
3647
+ return surfaceManifestDiagnostics;
3648
+ }
3649
+ });
3650
+ Object.defineProperty(exports, "toWatchKeys", {
3651
+ enumerable: true,
3652
+ get: function() {
3653
+ return toWatchKeys;
3654
+ }
3655
+ });
3656
+ Object.defineProperty(exports, "unresolvableIncludesMessage", {
3657
+ enumerable: true,
3658
+ get: function() {
3659
+ return unresolvableIncludesMessage;
3660
+ }
3661
+ });
3662
+ Object.defineProperty(exports, "unresolvedParentName", {
3663
+ enumerable: true,
3664
+ get: function() {
3665
+ return unresolvedParentName;
3666
+ }
3667
+ });
3668
+ Object.defineProperty(exports, "validateLayerOrder", {
3669
+ enumerable: true,
3670
+ get: function() {
3671
+ return validateLayerOrder;
3672
+ }
3673
+ });
3674
+ Object.defineProperty(exports, "walkPackageSources", {
3675
+ enumerable: true,
3676
+ get: function() {
3677
+ return walkPackageSources;
3678
+ }
3679
+ });
3680
+ Object.defineProperty(exports, "withoutInvalidOriginals", {
3681
+ enumerable: true,
3682
+ get: function() {
3683
+ return withoutInvalidOriginals;
3684
+ }
3685
+ });