| 63 | apply: 'build', |
| 64 | enforce: 'post', |
| 65 | transform(code: string, id: string) { |
| 66 | // Only operate on JS/TS and extracted Vue script blocks |
| 67 | if (!/\.(mjs|cjs|js|ts|jsx|tsx)(\?|$)/.test(id) && !/\.vue\?vue&type=script/.test(id)) { |
| 68 | return null; |
| 69 | } |
| 70 | let ast: any; |
| 71 | try { |
| 72 | ast = babelParse(code, { |
| 73 | sourceType: 'module', |
| 74 | plugins: [ |
| 75 | 'typescript', |
| 76 | 'jsx', |
| 77 | // Allow decorators/experimental features if present; harmless if unused |
| 78 | ['decorators', { decoratorsBeforeExport: true }], |
| 79 | ] as any, |
| 80 | }); |
| 81 | } catch { |
| 82 | return null; |
| 83 | } |
| 84 | |
| 85 | let mutated = false; |
| 86 | let hasNSVNamespace = false; |
| 87 | let hasNSVDefaultVar = false; |
| 88 | const nsVarName = '__NSV'; |
| 89 | const defVarName = '__nsv'; |
| 90 | |
| 91 | const newNodes: t.Statement[] = []; |
| 92 | const nodesToRemove: t.Node[] = []; |
| 93 | |
| 94 | (traverse as any).default?.(ast, { |
| 95 | Program: { |
| 96 | exit(path: any) { |
| 97 | if (!mutated) return; |
| 98 | // Prepend namespace/default helpers if they were requested by transforms |
| 99 | const body = path.node.body as t.Statement[]; |
| 100 | const prepend: t.Statement[] = []; |
| 101 | if (!hasNSVNamespace) { |
| 102 | prepend.push(t.importDeclaration([t.importNamespaceSpecifier(t.identifier(nsVarName))], t.stringLiteral('nativescript-vue'))); |
| 103 | hasNSVNamespace = true; |
| 104 | } |
| 105 | if (!hasNSVDefaultVar) { |
| 106 | prepend.push( |
| 107 | t.variableDeclaration('const', [ |
| 108 | t.variableDeclarator( |
| 109 | t.identifier(defVarName), |
| 110 | t.logicalExpression( |
| 111 | '||', |
| 112 | // Prefer explicit default when present; fall back to namespace |
| 113 | t.memberExpression(t.identifier(nsVarName), t.identifier('default'), false), |
| 114 | t.identifier(nsVarName), |
| 115 | ), |
| 116 | ), |
| 117 | ]), |
| 118 | ); |
| 119 | hasNSVDefaultVar = true; |
| 120 | } |
| 121 | path.node.body = [...prepend, ...body]; |
| 122 | }, |