@mintlify/common 1.0.1269 → 1.0.1270

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 (26) hide show
  1. package/dist/mdx/estreeReferences.d.ts +39 -0
  2. package/dist/mdx/estreeReferences.js +963 -0
  3. package/dist/mdx/plugins/remark/firstPartyMarkdownComponents.d.ts +3 -0
  4. package/dist/mdx/plugins/remark/firstPartyMarkdownComponents.js +29 -0
  5. package/dist/mdx/plugins/remark/remarkMdxRemoveUnknownJsx/index.d.ts +1 -1
  6. package/dist/mdx/plugins/remark/remarkVisibilityForMarkdown.d.ts +7 -1
  7. package/dist/mdx/plugins/remark/remarkVisibilityForMarkdown.js +581 -177
  8. package/dist/mdx/plugins/remark/staticEvaluator.d.ts +55 -0
  9. package/dist/mdx/plugins/remark/staticEvaluator.js +639 -0
  10. package/dist/mdx/plugins/remark/unfoldComponentsForMarkdown.d.ts +71 -0
  11. package/dist/mdx/plugins/remark/unfoldComponentsForMarkdown.js +1414 -0
  12. package/dist/mdx/remark-core.d.ts +7 -0
  13. package/dist/mdx/remark-core.js +32 -0
  14. package/dist/mdx/remark.d.ts +1 -7
  15. package/dist/mdx/remark.js +2 -32
  16. package/dist/mdx/snippets/getExportMap.js +33 -5
  17. package/dist/mdx/snippets/resolveAllImports.js +3 -2
  18. package/dist/mdx/snippets/resolveImport/exportCollision.d.ts +1 -0
  19. package/dist/mdx/snippets/resolveImport/exportCollision.js +2 -1
  20. package/dist/mdx/snippets/resolveImport/index.d.ts +11 -1
  21. package/dist/mdx/snippets/resolveImport/index.js +129 -16
  22. package/dist/mdx/snippets/resolveImport/resolveComponentWithContent.js +38 -5
  23. package/dist/mdx/snippets/resolveImport/snippetDeclarations.d.ts +56 -0
  24. package/dist/mdx/snippets/resolveImport/snippetDeclarations.js +655 -0
  25. package/dist/tsconfig.build.tsbuildinfo +1 -1
  26. package/package.json +2 -2
@@ -0,0 +1,655 @@
1
+ import { jsx, toJs } from 'estree-util-to-js';
2
+ import { isObject } from '../../../types/guards.js';
3
+ import { collectFreeReferences, collectPatternNames, forEachCodeChild, visitReferences, } from '../../estreeReferences.js';
4
+ import { getAST } from '../../remark.js';
5
+ import { estreeIsProgram, isMdxJsEsm } from '../../utils.js';
6
+ import { moduleExportName } from '../importedExportName.js';
7
+ function statementDeclaredNames(statement) {
8
+ const names = new Set();
9
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
10
+ if (declaration == null)
11
+ return names;
12
+ if (declaration.type === 'VariableDeclaration') {
13
+ for (const declarator of declaration.declarations) {
14
+ collectPatternNames(declarator.id, names);
15
+ }
16
+ }
17
+ else if ((declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
18
+ declaration.id != null) {
19
+ names.add(declaration.id.name);
20
+ }
21
+ return names;
22
+ }
23
+ export function isolateExportedDeclarator(tree, name) {
24
+ var _a;
25
+ for (const node of tree.children) {
26
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
27
+ continue;
28
+ for (const statement of node.data.estree.body) {
29
+ if (statement.type !== 'ExportNamedDeclaration' ||
30
+ ((_a = statement.declaration) === null || _a === void 0 ? void 0 : _a.type) !== 'VariableDeclaration') {
31
+ continue;
32
+ }
33
+ const declarator = statement.declaration.declarations.find((candidate) => candidate.id.type === 'Identifier' && candidate.id.name === name);
34
+ if (declarator === undefined)
35
+ continue;
36
+ const isolated = Object.assign(Object.assign({}, node.data.estree), { body: [
37
+ Object.assign(Object.assign({}, statement), { declaration: Object.assign(Object.assign({}, statement.declaration), { declarations: [declarator] }) }),
38
+ ] });
39
+ return getAST(toJs(isolated, { handlers: jsx }).value);
40
+ }
41
+ }
42
+ return tree;
43
+ }
44
+ /** Names a module makes importable: named export declarations, specifiers, and default. */
45
+ export function collectExportedNames(tree) {
46
+ const names = new Set();
47
+ for (const node of tree.children) {
48
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
49
+ continue;
50
+ for (const statement of node.data.estree.body) {
51
+ if (statement.type === 'ExportDefaultDeclaration') {
52
+ names.add('default');
53
+ continue;
54
+ }
55
+ if (statement.type !== 'ExportNamedDeclaration')
56
+ continue;
57
+ // `export { local as "Name" }` exports a string name, which imports can still request
58
+ for (const specifier of statement.specifiers)
59
+ names.add(moduleExportName(specifier.exported));
60
+ for (const name of statementDeclaredNames(statement))
61
+ names.add(name);
62
+ }
63
+ }
64
+ return names;
65
+ }
66
+ /** Top-level bindings that only hold their value once their declaration runs: variables and classes. */
67
+ function collectInitializedBindingNames(tree) {
68
+ const names = new Set();
69
+ for (const node of tree.children) {
70
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
71
+ continue;
72
+ for (const statement of node.data.estree.body) {
73
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
74
+ if ((declaration === null || declaration === void 0 ? void 0 : declaration.type) !== 'VariableDeclaration' && (declaration === null || declaration === void 0 ? void 0 : declaration.type) !== 'ClassDeclaration') {
75
+ continue;
76
+ }
77
+ for (const name of statementDeclaredNames(statement))
78
+ names.add(name);
79
+ }
80
+ }
81
+ return names;
82
+ }
83
+ /** Every top-level lexical binding in the tree's ESM statements, exported or not. */
84
+ export function collectTopLevelBindingNames(tree) {
85
+ const names = new Set();
86
+ for (const node of tree.children) {
87
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
88
+ continue;
89
+ for (const statement of node.data.estree.body) {
90
+ if (statement.type === 'ImportDeclaration') {
91
+ for (const specifier of statement.specifiers)
92
+ names.add(specifier.local.name);
93
+ continue;
94
+ }
95
+ if (statement.type === 'ExportNamedDeclaration' ||
96
+ statement.type === 'VariableDeclaration' ||
97
+ statement.type === 'FunctionDeclaration' ||
98
+ statement.type === 'ClassDeclaration') {
99
+ for (const name of statementDeclaredNames(statement))
100
+ names.add(name);
101
+ continue;
102
+ }
103
+ if (statement.type === 'ExportDefaultDeclaration' &&
104
+ (statement.declaration.type === 'FunctionDeclaration' ||
105
+ statement.declaration.type === 'ClassDeclaration') &&
106
+ statement.declaration.id != null) {
107
+ names.add(statement.declaration.id.name);
108
+ }
109
+ }
110
+ }
111
+ return names;
112
+ }
113
+ function forEachShorthandProperty(node, callback) {
114
+ if (Array.isArray(node)) {
115
+ for (const child of node)
116
+ forEachShorthandProperty(child, callback);
117
+ return;
118
+ }
119
+ if (!isObject(node))
120
+ return;
121
+ if (node.type === 'Property' && node.shorthand === true)
122
+ callback(node);
123
+ forEachCodeChild(node, (child) => forEachShorthandProperty(child, callback));
124
+ }
125
+ function shorthandValueName(value) {
126
+ if (!isObject(value))
127
+ return undefined;
128
+ if (value.type === 'AssignmentPattern' && isObject(value.left))
129
+ return value.left.name;
130
+ return value.name;
131
+ }
132
+ function renameName(identifier, renames) {
133
+ if (!isObject(identifier) || typeof identifier.name !== 'string')
134
+ return;
135
+ const next = renames.get(identifier.name);
136
+ if (next !== undefined)
137
+ identifier.name = next;
138
+ }
139
+ function renamePatternBindings(pattern, renames) {
140
+ if (!isObject(pattern))
141
+ return;
142
+ switch (pattern.type) {
143
+ case 'Identifier':
144
+ renameName(pattern, renames);
145
+ return;
146
+ case 'AssignmentPattern':
147
+ renamePatternBindings(pattern.left, renames);
148
+ return;
149
+ case 'RestElement':
150
+ renamePatternBindings(pattern.argument, renames);
151
+ return;
152
+ case 'ObjectPattern': {
153
+ const properties = Array.isArray(pattern.properties) ? pattern.properties : [];
154
+ for (const property of properties) {
155
+ if (!isObject(property))
156
+ continue;
157
+ renamePatternBindings(property.type === 'RestElement' ? property.argument : property.value, renames);
158
+ }
159
+ return;
160
+ }
161
+ case 'ArrayPattern': {
162
+ const elements = Array.isArray(pattern.elements) ? pattern.elements : [];
163
+ for (const element of elements)
164
+ renamePatternBindings(element, renames);
165
+ return;
166
+ }
167
+ default:
168
+ return;
169
+ }
170
+ }
171
+ /** Renames module-level references in place; `renameBindings` also renames the node's own declaration. */
172
+ function renameModuleBindings(node, renames, renameBindings) {
173
+ forEachShorthandProperty(node, (property) => {
174
+ if (isObject(property.key))
175
+ property.key = Object.assign({}, property.key);
176
+ });
177
+ visitReferences(node, new Set(), {
178
+ reference: (identifier) => renameName(identifier, renames),
179
+ });
180
+ if (renameBindings && isObject(node)) {
181
+ if (node.type === 'VariableDeclaration' && Array.isArray(node.declarations)) {
182
+ for (const declarator of node.declarations) {
183
+ if (isObject(declarator))
184
+ renamePatternBindings(declarator.id, renames);
185
+ }
186
+ }
187
+ else {
188
+ renameName(node.id, renames);
189
+ }
190
+ }
191
+ forEachShorthandProperty(node, (property) => {
192
+ if (isObject(property.key) && shorthandValueName(property.value) !== property.key.name) {
193
+ property.shorthand = false;
194
+ }
195
+ });
196
+ }
197
+ /**
198
+ * Orders items after their dependencies. Items in a dependency cycle keep their original order,
199
+ * since `var` cycles are valid and their values depend on which initializer runs first.
200
+ */
201
+ function orderByDependencies(items, dependenciesOf) {
202
+ const position = new Map(items.map((item, index) => [item, index]));
203
+ const visitIndex = new Map();
204
+ const lowLink = new Map();
205
+ const stack = [];
206
+ const onStack = new Set();
207
+ const ordered = [];
208
+ const connect = (item) => {
209
+ var _a, _b, _c, _d;
210
+ const index = visitIndex.size;
211
+ visitIndex.set(item, index);
212
+ lowLink.set(item, index);
213
+ stack.push(item);
214
+ onStack.add(item);
215
+ for (const dependency of dependenciesOf(item)) {
216
+ if (!position.has(dependency))
217
+ continue;
218
+ if (!visitIndex.has(dependency)) {
219
+ connect(dependency);
220
+ lowLink.set(item, Math.min((_a = lowLink.get(item)) !== null && _a !== void 0 ? _a : index, (_b = lowLink.get(dependency)) !== null && _b !== void 0 ? _b : index));
221
+ }
222
+ else if (onStack.has(dependency)) {
223
+ lowLink.set(item, Math.min((_c = lowLink.get(item)) !== null && _c !== void 0 ? _c : index, (_d = visitIndex.get(dependency)) !== null && _d !== void 0 ? _d : index));
224
+ }
225
+ }
226
+ if (lowLink.get(item) !== index)
227
+ return;
228
+ const component = [];
229
+ for (let member = stack.pop(); member !== undefined; member = stack.pop()) {
230
+ onStack.delete(member);
231
+ component.push(member);
232
+ if (member === item)
233
+ break;
234
+ }
235
+ component.sort((a, b) => { var _a, _b; return ((_a = position.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = position.get(b)) !== null && _b !== void 0 ? _b : 0); });
236
+ ordered.push(...component);
237
+ };
238
+ for (const item of items)
239
+ if (!visitIndex.has(item))
240
+ connect(item);
241
+ return ordered;
242
+ }
243
+ /**
244
+ * Orders units so each follows the units it reads while initializing. Reads inside function and
245
+ * method bodies run later, so they never force an order, which keeps cycles through them safe.
246
+ */
247
+ function orderByEagerReads(selected, units) {
248
+ // Units are collected in source order, so their first appearance gives their position
249
+ const sourceOrder = new Map();
250
+ for (const unit of units.values()) {
251
+ if (!sourceOrder.has(unit))
252
+ sourceOrder.set(unit, sourceOrder.size);
253
+ }
254
+ const inSourceOrder = [...selected].sort((a, b) => { var _a, _b; return ((_a = sourceOrder.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = sourceOrder.get(b)) !== null && _b !== void 0 ? _b : 0); });
255
+ return orderByDependencies(inSourceOrder, (unit) => [...collectFreeReferences(unit.declaration, true)].flatMap((reference) => {
256
+ const dependency = units.get(reference);
257
+ return dependency === undefined ? [] : [dependency];
258
+ }));
259
+ }
260
+ function serializeDeclaration(program, declaration) {
261
+ return toJs(Object.assign(Object.assign({}, program), { body: [declaration] }), { handlers: jsx }).value;
262
+ }
263
+ /** Indexes a module's declarations by name, split per declarator, plus its export aliases. */
264
+ function collectDeclarationUnits(tree) {
265
+ const units = new Map();
266
+ const aliases = new Map();
267
+ const register = (program, declaration) => {
268
+ const pieces = declaration.type === 'VariableDeclaration'
269
+ ? declaration.declarations.map((declarator) => (Object.assign(Object.assign({}, declaration), { declarations: [declarator] })))
270
+ : [declaration];
271
+ for (const piece of pieces) {
272
+ const names = statementDeclaredNames(piece);
273
+ if (names.size === 0)
274
+ continue;
275
+ const references = collectFreeReferences(piece);
276
+ for (const name of names)
277
+ references.delete(name);
278
+ const unit = { names, references, declaration: piece, program };
279
+ for (const name of names) {
280
+ if (!units.has(name))
281
+ units.set(name, unit);
282
+ }
283
+ }
284
+ };
285
+ for (const node of tree.children) {
286
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
287
+ continue;
288
+ const program = node.data.estree;
289
+ for (const statement of program.body) {
290
+ if (statement.type === 'VariableDeclaration' ||
291
+ statement.type === 'FunctionDeclaration' ||
292
+ statement.type === 'ClassDeclaration') {
293
+ register(program, statement);
294
+ continue;
295
+ }
296
+ if (statement.type === 'ExportDefaultDeclaration') {
297
+ const declaration = statement.declaration;
298
+ if ((declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
299
+ declaration.id != null) {
300
+ // The name is a module binding even though the statement is a default export
301
+ register(program, declaration);
302
+ }
303
+ continue;
304
+ }
305
+ if (statement.type !== 'ExportNamedDeclaration')
306
+ continue;
307
+ if (statement.declaration != null) {
308
+ register(program, statement.declaration);
309
+ continue;
310
+ }
311
+ // A re-export names a binding in another module, so it is not an alias of a local
312
+ if (statement.source != null)
313
+ continue;
314
+ for (const specifier of statement.specifiers) {
315
+ if (specifier.local.type === 'Identifier') {
316
+ aliases.set(moduleExportName(specifier.exported), specifier.local.name);
317
+ }
318
+ }
319
+ }
320
+ }
321
+ return { units, aliases };
322
+ }
323
+ /** The local binding behind an export name, following `export { local as name }`. */
324
+ export function exportedBindingName(tree, exportName) {
325
+ var _a;
326
+ return (_a = collectDeclarationUnits(tree).aliases.get(exportName)) !== null && _a !== void 0 ? _a : exportName;
327
+ }
328
+ /** Source of the top-level declaration that binds `name`, without any `export` keyword. */
329
+ export function declarationSource(tree, name) {
330
+ const unit = collectDeclarationUnits(tree).units.get(name);
331
+ return unit === undefined ? undefined : serializeDeclaration(unit.program, unit.declaration);
332
+ }
333
+ /** Names an export statement's source declares, destructured patterns included. */
334
+ export function statementSourceNames(source) {
335
+ const names = new Set();
336
+ for (const node of getAST(source).children) {
337
+ if (!isMdxJsEsm(node) || !estreeIsProgram(node))
338
+ continue;
339
+ for (const statement of node.data.estree.body) {
340
+ for (const name of statementDeclaredNames(statement))
341
+ names.add(name);
342
+ }
343
+ }
344
+ return names;
345
+ }
346
+ /**
347
+ * Rewrites a single variable export so it no longer declares the names in `drop`. A declarator
348
+ * that only binds dropped names and that no kept declarator reads is removed, so its initializer
349
+ * never runs. Any other dropped name is renamed to a private name throughout the statement, so
350
+ * rest elements still receive the same keys and kept declarators still read the snippet's values.
351
+ */
352
+ export function pruneDeclaredNames(source, drop, isNameTaken = () => false) {
353
+ var _a;
354
+ const tree = getAST(source);
355
+ const [node] = tree.children;
356
+ if (node === undefined || !isMdxJsEsm(node) || !estreeIsProgram(node))
357
+ return undefined;
358
+ const program = node.data.estree;
359
+ const [statement] = program.body;
360
+ if (program.body.length !== 1 ||
361
+ (statement === null || statement === void 0 ? void 0 : statement.type) !== 'ExportNamedDeclaration' ||
362
+ ((_a = statement.declaration) === null || _a === void 0 ? void 0 : _a.type) !== 'VariableDeclaration') {
363
+ return undefined;
364
+ }
365
+ const declaration = statement.declaration;
366
+ let declarators = [...declaration.declarations];
367
+ const isRemovable = (declarator) => {
368
+ const names = new Set();
369
+ collectPatternNames(declarator.id, names);
370
+ if (names.size === 0 || ![...names].every((name) => drop.has(name)))
371
+ return false;
372
+ const readByOthers = declarators
373
+ .filter((other) => other !== declarator)
374
+ .some((other) => [...collectFreeReferences(other)].some((reference) => names.has(reference)));
375
+ return !readByOthers;
376
+ };
377
+ for (let removable = declarators.find(isRemovable); removable !== undefined;) {
378
+ declarators = declarators.filter((declarator) => declarator !== removable);
379
+ removable = declarators.find(isRemovable);
380
+ }
381
+ if (declarators.length === 0)
382
+ return undefined;
383
+ declaration.declarations = declarators;
384
+ const fingerprint = moduleFingerprint(tree);
385
+ const renames = new Map();
386
+ for (const name of drop) {
387
+ const base = `${PRIVATE_SIBLING_PREFIX}${name}_${fingerprint}`;
388
+ let candidate = base;
389
+ for (let suffix = 1; isNameTaken(candidate); suffix++)
390
+ candidate = `${base}_${suffix}`;
391
+ renames.set(name, candidate);
392
+ }
393
+ renameModuleBindings(declaration, renames, true);
394
+ return toJs(program, { handlers: jsx }).value;
395
+ }
396
+ const PRIVATE_SIBLING_PREFIX = '__snippet_';
397
+ export function isPrivateSiblingName(name) {
398
+ return name.startsWith(PRIVATE_SIBLING_PREFIX);
399
+ }
400
+ /** FNV-1a over a module's ESM source, so a helper's private name identifies its exact code. */
401
+ function moduleFingerprint(tree) {
402
+ let hash = 0x811c9dc5;
403
+ for (const node of tree.children) {
404
+ if (!isMdxJsEsm(node))
405
+ continue;
406
+ for (let index = 0; index < node.value.length; index++) {
407
+ hash = Math.imul(hash ^ node.value.charCodeAt(index), 0x01000193) >>> 0;
408
+ }
409
+ }
410
+ return hash.toString(36);
411
+ }
412
+ /**
413
+ * Removes the private sibling declarations for `names` from the tree, with the private siblings
414
+ * they reference, and returns them dependencies first so they can be re-inserted above new readers.
415
+ */
416
+ export function takePrivateDeclarations(tree, names) {
417
+ const initializedNames = collectInitializedBindingNames(tree);
418
+ const sourceOrder = new Map(tree.children.map((child, index) => [child, index]));
419
+ const taken = [];
420
+ const movable = new Map();
421
+ // A helper that reads a page binding while initializing stays below it, as does anything that
422
+ // reads such a helper while initializing. Imports and function declarations are hoisted.
423
+ const take = (name) => {
424
+ const known = movable.get(name);
425
+ if (known !== undefined)
426
+ return known;
427
+ movable.set(name, true);
428
+ const node = tree.children.find((child) => isMdxJsEsm(child) &&
429
+ estreeIsProgram(child) &&
430
+ child.data.estree.body.some((statement) => statementDeclaredNames(statement).has(name)));
431
+ if (node === undefined || !isMdxJsEsm(node) || !estreeIsProgram(node))
432
+ return true;
433
+ const eager = collectFreeReferences(node.data.estree, true);
434
+ let canMove = ![...eager].some((reference) => !isPrivateSiblingName(reference) && initializedNames.has(reference));
435
+ for (const reference of collectFreeReferences(node.data.estree)) {
436
+ if (isPrivateSiblingName(reference) && !take(reference) && eager.has(reference)) {
437
+ canMove = false;
438
+ }
439
+ }
440
+ movable.set(name, canMove);
441
+ if (!canMove)
442
+ return false;
443
+ // A grouped declaration may already have been taken through one of its other names
444
+ const index = tree.children.indexOf(node);
445
+ if (index === -1)
446
+ return true;
447
+ tree.children.splice(index, 1);
448
+ const declared = new Set(node.data.estree.body.flatMap((statement) => [...statementDeclaredNames(statement)]));
449
+ taken.push({ node, declared, eager });
450
+ return true;
451
+ };
452
+ for (const name of names)
453
+ take(name);
454
+ // Method and function bodies read lazily, so only reads made while initializing set the order
455
+ taken.sort((a, b) => { var _a, _b; return ((_a = sourceOrder.get(a.node)) !== null && _a !== void 0 ? _a : 0) - ((_b = sourceOrder.get(b.node)) !== null && _b !== void 0 ? _b : 0); });
456
+ const byName = new Map();
457
+ for (const entry of taken) {
458
+ for (const declaredName of entry.declared)
459
+ byName.set(declaredName, entry);
460
+ }
461
+ return orderByDependencies(taken, (entry) => [...entry.eager].flatMap((reference) => {
462
+ const dependency = byName.get(reference);
463
+ return dependency === undefined ? [] : [dependency];
464
+ })).map((entry) => entry.node);
465
+ }
466
+ /**
467
+ * Injects each node as high as it can go: at the top of the page, or just below the last
468
+ * declaration it reads while initializing, such as a reused helper that could not move above a
469
+ * page binding. Placing nodes one at a time keeps helpers that need no such dependency at the top,
470
+ * above any existing code that reads them.
471
+ */
472
+ export function injectBelowEagerDependencies(tree, nodes) {
473
+ var _a;
474
+ let topIndex = ((_a = tree.children[0]) === null || _a === void 0 ? void 0 : _a.type) === 'yaml' ? 1 : 0;
475
+ for (const node of nodes) {
476
+ const eagerReads = isMdxJsEsm(node) && estreeIsProgram(node)
477
+ ? collectFreeReferences(node.data.estree, true)
478
+ : new Set();
479
+ let index = topIndex;
480
+ tree.children.forEach((child, childIndex) => {
481
+ if (childIndex < index || !isMdxJsEsm(child) || !estreeIsProgram(child))
482
+ return;
483
+ const declaresRead = child.data.estree.body.some((statement) => {
484
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
485
+ if ((declaration === null || declaration === void 0 ? void 0 : declaration.type) !== 'VariableDeclaration' &&
486
+ (declaration === null || declaration === void 0 ? void 0 : declaration.type) !== 'ClassDeclaration') {
487
+ return false;
488
+ }
489
+ return [...statementDeclaredNames(statement)].some((name) => eagerReads.has(name));
490
+ });
491
+ if (declaresRead)
492
+ index = childIndex + 1;
493
+ });
494
+ tree.children.splice(index, 0, node);
495
+ if (index === topIndex)
496
+ topIndex++;
497
+ }
498
+ }
499
+ /**
500
+ * Collects the snippet declarations the injected statement transitively references. They stay
501
+ * private to the import, as in a real module: each gets a reserved name derived from its snippet,
502
+ * and dependencies are declared first. A sibling an earlier import already injected is reused and
503
+ * moved up with its own dependencies, so it stays above every reader.
504
+ */
505
+ /**
506
+ * The private names that the other bindings of `binding`'s declarator take on a page, such as
507
+ * `other` for `export const [binding, other] = …`.
508
+ */
509
+ export function patternSiblingNames(imported, binding) {
510
+ var _a;
511
+ const unit = collectDeclarationUnits(imported).units.get(binding);
512
+ const fingerprint = moduleFingerprint(imported);
513
+ const names = new Map();
514
+ for (const name of (_a = unit === null || unit === void 0 ? void 0 : unit.names) !== null && _a !== void 0 ? _a : []) {
515
+ if (name !== binding)
516
+ names.set(name, `${PRIVATE_SIBLING_PREFIX}${name}_${fingerprint}`);
517
+ }
518
+ return names;
519
+ }
520
+ export function prepareSnippetSiblings(destination, imported, statement, requested,
521
+ // Snippet bindings this page already declares, so readers share that binding instead of a copy
522
+ heldBindings = new Map()) {
523
+ var _a;
524
+ const { units, aliases } = collectDeclarationUnits(imported);
525
+ const requestedOriginal = (_a = aliases.get(requested.name)) !== null && _a !== void 0 ? _a : requested.name;
526
+ const statementNames = collectTopLevelBindingNames(statement);
527
+ const statementOriginals = new Set([...statementNames].map((name) => (name === requested.localName ? requestedOriginal : name)));
528
+ const renames = new Map();
529
+ if (requestedOriginal !== requested.localName && statementNames.has(requested.localName)) {
530
+ renames.set(requestedOriginal, requested.localName);
531
+ }
532
+ const destinationNames = collectTopLevelBindingNames(destination);
533
+ const fingerprint = moduleFingerprint(imported);
534
+ const visited = new Set();
535
+ const ordered = [];
536
+ const visitName = (name) => {
537
+ if (statementOriginals.has(name))
538
+ return;
539
+ const unit = units.get(name);
540
+ // A declarator is reused only when the page holds every name it binds. Copying it for one
541
+ // name would redeclare the others.
542
+ const unitHeld = unit !== undefined && [...unit.names].every((unitName) => heldBindings.has(unitName));
543
+ if (unitHeld) {
544
+ for (const unitName of unit.names) {
545
+ const held = heldBindings.get(unitName);
546
+ if (held !== undefined)
547
+ renames.set(unitName, held);
548
+ }
549
+ return;
550
+ }
551
+ if (unit === undefined || visited.has(unit))
552
+ return;
553
+ visited.add(unit);
554
+ for (const unitName of unit.names) {
555
+ renames.set(unitName, `${PRIVATE_SIBLING_PREFIX}${unitName}_${fingerprint}`);
556
+ }
557
+ for (const reference of unit.references)
558
+ visitName(reference);
559
+ ordered.push(unit);
560
+ };
561
+ const programs = statement.children.flatMap((node) => isMdxJsEsm(node) && estreeIsProgram(node) ? [node.data.estree] : []);
562
+ const statementReferences = collectFreeReferences(programs);
563
+ for (const reference of statementReferences)
564
+ visitName(reference);
565
+ // MDX only parses lines that start with `import`/`export` as code, so private siblings are
566
+ // exported under their reserved names rather than declared bare.
567
+ const render = (unit) => {
568
+ const declaration = structuredClone(unit.declaration);
569
+ renameModuleBindings(declaration, renames, true);
570
+ return getAST(serializeDeclaration(unit.program, {
571
+ type: 'ExportNamedDeclaration',
572
+ declaration,
573
+ specifiers: [],
574
+ source: null,
575
+ }));
576
+ };
577
+ // Units are settled dependencies first, so each renders with its dependencies' final names. A
578
+ // name already in the destination is reused only when it declares exactly this code; otherwise
579
+ // the next suffix is tried, so a page binding or a helper rewritten for another import never
580
+ // supplies the value, and a later import of the same code finds the suffixed copy again.
581
+ const reused = [];
582
+ const injectedUnits = [];
583
+ for (const unit of ordered) {
584
+ const bases = new Map([...unit.names].map((unitName) => {
585
+ var _a;
586
+ return [
587
+ unitName,
588
+ (_a = renames.get(unitName)) !== null && _a !== void 0 ? _a : unitName,
589
+ ];
590
+ }));
591
+ for (let suffix = 0;; suffix++) {
592
+ const names = [];
593
+ for (const [unitName, base] of bases) {
594
+ const name = suffix === 0 ? base : `${base}_${suffix}`;
595
+ renames.set(unitName, name);
596
+ names.push(name);
597
+ }
598
+ if (names.some((name) => statementNames.has(name)))
599
+ continue;
600
+ const rendered = render(unit);
601
+ const present = names.find((name) => destinationNames.has(name));
602
+ if (present === undefined) {
603
+ injectedUnits.push(unit);
604
+ break;
605
+ }
606
+ if (declarationSource(destination, present) === declarationSource(rendered, present)) {
607
+ reused.push(...names);
608
+ break;
609
+ }
610
+ }
611
+ }
612
+ // A sibling that reads the imported statement while initializing must run after it; anything
613
+ // that eagerly reads such a sibling follows it there
614
+ const trailingNames = new Set(statementOriginals);
615
+ const trailingUnits = new Set();
616
+ for (let grew = true; grew;) {
617
+ grew = false;
618
+ for (const unit of injectedUnits) {
619
+ if (trailingUnits.has(unit))
620
+ continue;
621
+ const eager = collectFreeReferences(unit.declaration, true);
622
+ if (![...eager].some((reference) => trailingNames.has(reference)))
623
+ continue;
624
+ trailingUnits.add(unit);
625
+ for (const unitName of unit.names)
626
+ trailingNames.add(unitName);
627
+ grew = true;
628
+ }
629
+ }
630
+ // Rendered once every name is settled, so cyclic helpers agree on each other's final names
631
+ const renderAll = (units) => units.flatMap((unit) => render(unit).children);
632
+ const declarationOrder = orderByEagerReads(injectedUnits, units);
633
+ const siblings = [
634
+ ...takePrivateDeclarations(destination, reused),
635
+ ...renderAll(declarationOrder.filter((unit) => !trailingUnits.has(unit))),
636
+ ];
637
+ const trailing = renderAll(declarationOrder.filter((unit) => trailingUnits.has(unit)));
638
+ const privateNames = new Map();
639
+ for (const unit of ordered) {
640
+ for (const unitName of unit.names) {
641
+ const finalName = renames.get(unitName);
642
+ if (finalName !== undefined)
643
+ privateNames.set(unitName, finalName);
644
+ }
645
+ }
646
+ if (![...statementReferences].some((reference) => renames.has(reference))) {
647
+ return { siblings, statement, trailing, privateNames };
648
+ }
649
+ const rewritten = programs.map((program) => {
650
+ const clone = structuredClone(program);
651
+ renameModuleBindings(clone, renames, false);
652
+ return toJs(clone, { handlers: jsx }).value;
653
+ });
654
+ return { siblings, statement: getAST(rewritten.join('\n')), trailing, privateNames };
655
+ }