@graphql-tools/graphql-tag-pluck 6.4.1 → 6.5.1

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.
package/es5/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { __spread, __assign, __awaiter, __generator } from 'tslib';
2
- import { parse as parse$1 } from '@babel/parser';
2
+ import { parse } from '@babel/parser';
3
3
  import { isVariableDeclarator, isIdentifier, isTemplateLiteral, isImportDefaultSpecifier, isImportSpecifier } from '@babel/types';
4
4
  import { asArray } from '@graphql-tools/utils/es5';
5
5
  import traverse from '@babel/traverse';
@@ -151,6 +151,18 @@ var defaults = {
151
151
  name: 'react-relay',
152
152
  identifier: 'graphql',
153
153
  },
154
+ {
155
+ name: 'react-relay/hooks',
156
+ identifier: 'graphql',
157
+ },
158
+ {
159
+ name: 'relay-runtime',
160
+ identifier: 'graphql',
161
+ },
162
+ {
163
+ name: 'babel-plugin-relay/macro',
164
+ identifier: 'graphql',
165
+ },
154
166
  {
155
167
  name: 'apollo-boost',
156
168
  identifier: 'gql',
@@ -191,6 +203,26 @@ var defaults = {
191
203
  name: 'graphql.macro',
192
204
  identifier: 'gql',
193
205
  },
206
+ {
207
+ name: '@urql/core',
208
+ identifier: 'gql',
209
+ },
210
+ {
211
+ name: 'urql',
212
+ identifier: 'gql',
213
+ },
214
+ {
215
+ name: '@urql/preact',
216
+ identifier: 'gql',
217
+ },
218
+ {
219
+ name: '@urql/svelte',
220
+ identifier: 'gql',
221
+ },
222
+ {
223
+ name: '@urql/vue',
224
+ identifier: 'gql',
225
+ },
194
226
  ],
195
227
  gqlMagicComment: 'graphql',
196
228
  globalGqlIdentifierName: ['gql', 'graphql'],
@@ -230,7 +262,7 @@ const createVisitor = (function (code, out, options) {
230
262
  // Slice quotes
231
263
  .slice(start + 1, end - 1)
232
264
  // Erase string interpolations as we gonna export everything as a single
233
- // string anyways
265
+ // string anyway
234
266
  .replace(/\$\{[^}]*\}/g, '')
235
267
  .split('\\`')
236
268
  .join('`'), options.skipIndent);
@@ -422,7 +454,7 @@ var gqlPluckFromCodeStringSync = function (filePath, code, options) {
422
454
  function parseCode(_a) {
423
455
  var code = _a.code, filePath = _a.filePath, options = _a.options;
424
456
  var out = { returnValue: null };
425
- var ast = parse$1(code, generateConfig(filePath, code));
457
+ var ast = parse(code, generateConfig(filePath, code));
426
458
  var visitor = createVisitor(code, out, options);
427
459
  traverse(ast, visitor);
428
460
  return out.returnValue || [];
@@ -453,7 +485,7 @@ function pluckVueFileScript(fileData) {
453
485
  switch (_a.label) {
454
486
  case 0:
455
487
  _a.trys.push([0, 2, , 3]);
456
- return [4 /*yield*/, Promise.resolve().then(function () { return compilerSfc_cjs; })];
488
+ return [4 /*yield*/, import('@vue/compiler-sfc')];
457
489
  case 1:
458
490
  // tslint:disable-next-line: no-implicit-dependencies
459
491
  vueTemplateCompiler = _a.sent();
@@ -479,2510 +511,5 @@ function pluckVueFileScriptSync(fileData) {
479
511
  return parseWithVue(vueTemplateCompiler, fileData);
480
512
  }
481
513
 
482
- Object.defineProperty(exports, '__esModule', { value: true });
483
-
484
- var CompilerDOM = require('@vue/compiler-dom');
485
- var sourceMap = require('source-map');
486
- var postcss = require('postcss');
487
- var hash = require('hash-sum');
488
- var path = require('path');
489
- var compilerCore = require('@vue/compiler-core');
490
- var url = require('url');
491
- var shared = require('@vue/shared');
492
- var CompilerSSR = require('@vue/compiler-ssr');
493
- var selectorParser = require('postcss-selector-parser');
494
- var merge = require('merge-source-map');
495
- var MagicString = require('magic-string');
496
- var parser = require('@babel/parser');
497
- var estreeWalker = require('estree-walker');
498
-
499
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
500
-
501
- function _interopNamespace(e) {
502
- if (e && e.__esModule) return e;
503
- var n = Object.create(null);
504
- if (e) {
505
- Object.keys(e).forEach(function (k) {
506
- n[k] = e[k];
507
- });
508
- }
509
- n['default'] = e;
510
- return Object.freeze(n);
511
- }
512
-
513
- var CompilerDOM__namespace = /*#__PURE__*/_interopNamespace(CompilerDOM);
514
- var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
515
- var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
516
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
517
- var CompilerSSR__namespace = /*#__PURE__*/_interopNamespace(CompilerSSR);
518
- var selectorParser__default = /*#__PURE__*/_interopDefaultLegacy(selectorParser);
519
- var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);
520
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
521
-
522
- const CSS_VARS_HELPER = `useCssVars`;
523
- const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
524
- function genCssVarsFromList(vars, id, isProd) {
525
- return `{\n ${vars
526
- .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
527
- .join(',\n ')}\n}`;
528
- }
529
- function genVarName(id, raw, isProd) {
530
- if (isProd) {
531
- return hash__default(id + raw);
532
- }
533
- else {
534
- return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
535
- }
536
- }
537
- function parseCssVars(sfc) {
538
- const vars = [];
539
- sfc.styles.forEach(style => {
540
- let match;
541
- while ((match = cssVarRE.exec(style.content))) {
542
- vars.push(match[1] || match[2] || match[3]);
543
- }
544
- });
545
- return vars;
546
- }
547
- const cssVarsPlugin = postcss__default.plugin('vue-scoped', opts => (root) => {
548
- const { id, isProd } = opts;
549
- root.walkDecls(decl => {
550
- // rewrite CSS variables
551
- if (cssVarRE.test(decl.value)) {
552
- decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
553
- return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
554
- });
555
- }
556
- });
557
- });
558
- function genCssVarsCode(vars, bindings, id, isProd) {
559
- const varsExp = genCssVarsFromList(vars, id, isProd);
560
- const exp = CompilerDOM.createSimpleExpression(varsExp, false);
561
- const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
562
- prefixIdentifiers: true,
563
- inline: true,
564
- bindingMetadata: bindings
565
- });
566
- const transformed = CompilerDOM.processExpression(exp, context);
567
- const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
568
- ? transformed.content
569
- : transformed.children
570
- .map(c => {
571
- return typeof c === 'string'
572
- ? c
573
- : c.content;
574
- })
575
- .join('');
576
- return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
577
- }
578
- // <script setup> already gets the calls injected as part of the transform
579
- // this is only for single normal <script>
580
- function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
581
- return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
582
- `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
583
- `const __setup__ = __default__.setup\n` +
584
- `__default__.setup = __setup__\n` +
585
- ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
586
- ` : __injectCSSVars__\n`);
587
- }
588
-
589
- const hasWarned = {};
590
- function warnOnce(msg) {
591
- const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
592
- if (!isNodeProd && !false && !hasWarned[msg]) {
593
- hasWarned[msg] = true;
594
- warn(msg);
595
- }
596
- }
597
- function warn(msg) {
598
- console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
599
- }
600
- function warnExperimental(feature, rfcId) {
601
- warnOnce(`${feature} is still an experimental proposal.\n` +
602
- `Follow its status at https://github.com/vuejs/rfcs/pull/${rfcId}.`);
603
- warnOnce(`When using experimental features,\n` +
604
- `it is recommended to pin your vue dependencies to exact versions to avoid breakage.`);
605
- }
606
-
607
- const SFC_CACHE_MAX_SIZE = 500;
608
- const sourceToSFC = new (require('lru-cache'))(SFC_CACHE_MAX_SIZE);
609
- function parse(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, compiler = CompilerDOM__namespace } = {}) {
610
- const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
611
- const cache = sourceToSFC.get(sourceKey);
612
- if (cache) {
613
- return cache;
614
- }
615
- const descriptor = {
616
- filename,
617
- source,
618
- template: null,
619
- script: null,
620
- scriptSetup: null,
621
- styles: [],
622
- customBlocks: [],
623
- cssVars: []
624
- };
625
- const errors = [];
626
- const ast = compiler.parse(source, {
627
- // there are no components at SFC parsing level
628
- isNativeTag: () => true,
629
- // preserve all whitespaces
630
- isPreTag: () => true,
631
- getTextMode: ({ tag, props }, parent) => {
632
- // all top level elements except <template> are parsed as raw text
633
- // containers
634
- if ((!parent && tag !== 'template') ||
635
- // <template lang="xxx"> should also be treated as raw text
636
- (tag === 'template' &&
637
- props.some(p => p.type === 6 /* ATTRIBUTE */ &&
638
- p.name === 'lang' &&
639
- p.value &&
640
- p.value.content !== 'html'))) {
641
- return 2 /* RAWTEXT */;
642
- }
643
- else {
644
- return 0 /* DATA */;
645
- }
646
- },
647
- onError: e => {
648
- errors.push(e);
649
- }
650
- });
651
- ast.children.forEach(node => {
652
- if (node.type !== 1 /* ELEMENT */) {
653
- return;
654
- }
655
- if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
656
- return;
657
- }
658
- switch (node.tag) {
659
- case 'template':
660
- if (!descriptor.template) {
661
- const templateBlock = (descriptor.template = createBlock(node, source, false));
662
- templateBlock.ast = node;
663
- }
664
- else {
665
- errors.push(createDuplicateBlockError(node));
666
- }
667
- break;
668
- case 'script':
669
- const scriptBlock = createBlock(node, source, pad);
670
- const isSetup = !!scriptBlock.attrs.setup;
671
- if (isSetup && !descriptor.scriptSetup) {
672
- descriptor.scriptSetup = scriptBlock;
673
- break;
674
- }
675
- if (!isSetup && !descriptor.script) {
676
- descriptor.script = scriptBlock;
677
- break;
678
- }
679
- errors.push(createDuplicateBlockError(node, isSetup));
680
- break;
681
- case 'style':
682
- const styleBlock = createBlock(node, source, pad);
683
- if (styleBlock.attrs.vars) {
684
- errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
685
- `https://github.com/vuejs/rfcs/pull/231`));
686
- }
687
- descriptor.styles.push(styleBlock);
688
- break;
689
- default:
690
- descriptor.customBlocks.push(createBlock(node, source, pad));
691
- break;
692
- }
693
- });
694
- if (descriptor.scriptSetup) {
695
- if (descriptor.scriptSetup.src) {
696
- errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
697
- `its syntax will be ambiguous outside of the component.`));
698
- descriptor.scriptSetup = null;
699
- }
700
- if (descriptor.script && descriptor.script.src) {
701
- errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
702
- `also present because they must be processed together.`));
703
- descriptor.script = null;
704
- }
705
- }
706
- if (sourceMap) {
707
- const genMap = (block) => {
708
- if (block && !block.src) {
709
- block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
710
- }
711
- };
712
- genMap(descriptor.template);
713
- genMap(descriptor.script);
714
- descriptor.styles.forEach(genMap);
715
- descriptor.customBlocks.forEach(genMap);
716
- }
717
- // parse CSS vars
718
- descriptor.cssVars = parseCssVars(descriptor);
719
- if (descriptor.cssVars.length) {
720
- warnExperimental(`v-bind() CSS variable injection`, 231);
721
- }
722
- const result = {
723
- descriptor,
724
- errors
725
- };
726
- sourceToSFC.set(sourceKey, result);
727
- return result;
728
- }
729
- function createDuplicateBlockError(node, isScriptSetup = false) {
730
- const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
731
- err.loc = node.loc;
732
- return err;
733
- }
734
- function createBlock(node, source, pad) {
735
- const type = node.tag;
736
- let { start, end } = node.loc;
737
- let content = '';
738
- if (node.children.length) {
739
- start = node.children[0].loc.start;
740
- end = node.children[node.children.length - 1].loc.end;
741
- content = source.slice(start.offset, end.offset);
742
- }
743
- const loc = {
744
- source: content,
745
- start,
746
- end
747
- };
748
- const attrs = {};
749
- const block = {
750
- type,
751
- content,
752
- loc,
753
- attrs
754
- };
755
- if (pad) {
756
- block.content = padContent(source, block, pad) + block.content;
757
- }
758
- node.props.forEach(p => {
759
- if (p.type === 6 /* ATTRIBUTE */) {
760
- attrs[p.name] = p.value ? p.value.content || true : true;
761
- if (p.name === 'lang') {
762
- block.lang = p.value && p.value.content;
763
- }
764
- else if (p.name === 'src') {
765
- block.src = p.value && p.value.content;
766
- }
767
- else if (type === 'style') {
768
- if (p.name === 'scoped') {
769
- block.scoped = true;
770
- }
771
- else if (p.name === 'module') {
772
- block.module = attrs[p.name];
773
- }
774
- }
775
- else if (type === 'script' && p.name === 'setup') {
776
- block.setup = attrs.setup;
777
- }
778
- }
779
- });
780
- return block;
781
- }
782
- const splitRE = /\r?\n/g;
783
- const emptyRE = /^(?:\/\/)?\s*$/;
784
- const replaceRE = /./g;
785
- function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
786
- const map = new sourceMap.SourceMapGenerator({
787
- file: filename.replace(/\\/g, '/'),
788
- sourceRoot: sourceRoot.replace(/\\/g, '/')
789
- });
790
- map.setSourceContent(filename, source);
791
- generated.split(splitRE).forEach((line, index) => {
792
- if (!emptyRE.test(line)) {
793
- const originalLine = index + 1 + lineOffset;
794
- const generatedLine = index + 1;
795
- for (let i = 0; i < line.length; i++) {
796
- if (!/\s/.test(line[i])) {
797
- map.addMapping({
798
- source: filename,
799
- original: {
800
- line: originalLine,
801
- column: i
802
- },
803
- generated: {
804
- line: generatedLine,
805
- column: i
806
- }
807
- });
808
- }
809
- }
810
- }
811
- });
812
- return JSON.parse(map.toString());
813
- }
814
- function padContent(content, block, pad) {
815
- content = content.slice(0, block.loc.start.offset);
816
- if (pad === 'space') {
817
- return content.replace(replaceRE, ' ');
818
- }
819
- else {
820
- const offset = content.split(splitRE).length;
821
- const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
822
- return Array(offset).join(padChar);
823
- }
824
- }
825
- function hasSrc(node) {
826
- return node.props.some(p => {
827
- if (p.type !== 6 /* ATTRIBUTE */) {
828
- return false;
829
- }
830
- return p.name === 'src';
831
- });
832
- }
833
-
834
- function isRelativeUrl(url) {
835
- const firstChar = url.charAt(0);
836
- return firstChar === '.' || firstChar === '~' || firstChar === '@';
837
- }
838
- const externalRE = /^https?:\/\//;
839
- function isExternalUrl(url) {
840
- return externalRE.test(url);
841
- }
842
- const dataUrlRE = /^\s*data:/i;
843
- function isDataUrl(url) {
844
- return dataUrlRE.test(url);
845
- }
846
- /**
847
- * Parses string url into URL object.
848
- */
849
- function parseUrl(url) {
850
- const firstChar = url.charAt(0);
851
- if (firstChar === '~') {
852
- const secondChar = url.charAt(1);
853
- url = url.slice(secondChar === '/' ? 2 : 1);
854
- }
855
- return parseUriParts(url);
856
- }
857
- /**
858
- * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
859
- * @param urlString an url as a string
860
- */
861
- function parseUriParts(urlString) {
862
- // A TypeError is thrown if urlString is not a string
863
- // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
864
- return url.parse(shared.isString(urlString) ? urlString : '', false, true);
865
- }
866
-
867
- const defaultAssetUrlOptions = {
868
- base: null,
869
- includeAbsolute: false,
870
- tags: {
871
- video: ['src', 'poster'],
872
- source: ['src'],
873
- img: ['src'],
874
- image: ['xlink:href', 'href'],
875
- use: ['xlink:href', 'href']
876
- }
877
- };
878
- const normalizeOptions = (options) => {
879
- if (Object.keys(options).some(key => shared.isArray(options[key]))) {
880
- // legacy option format which directly passes in tags config
881
- return {
882
- ...defaultAssetUrlOptions,
883
- tags: options
884
- };
885
- }
886
- return {
887
- ...defaultAssetUrlOptions,
888
- ...options
889
- };
890
- };
891
- const createAssetUrlTransformWithOptions = (options) => {
892
- return (node, context) => transformAssetUrl(node, context, options);
893
- };
894
- /**
895
- * A `@vue/compiler-core` plugin that transforms relative asset urls into
896
- * either imports or absolute urls.
897
- *
898
- * ``` js
899
- * // Before
900
- * createVNode('img', { src: './logo.png' })
901
- *
902
- * // After
903
- * import _imports_0 from './logo.png'
904
- * createVNode('img', { src: _imports_0 })
905
- * ```
906
- */
907
- const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
908
- if (node.type === 1 /* ELEMENT */) {
909
- if (!node.props.length) {
910
- return;
911
- }
912
- const tags = options.tags || defaultAssetUrlOptions.tags;
913
- const attrs = tags[node.tag];
914
- const wildCardAttrs = tags['*'];
915
- if (!attrs && !wildCardAttrs) {
916
- return;
917
- }
918
- const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
919
- node.props.forEach((attr, index) => {
920
- if (attr.type !== 6 /* ATTRIBUTE */ ||
921
- !assetAttrs.includes(attr.name) ||
922
- !attr.value ||
923
- isExternalUrl(attr.value.content) ||
924
- isDataUrl(attr.value.content) ||
925
- attr.value.content[0] === '#' ||
926
- (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
927
- return;
928
- }
929
- const url = parseUrl(attr.value.content);
930
- if (options.base) {
931
- // explicit base - directly rewrite the url into absolute url
932
- // does not apply to absolute urls or urls that start with `@`
933
- // since they are aliases
934
- if (attr.value.content[0] !== '@' &&
935
- isRelativeUrl(attr.value.content)) {
936
- // Allow for full hostnames provided in options.base
937
- const base = parseUrl(options.base);
938
- const protocol = base.protocol || '';
939
- const host = base.host ? protocol + '//' + base.host : '';
940
- const basePath = base.path || '/';
941
- // when packaged in the browser, path will be using the posix-
942
- // only version provided by rollup-plugin-node-builtins.
943
- attr.value.content =
944
- host +
945
- (path__default.posix || path__default).join(basePath, url.path + (url.hash || ''));
946
- }
947
- return;
948
- }
949
- // otherwise, transform the url into an import.
950
- // this assumes a bundler will resolve the import into the correct
951
- // absolute url (e.g. webpack file-loader)
952
- const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
953
- node.props[index] = {
954
- type: 7 /* DIRECTIVE */,
955
- name: 'bind',
956
- arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
957
- exp,
958
- modifiers: [],
959
- loc: attr.loc
960
- };
961
- });
962
- }
963
- };
964
- function getImportsExpressionExp(path, hash, loc, context) {
965
- if (path) {
966
- const importsArray = Array.from(context.imports);
967
- const existing = importsArray.find(i => i.path === path);
968
- if (existing) {
969
- return existing.exp;
970
- }
971
- const name = `_imports_${importsArray.length}`;
972
- const exp = compilerCore.createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
973
- context.imports.add({ exp, path });
974
- if (hash && path) {
975
- return context.hoist(compilerCore.createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
976
- }
977
- else {
978
- return exp;
979
- }
980
- }
981
- else {
982
- return compilerCore.createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
983
- }
984
- }
985
-
986
- const srcsetTags = ['img', 'source'];
987
- // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
988
- const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
989
- const createSrcsetTransformWithOptions = (options) => {
990
- return (node, context) => transformSrcset(node, context, options);
991
- };
992
- const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
993
- if (node.type === 1 /* ELEMENT */) {
994
- if (srcsetTags.includes(node.tag) && node.props.length) {
995
- node.props.forEach((attr, index) => {
996
- if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
997
- if (!attr.value)
998
- return;
999
- const value = attr.value.content;
1000
- const imageCandidates = value.split(',').map(s => {
1001
- // The attribute value arrives here with all whitespace, except
1002
- // normal spaces, represented by escape sequences
1003
- const [url, descriptor] = s
1004
- .replace(escapedSpaceCharacters, ' ')
1005
- .trim()
1006
- .split(' ', 2);
1007
- return { url, descriptor };
1008
- });
1009
- // for data url need recheck url
1010
- for (let i = 0; i < imageCandidates.length; i++) {
1011
- if (imageCandidates[i].url.trim().startsWith('data:')) {
1012
- imageCandidates[i + 1].url =
1013
- imageCandidates[i].url + ',' + imageCandidates[i + 1].url;
1014
- imageCandidates.splice(i, 1);
1015
- }
1016
- }
1017
- // When srcset does not contain any relative URLs, skip transforming
1018
- if (!options.includeAbsolute &&
1019
- !imageCandidates.some(({ url }) => isRelativeUrl(url))) {
1020
- return;
1021
- }
1022
- if (options.base) {
1023
- const base = options.base;
1024
- const set = [];
1025
- imageCandidates.forEach(({ url, descriptor }) => {
1026
- descriptor = descriptor ? ` ${descriptor}` : ``;
1027
- if (isRelativeUrl(url)) {
1028
- set.push((path__default.posix || path__default).join(base, url) + descriptor);
1029
- }
1030
- else {
1031
- set.push(url + descriptor);
1032
- }
1033
- });
1034
- attr.value.content = set.join(', ');
1035
- return;
1036
- }
1037
- const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
1038
- imageCandidates.forEach(({ url, descriptor }, index) => {
1039
- if (!isExternalUrl(url) &&
1040
- !isDataUrl(url) &&
1041
- (options.includeAbsolute || isRelativeUrl(url))) {
1042
- const { path } = parseUrl(url);
1043
- let exp;
1044
- if (path) {
1045
- const importsArray = Array.from(context.imports);
1046
- const existingImportsIndex = importsArray.findIndex(i => i.path === path);
1047
- if (existingImportsIndex > -1) {
1048
- exp = compilerCore.createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
1049
- }
1050
- else {
1051
- exp = compilerCore.createSimpleExpression(`_imports_${importsArray.length}`, false, attr.loc, 2 /* CAN_HOIST */);
1052
- context.imports.add({ exp, path });
1053
- }
1054
- compoundExpression.children.push(exp);
1055
- }
1056
- }
1057
- else {
1058
- const exp = compilerCore.createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
1059
- compoundExpression.children.push(exp);
1060
- }
1061
- const isNotLast = imageCandidates.length - 1 > index;
1062
- if (descriptor && isNotLast) {
1063
- compoundExpression.children.push(` + '${descriptor}, ' + `);
1064
- }
1065
- else if (descriptor) {
1066
- compoundExpression.children.push(` + '${descriptor}'`);
1067
- }
1068
- else if (isNotLast) {
1069
- compoundExpression.children.push(` + ', ' + `);
1070
- }
1071
- });
1072
- const hoisted = context.hoist(compoundExpression);
1073
- hoisted.constType = 2 /* CAN_HOIST */;
1074
- node.props[index] = {
1075
- type: 7 /* DIRECTIVE */,
1076
- name: 'bind',
1077
- arg: compilerCore.createSimpleExpression('srcset', true, attr.loc),
1078
- exp: hoisted,
1079
- modifiers: [],
1080
- loc: attr.loc
1081
- };
1082
- }
1083
- });
1084
- }
1085
- }
1086
- };
1087
-
1088
- function preprocess({ source, filename, preprocessOptions }, preprocessor) {
1089
- // Consolidate exposes a callback based API, but the callback is in fact
1090
- // called synchronously for most templating engines. In our case, we have to
1091
- // expose a synchronous API so that it is usable in Jest transforms (which
1092
- // have to be sync because they are applied via Node.js require hooks)
1093
- let res = '';
1094
- let err = null;
1095
- preprocessor.render(source, { filename, ...preprocessOptions }, (_err, _res) => {
1096
- if (_err)
1097
- err = _err;
1098
- res = _res;
1099
- });
1100
- if (err)
1101
- throw err;
1102
- return res;
1103
- }
1104
- function compileTemplate(options) {
1105
- const { preprocessLang, preprocessCustomRequire } = options;
1106
- const preprocessor = preprocessLang
1107
- ? preprocessCustomRequire
1108
- ? preprocessCustomRequire(preprocessLang)
1109
- : require('consolidate')[preprocessLang]
1110
- : false;
1111
- if (preprocessor) {
1112
- try {
1113
- return doCompileTemplate({
1114
- ...options,
1115
- source: preprocess(options, preprocessor)
1116
- });
1117
- }
1118
- catch (e) {
1119
- return {
1120
- code: `export default function render() {}`,
1121
- source: options.source,
1122
- tips: [],
1123
- errors: [e]
1124
- };
1125
- }
1126
- }
1127
- else if (preprocessLang) {
1128
- return {
1129
- code: `export default function render() {}`,
1130
- source: options.source,
1131
- tips: [
1132
- `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
1133
- ],
1134
- errors: [
1135
- `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
1136
- ]
1137
- };
1138
- }
1139
- else {
1140
- return doCompileTemplate(options);
1141
- }
1142
- }
1143
- function doCompileTemplate({ filename, id, scoped, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace, compilerOptions = {}, transformAssetUrls }) {
1144
- const errors = [];
1145
- let nodeTransforms = [];
1146
- if (shared.isObject(transformAssetUrls)) {
1147
- const assetOptions = normalizeOptions(transformAssetUrls);
1148
- nodeTransforms = [
1149
- createAssetUrlTransformWithOptions(assetOptions),
1150
- createSrcsetTransformWithOptions(assetOptions)
1151
- ];
1152
- }
1153
- else if (transformAssetUrls !== false) {
1154
- nodeTransforms = [transformAssetUrl, transformSrcset];
1155
- }
1156
- if (ssr && !ssrCssVars) {
1157
- warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
1158
- `corresponding \`cssVars\` option.\`.`);
1159
- }
1160
- if (!id) {
1161
- warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
1162
- id = '';
1163
- }
1164
- const shortId = id.replace(/^data-v-/, '');
1165
- const longId = `data-v-${shortId}`;
1166
- let { code, ast, preamble, map } = compiler.compile(source, {
1167
- mode: 'module',
1168
- prefixIdentifiers: true,
1169
- hoistStatic: true,
1170
- cacheHandlers: true,
1171
- ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
1172
- ? genCssVarsFromList(ssrCssVars, shortId, isProd)
1173
- : '',
1174
- scopeId: scoped ? longId : undefined,
1175
- ...compilerOptions,
1176
- nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
1177
- filename,
1178
- sourceMap: true,
1179
- onError: e => errors.push(e)
1180
- });
1181
- // inMap should be the map produced by ./parse.ts which is a simple line-only
1182
- // mapping. If it is present, we need to adjust the final map and errors to
1183
- // reflect the original line numbers.
1184
- if (inMap) {
1185
- if (map) {
1186
- map = mapLines(inMap, map);
1187
- }
1188
- if (errors.length) {
1189
- patchErrors(errors, source, inMap);
1190
- }
1191
- }
1192
- return { code, ast, preamble, source, errors, tips: [], map };
1193
- }
1194
- function mapLines(oldMap, newMap) {
1195
- if (!oldMap)
1196
- return newMap;
1197
- if (!newMap)
1198
- return oldMap;
1199
- const oldMapConsumer = new sourceMap.SourceMapConsumer(oldMap);
1200
- const newMapConsumer = new sourceMap.SourceMapConsumer(newMap);
1201
- const mergedMapGenerator = new sourceMap.SourceMapGenerator();
1202
- newMapConsumer.eachMapping(m => {
1203
- if (m.originalLine == null) {
1204
- return;
1205
- }
1206
- const origPosInOldMap = oldMapConsumer.originalPositionFor({
1207
- line: m.originalLine,
1208
- column: m.originalColumn
1209
- });
1210
- if (origPosInOldMap.source == null) {
1211
- return;
1212
- }
1213
- mergedMapGenerator.addMapping({
1214
- generated: {
1215
- line: m.generatedLine,
1216
- column: m.generatedColumn
1217
- },
1218
- original: {
1219
- line: origPosInOldMap.line,
1220
- // use current column, since the oldMap produced by @vue/compiler-sfc
1221
- // does not
1222
- column: m.originalColumn
1223
- },
1224
- source: origPosInOldMap.source,
1225
- name: origPosInOldMap.name
1226
- });
1227
- });
1228
- // source-map's type definition is incomplete
1229
- const generator = mergedMapGenerator;
1230
- oldMapConsumer.sources.forEach((sourceFile) => {
1231
- generator._sources.add(sourceFile);
1232
- const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
1233
- if (sourceContent != null) {
1234
- mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
1235
- }
1236
- });
1237
- generator._sourceRoot = oldMap.sourceRoot;
1238
- generator._file = oldMap.file;
1239
- return generator.toJSON();
1240
- }
1241
- function patchErrors(errors, source, inMap) {
1242
- const originalSource = inMap.sourcesContent[0];
1243
- const offset = originalSource.indexOf(source);
1244
- const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
1245
- errors.forEach(err => {
1246
- if (err.loc) {
1247
- err.loc.start.line += lineOffset;
1248
- err.loc.start.offset += offset;
1249
- if (err.loc.end !== err.loc.start) {
1250
- err.loc.end.line += lineOffset;
1251
- err.loc.end.offset += offset;
1252
- }
1253
- }
1254
- });
1255
- }
1256
-
1257
- var trimPlugin = postcss__default.plugin('trim', () => (css) => {
1258
- css.walk(({ type, raws }) => {
1259
- if (type === 'rule' || type === 'atrule') {
1260
- if (raws.before)
1261
- raws.before = '\n';
1262
- if (raws.after)
1263
- raws.after = '\n';
1264
- }
1265
- });
1266
- });
1267
-
1268
- const animationNameRE = /^(-\w+-)?animation-name$/;
1269
- const animationRE = /^(-\w+-)?animation$/;
1270
- var scopedPlugin = postcss__default.plugin('vue-scoped', (id) => (root) => {
1271
- const keyframes = Object.create(null);
1272
- const shortId = id.replace(/^data-v-/, '');
1273
- root.each(function rewriteSelectors(node) {
1274
- if (node.type !== 'rule') {
1275
- // handle media queries
1276
- if (node.type === 'atrule') {
1277
- if (node.name === 'media' || node.name === 'supports') {
1278
- node.each(rewriteSelectors);
1279
- }
1280
- else if (/-?keyframes$/.test(node.name)) {
1281
- // register keyframes
1282
- keyframes[node.params] = node.params = node.params + '-' + shortId;
1283
- }
1284
- }
1285
- return;
1286
- }
1287
- node.selector = selectorParser__default(selectors => {
1288
- function rewriteSelector(selector, slotted) {
1289
- let node = null;
1290
- let shouldInject = true;
1291
- // find the last child node to insert attribute selector
1292
- selector.each(n => {
1293
- // DEPRECATED ">>>" and "/deep/" combinator
1294
- if (n.type === 'combinator' &&
1295
- (n.value === '>>>' || n.value === '/deep/')) {
1296
- n.value = ' ';
1297
- n.spaces.before = n.spaces.after = '';
1298
- warn(`the >>> and /deep/ combinators have been deprecated. ` +
1299
- `Use :deep() instead.`);
1300
- return false;
1301
- }
1302
- if (n.type === 'pseudo') {
1303
- const { value } = n;
1304
- // deep: inject [id] attribute at the node before the ::v-deep
1305
- // combinator.
1306
- if (value === ':deep' || value === '::v-deep') {
1307
- if (n.nodes.length) {
1308
- // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
1309
- // replace the current node with ::v-deep's inner selector
1310
- let last = n;
1311
- n.nodes[0].each(ss => {
1312
- selector.insertAfter(last, ss);
1313
- last = ss;
1314
- });
1315
- // insert a space combinator before if it doesn't already have one
1316
- const prev = selector.at(selector.index(n) - 1);
1317
- if (!prev || !isSpaceCombinator(prev)) {
1318
- selector.insertAfter(n, selectorParser__default.combinator({
1319
- value: ' '
1320
- }));
1321
- }
1322
- selector.removeChild(n);
1323
- }
1324
- else {
1325
- // DEPRECATED usage
1326
- // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
1327
- warn(`::v-deep usage as a combinator has ` +
1328
- `been deprecated. Use :deep(<inner-selector>) instead.`);
1329
- const prev = selector.at(selector.index(n) - 1);
1330
- if (prev && isSpaceCombinator(prev)) {
1331
- selector.removeChild(prev);
1332
- }
1333
- selector.removeChild(n);
1334
- }
1335
- return false;
1336
- }
1337
- // slot: use selector inside `::v-slotted` and inject [id + '-s']
1338
- // instead.
1339
- // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
1340
- if (value === ':slotted' || value === '::v-slotted') {
1341
- rewriteSelector(n.nodes[0], true /* slotted */);
1342
- let last = n;
1343
- n.nodes[0].each(ss => {
1344
- selector.insertAfter(last, ss);
1345
- last = ss;
1346
- });
1347
- // selector.insertAfter(n, n.nodes[0])
1348
- selector.removeChild(n);
1349
- // since slotted attribute already scopes the selector there's no
1350
- // need for the non-slot attribute.
1351
- shouldInject = false;
1352
- return false;
1353
- }
1354
- // global: replace with inner selector and do not inject [id].
1355
- // ::v-global(.foo) -> .foo
1356
- if (value === ':global' || value === '::v-global') {
1357
- selectors.insertAfter(selector, n.nodes[0]);
1358
- selectors.removeChild(selector);
1359
- return false;
1360
- }
1361
- }
1362
- if (n.type !== 'pseudo' && n.type !== 'combinator') {
1363
- node = n;
1364
- }
1365
- });
1366
- if (node) {
1367
- node.spaces.after = '';
1368
- }
1369
- else {
1370
- // For deep selectors & standalone pseudo selectors,
1371
- // the attribute selectors are prepended rather than appended.
1372
- // So all leading spaces must be eliminated to avoid problems.
1373
- selector.first.spaces.before = '';
1374
- }
1375
- if (shouldInject) {
1376
- const idToAdd = slotted ? id + '-s' : id;
1377
- selector.insertAfter(
1378
- // If node is null it means we need to inject [id] at the start
1379
- // insertAfter can handle `null` here
1380
- node, selectorParser__default.attribute({
1381
- attribute: idToAdd,
1382
- value: idToAdd,
1383
- raws: {},
1384
- quoteMark: `"`
1385
- }));
1386
- }
1387
- }
1388
- selectors.each(selector => rewriteSelector(selector));
1389
- }).processSync(node.selector);
1390
- });
1391
- if (Object.keys(keyframes).length) {
1392
- // If keyframes are found in this <style>, find and rewrite animation names
1393
- // in declarations.
1394
- // Caveat: this only works for keyframes and animation rules in the same
1395
- // <style> element.
1396
- // individual animation-name declaration
1397
- root.walkDecls(decl => {
1398
- if (animationNameRE.test(decl.prop)) {
1399
- decl.value = decl.value
1400
- .split(',')
1401
- .map(v => keyframes[v.trim()] || v.trim())
1402
- .join(',');
1403
- }
1404
- // shorthand
1405
- if (animationRE.test(decl.prop)) {
1406
- decl.value = decl.value
1407
- .split(',')
1408
- .map(v => {
1409
- const vals = v.trim().split(/\s+/);
1410
- const i = vals.findIndex(val => keyframes[val]);
1411
- if (i !== -1) {
1412
- vals.splice(i, 1, keyframes[vals[i]]);
1413
- return vals.join(' ');
1414
- }
1415
- else {
1416
- return v;
1417
- }
1418
- })
1419
- .join(',');
1420
- }
1421
- });
1422
- }
1423
- });
1424
- function isSpaceCombinator(node) {
1425
- return node.type === 'combinator' && /^\s+$/.test(node.value);
1426
- }
1427
-
1428
- // .scss/.sass processor
1429
- const scss = (source, map, options, load = require) => {
1430
- const nodeSass = load('sass');
1431
- const finalOptions = {
1432
- ...options,
1433
- data: getSource(source, options.filename, options.additionalData),
1434
- file: options.filename,
1435
- outFile: options.filename,
1436
- sourceMap: !!map
1437
- };
1438
- try {
1439
- const result = nodeSass.renderSync(finalOptions);
1440
- const dependencies = result.stats.includedFiles;
1441
- if (map) {
1442
- return {
1443
- code: result.css.toString(),
1444
- map: merge__default(map, JSON.parse(result.map.toString())),
1445
- errors: [],
1446
- dependencies
1447
- };
1448
- }
1449
- return { code: result.css.toString(), errors: [], dependencies };
1450
- }
1451
- catch (e) {
1452
- return { code: '', errors: [e], dependencies: [] };
1453
- }
1454
- };
1455
- const sass = (source, map, options, load) => scss(source, map, {
1456
- ...options,
1457
- indentedSyntax: true
1458
- }, load);
1459
- // .less
1460
- const less = (source, map, options, load = require) => {
1461
- const nodeLess = load('less');
1462
- let result;
1463
- let error = null;
1464
- nodeLess.render(getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err, output) => {
1465
- error = err;
1466
- result = output;
1467
- });
1468
- if (error)
1469
- return { code: '', errors: [error], dependencies: [] };
1470
- const dependencies = result.imports;
1471
- if (map) {
1472
- return {
1473
- code: result.css.toString(),
1474
- map: merge__default(map, result.map),
1475
- errors: [],
1476
- dependencies: dependencies
1477
- };
1478
- }
1479
- return {
1480
- code: result.css.toString(),
1481
- errors: [],
1482
- dependencies: dependencies
1483
- };
1484
- };
1485
- // .styl
1486
- const styl = (source, map, options, load = require) => {
1487
- const nodeStylus = load('stylus');
1488
- try {
1489
- const ref = nodeStylus(source);
1490
- Object.keys(options).forEach(key => ref.set(key, options[key]));
1491
- if (map)
1492
- ref.set('sourcemap', { inline: false, comment: false });
1493
- const result = ref.render();
1494
- const dependencies = ref.deps();
1495
- if (map) {
1496
- return {
1497
- code: result,
1498
- map: merge__default(map, ref.sourcemap),
1499
- errors: [],
1500
- dependencies
1501
- };
1502
- }
1503
- return { code: result, errors: [], dependencies };
1504
- }
1505
- catch (e) {
1506
- return { code: '', errors: [e], dependencies: [] };
1507
- }
1508
- };
1509
- function getSource(source, filename, additionalData) {
1510
- if (!additionalData)
1511
- return source;
1512
- if (shared.isFunction(additionalData)) {
1513
- return additionalData(source, filename);
1514
- }
1515
- return additionalData + source;
1516
- }
1517
- const processors = {
1518
- less,
1519
- sass,
1520
- scss,
1521
- styl,
1522
- stylus: styl
1523
- };
1524
-
1525
- function compileStyle(options) {
1526
- return doCompileStyle({
1527
- ...options,
1528
- isAsync: false
1529
- });
1530
- }
1531
- function compileStyleAsync(options) {
1532
- return doCompileStyle({ ...options, isAsync: true });
1533
- }
1534
- function doCompileStyle(options) {
1535
- const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
1536
- const preprocessor = preprocessLang && processors[preprocessLang];
1537
- const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
1538
- const map = preProcessedSource
1539
- ? preProcessedSource.map
1540
- : options.inMap || options.map;
1541
- const source = preProcessedSource ? preProcessedSource.code : options.source;
1542
- const shortId = id.replace(/^data-v-/, '');
1543
- const longId = `data-v-${shortId}`;
1544
- const plugins = (postcssPlugins || []).slice();
1545
- plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
1546
- if (trim) {
1547
- plugins.push(trimPlugin());
1548
- }
1549
- if (scoped) {
1550
- plugins.push(scopedPlugin(longId));
1551
- }
1552
- let cssModules;
1553
- if (modules) {
1554
- if (!options.isAsync) {
1555
- throw new Error('[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync().');
1556
- }
1557
- plugins.push(require('postcss-modules')({
1558
- ...modulesOptions,
1559
- getJSON: (_cssFileName, json) => {
1560
- cssModules = json;
1561
- }
1562
- }));
1563
- }
1564
- const postCSSOptions = {
1565
- ...postcssOptions,
1566
- to: filename,
1567
- from: filename
1568
- };
1569
- if (map) {
1570
- postCSSOptions.map = {
1571
- inline: false,
1572
- annotation: false,
1573
- prev: map
1574
- };
1575
- }
1576
- let result;
1577
- let code;
1578
- let outMap;
1579
- // stylus output include plain css. so need remove the repeat item
1580
- const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
1581
- // sass has filename self when provided filename option
1582
- dependencies.delete(filename);
1583
- const errors = [];
1584
- if (preProcessedSource && preProcessedSource.errors.length) {
1585
- errors.push(...preProcessedSource.errors);
1586
- }
1587
- const recordPlainCssDependencies = (messages) => {
1588
- messages.forEach(msg => {
1589
- if (msg.type === 'dependency') {
1590
- // postcss output path is absolute position path
1591
- dependencies.add(msg.file);
1592
- }
1593
- });
1594
- return dependencies;
1595
- };
1596
- try {
1597
- result = postcss__default(plugins).process(source, postCSSOptions);
1598
- // In async mode, return a promise.
1599
- if (options.isAsync) {
1600
- return result
1601
- .then(result => ({
1602
- code: result.css || '',
1603
- map: result.map && result.map.toJSON(),
1604
- errors,
1605
- modules: cssModules,
1606
- rawResult: result,
1607
- dependencies: recordPlainCssDependencies(result.messages)
1608
- }))
1609
- .catch(error => ({
1610
- code: '',
1611
- map: undefined,
1612
- errors: [...errors, error],
1613
- rawResult: undefined,
1614
- dependencies
1615
- }));
1616
- }
1617
- recordPlainCssDependencies(result.messages);
1618
- // force synchronous transform (we know we only have sync plugins)
1619
- code = result.css;
1620
- outMap = result.map;
1621
- }
1622
- catch (e) {
1623
- errors.push(e);
1624
- }
1625
- return {
1626
- code: code || ``,
1627
- map: outMap && outMap.toJSON(),
1628
- errors,
1629
- rawResult: result,
1630
- dependencies
1631
- };
1632
- }
1633
- function preprocess$1(options, preprocessor) {
1634
- return preprocessor(options.source, options.map, {
1635
- filename: options.filename,
1636
- ...options.preprocessOptions
1637
- }, options.preprocessCustomRequire);
1638
- }
1639
-
1640
- const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
1641
- const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
1642
- /**
1643
- * Utility for rewriting `export default` in a script block into a variable
1644
- * declaration so that we can inject things into it
1645
- */
1646
- function rewriteDefault(input, as, parserPlugins) {
1647
- if (!hasDefaultExport(input)) {
1648
- return input + `\nconst ${as} = {}`;
1649
- }
1650
- const replaced = input.replace(defaultExportRE, `$1const ${as} =`);
1651
- if (!hasDefaultExport(replaced)) {
1652
- return replaced;
1653
- }
1654
- // if the script somehow still contains `default export`, it probably has
1655
- // multi-line comments or template strings. fallback to a full parse.
1656
- const s = new MagicString__default(input);
1657
- const ast = parser.parse(input, {
1658
- sourceType: 'module',
1659
- plugins: parserPlugins
1660
- }).program.body;
1661
- ast.forEach(node => {
1662
- if (node.type === 'ExportDefaultDeclaration') {
1663
- s.overwrite(node.start, node.declaration.start, `const ${as} = `);
1664
- }
1665
- if (node.type === 'ExportNamedDeclaration') {
1666
- node.specifiers.forEach(specifier => {
1667
- if (specifier.type === 'ExportSpecifier' &&
1668
- specifier.exported.type === 'Identifier' &&
1669
- specifier.exported.name === 'default') {
1670
- const end = specifier.end;
1671
- s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
1672
- s.append(`\nconst ${as} = ${specifier.local.name}`);
1673
- }
1674
- });
1675
- }
1676
- });
1677
- return s.toString();
1678
- }
1679
- function hasDefaultExport(input) {
1680
- return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
1681
- }
1682
-
1683
- const DEFINE_PROPS = 'defineProps';
1684
- const DEFINE_EMIT = 'defineEmit';
1685
- /**
1686
- * Compile `<script setup>`
1687
- * It requires the whole SFC descriptor because we need to handle and merge
1688
- * normal `<script>` + `<script setup>` if both are present.
1689
- */
1690
- function compileScript(sfc, options) {
1691
- const { script, scriptSetup, source, filename } = sfc;
1692
- if (scriptSetup) {
1693
- warnExperimental(`<script setup>`, 227);
1694
- }
1695
- // for backwards compat
1696
- if (!options) {
1697
- options = { id: '' };
1698
- }
1699
- if (!options.id) {
1700
- warnOnce(`compileScript now requires passing the \`id\` option.\n` +
1701
- `Upgrade your vite or vue-loader version for compatibility with ` +
1702
- `the latest experimental proposals.`);
1703
- }
1704
- const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
1705
- const cssVars = sfc.cssVars;
1706
- const hasInheritAttrsFlag = sfc.template && sfc.template.attrs['inherit-attrs'] === 'false';
1707
- const scriptLang = script && script.lang;
1708
- const scriptSetupLang = scriptSetup && scriptSetup.lang;
1709
- const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts';
1710
- const plugins = [...shared.babelParserDefaultPlugins, 'jsx'];
1711
- if (options.babelParserPlugins)
1712
- plugins.push(...options.babelParserPlugins);
1713
- if (isTS)
1714
- plugins.push('typescript', 'decorators-legacy');
1715
- if (!scriptSetup) {
1716
- if (!script) {
1717
- throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
1718
- }
1719
- if (scriptLang && scriptLang !== 'ts') {
1720
- // do not process non js/ts script blocks
1721
- return script;
1722
- }
1723
- try {
1724
- const scriptAst = parser.parse(script.content, {
1725
- plugins,
1726
- sourceType: 'module'
1727
- }).program.body;
1728
- const bindings = analyzeScriptBindings(scriptAst);
1729
- const needRewrite = cssVars.length || hasInheritAttrsFlag;
1730
- let content = script.content;
1731
- if (needRewrite) {
1732
- content = rewriteDefault(content, `__default__`, plugins);
1733
- if (cssVars.length) {
1734
- content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
1735
- }
1736
- if (hasInheritAttrsFlag) {
1737
- content += `__default__.inheritAttrs = false`;
1738
- }
1739
- content += `\nexport default __default__`;
1740
- }
1741
- return {
1742
- ...script,
1743
- content,
1744
- bindings,
1745
- scriptAst
1746
- };
1747
- }
1748
- catch (e) {
1749
- // silently fallback if parse fails since user may be using custom
1750
- // babel syntax
1751
- return script;
1752
- }
1753
- }
1754
- if (script && scriptLang !== scriptSetupLang) {
1755
- throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`);
1756
- }
1757
- if (scriptSetupLang && scriptSetupLang !== 'ts') {
1758
- // do not process non js/ts script blocks
1759
- return scriptSetup;
1760
- }
1761
- const defaultTempVar = `__default__`;
1762
- const bindingMetadata = {};
1763
- const helperImports = new Set();
1764
- const userImports = Object.create(null);
1765
- const userImportAlias = Object.create(null);
1766
- const setupBindings = Object.create(null);
1767
- const refBindings = Object.create(null);
1768
- const refIdentifiers = new Set();
1769
- const enableRefSugar = options.refSugar !== false;
1770
- let defaultExport;
1771
- let hasDefinePropsCall = false;
1772
- let hasDefineEmitCall = false;
1773
- let propsRuntimeDecl;
1774
- let propsTypeDecl;
1775
- let propsIdentifier;
1776
- let emitRuntimeDecl;
1777
- let emitTypeDecl;
1778
- let emitIdentifier;
1779
- let hasAwait = false;
1780
- let hasInlinedSsrRenderFn = false;
1781
- // props/emits declared via types
1782
- const typeDeclaredProps = {};
1783
- const typeDeclaredEmits = new Set();
1784
- // record declared types for runtime props type generation
1785
- const declaredTypes = {};
1786
- // magic-string state
1787
- const s = new MagicString__default(source);
1788
- const startOffset = scriptSetup.loc.start.offset;
1789
- const endOffset = scriptSetup.loc.end.offset;
1790
- const scriptStartOffset = script && script.loc.start.offset;
1791
- const scriptEndOffset = script && script.loc.end.offset;
1792
- function helper(key) {
1793
- helperImports.add(key);
1794
- return `_${key}`;
1795
- }
1796
- function parse(input, options, offset) {
1797
- try {
1798
- return parser.parse(input, options).program.body;
1799
- }
1800
- catch (e) {
1801
- e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
1802
- throw e;
1803
- }
1804
- }
1805
- function error(msg, node, end = node.end + startOffset) {
1806
- throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, node.start + startOffset, end)}`);
1807
- }
1808
- function registerUserImport(source, local, imported, isType) {
1809
- if (source === 'vue' && imported) {
1810
- userImportAlias[imported] = local;
1811
- }
1812
- userImports[local] = {
1813
- isType,
1814
- imported: imported || 'default',
1815
- source
1816
- };
1817
- }
1818
- function processDefineProps(node) {
1819
- if (isCallOf(node, DEFINE_PROPS)) {
1820
- if (hasDefinePropsCall) {
1821
- error(`duplicate ${DEFINE_PROPS}() call`, node);
1822
- }
1823
- hasDefinePropsCall = true;
1824
- propsRuntimeDecl = node.arguments[0];
1825
- // context call has type parameters - infer runtime types from it
1826
- if (node.typeParameters) {
1827
- if (propsRuntimeDecl) {
1828
- error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
1829
- `at the same time. Use one or the other.`, node);
1830
- }
1831
- const typeArg = node.typeParameters.params[0];
1832
- if (typeArg.type === 'TSTypeLiteral') {
1833
- propsTypeDecl = typeArg;
1834
- }
1835
- else {
1836
- error(`type argument passed to ${DEFINE_PROPS}() must be a literal type.`, typeArg);
1837
- }
1838
- }
1839
- return true;
1840
- }
1841
- return false;
1842
- }
1843
- function processDefineEmit(node) {
1844
- if (isCallOf(node, DEFINE_EMIT)) {
1845
- if (hasDefineEmitCall) {
1846
- error(`duplicate ${DEFINE_EMIT}() call`, node);
1847
- }
1848
- hasDefineEmitCall = true;
1849
- emitRuntimeDecl = node.arguments[0];
1850
- if (node.typeParameters) {
1851
- if (emitRuntimeDecl) {
1852
- error(`${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
1853
- `at the same time. Use one or the other.`, node);
1854
- }
1855
- const typeArg = node.typeParameters.params[0];
1856
- if (typeArg.type === 'TSFunctionType' ||
1857
- typeArg.type === 'TSUnionType') {
1858
- emitTypeDecl = typeArg;
1859
- }
1860
- else {
1861
- error(`type argument passed to ${DEFINE_EMIT}() must be a function type ` +
1862
- `or a union of function types.`, typeArg);
1863
- }
1864
- }
1865
- return true;
1866
- }
1867
- return false;
1868
- }
1869
- function checkInvalidScopeReference(node, method) {
1870
- if (!node)
1871
- return;
1872
- walkIdentifiers(node, id => {
1873
- if (setupBindings[id.name]) {
1874
- error(`\`${method}()\` in <script setup> cannot reference locally ` +
1875
- `declared variables because it will be hoisted outside of the ` +
1876
- `setup() function. If your component options requires initialization ` +
1877
- `in the module scope, use a separate normal <script> to export ` +
1878
- `the options instead.`, id);
1879
- }
1880
- });
1881
- }
1882
- function processRefExpression(exp, statement) {
1883
- if (exp.type === 'AssignmentExpression') {
1884
- const { left, right } = exp;
1885
- if (left.type === 'Identifier') {
1886
- registerRefBinding(left);
1887
- s.prependRight(right.start + startOffset, `${helper('ref')}(`);
1888
- s.appendLeft(right.end + startOffset, ')');
1889
- }
1890
- else if (left.type === 'ObjectPattern') {
1891
- // remove wrapping parens
1892
- for (let i = left.start; i > 0; i--) {
1893
- const char = source[i + startOffset];
1894
- if (char === '(') {
1895
- s.remove(i + startOffset, i + startOffset + 1);
1896
- break;
1897
- }
1898
- }
1899
- for (let i = left.end; i > 0; i++) {
1900
- const char = source[i + startOffset];
1901
- if (char === ')') {
1902
- s.remove(i + startOffset, i + startOffset + 1);
1903
- break;
1904
- }
1905
- }
1906
- processRefObjectPattern(left, statement);
1907
- }
1908
- else if (left.type === 'ArrayPattern') {
1909
- processRefArrayPattern(left, statement);
1910
- }
1911
- }
1912
- else if (exp.type === 'SequenceExpression') {
1913
- // possible multiple declarations
1914
- // ref: x = 1, y = 2
1915
- exp.expressions.forEach(e => processRefExpression(e, statement));
1916
- }
1917
- else if (exp.type === 'Identifier') {
1918
- registerRefBinding(exp);
1919
- s.appendLeft(exp.end + startOffset, ` = ${helper('ref')}()`);
1920
- }
1921
- else {
1922
- error(`ref: statements can only contain assignment expressions.`, exp);
1923
- }
1924
- }
1925
- function registerRefBinding(id) {
1926
- if (id.name[0] === '$') {
1927
- error(`ref variable identifiers cannot start with $.`, id);
1928
- }
1929
- refBindings[id.name] = setupBindings[id.name] = "setup-ref" /* SETUP_REF */;
1930
- refIdentifiers.add(id);
1931
- }
1932
- function processRefObjectPattern(pattern, statement) {
1933
- for (const p of pattern.properties) {
1934
- let nameId;
1935
- if (p.type === 'ObjectProperty') {
1936
- if (p.key.start === p.value.start) {
1937
- // shorthand { foo } --> { foo: __foo }
1938
- nameId = p.key;
1939
- s.appendLeft(nameId.end + startOffset, `: __${nameId.name}`);
1940
- if (p.value.type === 'AssignmentPattern') {
1941
- // { foo = 1 }
1942
- refIdentifiers.add(p.value.left);
1943
- }
1944
- }
1945
- else {
1946
- if (p.value.type === 'Identifier') {
1947
- // { foo: bar } --> { foo: __bar }
1948
- nameId = p.value;
1949
- s.prependRight(nameId.start + startOffset, `__`);
1950
- }
1951
- else if (p.value.type === 'ObjectPattern') {
1952
- processRefObjectPattern(p.value, statement);
1953
- }
1954
- else if (p.value.type === 'ArrayPattern') {
1955
- processRefArrayPattern(p.value, statement);
1956
- }
1957
- else if (p.value.type === 'AssignmentPattern') {
1958
- // { foo: bar = 1 } --> { foo: __bar = 1 }
1959
- nameId = p.value.left;
1960
- s.prependRight(nameId.start + startOffset, `__`);
1961
- }
1962
- }
1963
- }
1964
- else {
1965
- // rest element { ...foo } --> { ...__foo }
1966
- nameId = p.argument;
1967
- s.prependRight(nameId.start + startOffset, `__`);
1968
- }
1969
- if (nameId) {
1970
- registerRefBinding(nameId);
1971
- // append binding declarations after the parent statement
1972
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
1973
- }
1974
- }
1975
- }
1976
- function processRefArrayPattern(pattern, statement) {
1977
- for (const e of pattern.elements) {
1978
- if (!e)
1979
- continue;
1980
- let nameId;
1981
- if (e.type === 'Identifier') {
1982
- // [a] --> [__a]
1983
- nameId = e;
1984
- }
1985
- else if (e.type === 'AssignmentPattern') {
1986
- // [a = 1] --> [__a = 1]
1987
- nameId = e.left;
1988
- }
1989
- else if (e.type === 'RestElement') {
1990
- // [...a] --> [...__a]
1991
- nameId = e.argument;
1992
- }
1993
- else if (e.type === 'ObjectPattern') {
1994
- processRefObjectPattern(e, statement);
1995
- }
1996
- else if (e.type === 'ArrayPattern') {
1997
- processRefArrayPattern(e, statement);
1998
- }
1999
- if (nameId) {
2000
- registerRefBinding(nameId);
2001
- // prefix original
2002
- s.prependRight(nameId.start + startOffset, `__`);
2003
- // append binding declarations after the parent statement
2004
- s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
2005
- }
2006
- }
2007
- }
2008
- // 1. process normal <script> first if it exists
2009
- let scriptAst;
2010
- if (script) {
2011
- // import dedupe between <script> and <script setup>
2012
- scriptAst = parse(script.content, {
2013
- plugins,
2014
- sourceType: 'module'
2015
- }, scriptStartOffset);
2016
- for (const node of scriptAst) {
2017
- if (node.type === 'ImportDeclaration') {
2018
- // record imports for dedupe
2019
- for (const specifier of node.specifiers) {
2020
- const imported = specifier.type === 'ImportSpecifier' &&
2021
- specifier.imported.type === 'Identifier' &&
2022
- specifier.imported.name;
2023
- registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type');
2024
- }
2025
- }
2026
- else if (node.type === 'ExportDefaultDeclaration') {
2027
- // export default
2028
- defaultExport = node;
2029
- const start = node.start + scriptStartOffset;
2030
- s.overwrite(start, start + `export default`.length, `const ${defaultTempVar} =`);
2031
- }
2032
- else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
2033
- const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
2034
- if (defaultSpecifier) {
2035
- defaultExport = node;
2036
- // 1. remove specifier
2037
- if (node.specifiers.length > 1) {
2038
- s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
2039
- }
2040
- else {
2041
- s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
2042
- }
2043
- if (node.source) {
2044
- // export { x as default } from './x'
2045
- // rewrite to `import { x as __default__ } from './x'` and
2046
- // add to top
2047
- s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
2048
- }
2049
- else {
2050
- // export { x as default }
2051
- // rewrite to `const __default__ = x` and move to end
2052
- s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
2053
- }
2054
- }
2055
- }
2056
- }
2057
- }
2058
- // 2. parse <script setup> and walk over top level statements
2059
- const scriptSetupAst = parse(scriptSetup.content, {
2060
- plugins: [
2061
- ...plugins,
2062
- // allow top level await but only inside <script setup>
2063
- 'topLevelAwait'
2064
- ],
2065
- sourceType: 'module'
2066
- }, startOffset);
2067
- for (const node of scriptSetupAst) {
2068
- const start = node.start + startOffset;
2069
- let end = node.end + startOffset;
2070
- // import or type declarations: move to top
2071
- // locate comment
2072
- if (node.trailingComments && node.trailingComments.length > 0) {
2073
- const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
2074
- end = lastCommentNode.end + startOffset;
2075
- }
2076
- // locate the end of whitespace between this statement and the next
2077
- while (end <= source.length) {
2078
- if (!/\s/.test(source.charAt(end))) {
2079
- break;
2080
- }
2081
- end++;
2082
- }
2083
- // process `ref: x` bindings (convert to refs)
2084
- if (node.type === 'LabeledStatement' &&
2085
- node.label.name === 'ref' &&
2086
- node.body.type === 'ExpressionStatement') {
2087
- if (enableRefSugar) {
2088
- warnExperimental(`ref: sugar`, 228);
2089
- s.overwrite(node.label.start + startOffset, node.body.start + startOffset, 'const ');
2090
- processRefExpression(node.body.expression, node);
2091
- }
2092
- else {
2093
- // TODO if we end up shipping ref: sugar as an opt-in feature,
2094
- // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
2095
- error(`ref: sugar needs to be explicitly enabled via vite or vue-loader options.`, node);
2096
- }
2097
- }
2098
- if (node.type === 'ImportDeclaration') {
2099
- // import declarations are moved to top
2100
- s.move(start, end, 0);
2101
- // dedupe imports
2102
- let removed = 0;
2103
- let prev, next;
2104
- const removeSpecifier = (node) => {
2105
- removed++;
2106
- s.remove(prev ? prev.end + startOffset : node.start + startOffset, next && !prev ? next.start + startOffset : node.end + startOffset);
2107
- };
2108
- for (let i = 0; i < node.specifiers.length; i++) {
2109
- const specifier = node.specifiers[i];
2110
- prev = node.specifiers[i - 1];
2111
- next = node.specifiers[i + 1];
2112
- const local = specifier.local.name;
2113
- const imported = specifier.type === 'ImportSpecifier' &&
2114
- specifier.imported.type === 'Identifier' &&
2115
- specifier.imported.name;
2116
- const source = node.source.value;
2117
- const existing = userImports[local];
2118
- if (source === 'vue' &&
2119
- (imported === DEFINE_PROPS || imported === DEFINE_EMIT)) {
2120
- removeSpecifier(specifier);
2121
- }
2122
- else if (existing) {
2123
- if (existing.source === source && existing.imported === imported) {
2124
- // already imported in <script setup>, dedupe
2125
- removeSpecifier(specifier);
2126
- }
2127
- else {
2128
- error(`different imports aliased to same local name.`, specifier);
2129
- }
2130
- }
2131
- else {
2132
- registerUserImport(source, local, imported, node.importKind === 'type');
2133
- }
2134
- }
2135
- if (node.specifiers.length && removed === node.specifiers.length) {
2136
- s.remove(node.start + startOffset, node.end + startOffset);
2137
- }
2138
- }
2139
- // process `defineProps` and `defineEmit` calls
2140
- if (node.type === 'ExpressionStatement' &&
2141
- (processDefineProps(node.expression) ||
2142
- processDefineEmit(node.expression))) {
2143
- s.remove(node.start + startOffset, node.end + startOffset);
2144
- }
2145
- if (node.type === 'VariableDeclaration' && !node.declare) {
2146
- for (const decl of node.declarations) {
2147
- if (decl.init) {
2148
- const isDefineProps = processDefineProps(decl.init);
2149
- if (isDefineProps) {
2150
- propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
2151
- }
2152
- const isDefineEmit = processDefineEmit(decl.init);
2153
- if (isDefineEmit) {
2154
- emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
2155
- }
2156
- if (isDefineProps || isDefineEmit)
2157
- if (node.declarations.length === 1) {
2158
- s.remove(node.start + startOffset, node.end + startOffset);
2159
- }
2160
- else {
2161
- s.remove(decl.start + startOffset, decl.end + startOffset);
2162
- }
2163
- }
2164
- }
2165
- }
2166
- // walk decalrations to record declared bindings
2167
- if ((node.type === 'VariableDeclaration' ||
2168
- node.type === 'FunctionDeclaration' ||
2169
- node.type === 'ClassDeclaration') &&
2170
- !node.declare) {
2171
- walkDeclaration(node, setupBindings, userImportAlias);
2172
- }
2173
- // Type declarations
2174
- if (node.type === 'VariableDeclaration' && node.declare) {
2175
- s.remove(start, end);
2176
- }
2177
- // move all type declarations to outer scope
2178
- if (node.type.startsWith('TS') ||
2179
- (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')) {
2180
- recordType(node, declaredTypes);
2181
- s.move(start, end, 0);
2182
- }
2183
- // walk statements & named exports / variable declarations for top level
2184
- // await
2185
- if ((node.type === 'VariableDeclaration' && !node.declare) ||
2186
- node.type.endsWith('Statement')) {
2187
- estreeWalker.walk(node, {
2188
- enter(node) {
2189
- if (isFunction(node)) {
2190
- this.skip();
2191
- }
2192
- if (node.type === 'AwaitExpression') {
2193
- hasAwait = true;
2194
- }
2195
- }
2196
- });
2197
- }
2198
- if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
2199
- node.type === 'ExportAllDeclaration' ||
2200
- node.type === 'ExportDefaultDeclaration') {
2201
- error(`<script setup> cannot contain ES module exports. ` +
2202
- `If you are using a previous version of <script setup>, please ` +
2203
- `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
2204
- }
2205
- }
2206
- // 3. Do a full walk to rewrite identifiers referencing let exports with ref
2207
- // value access
2208
- if (enableRefSugar && Object.keys(refBindings).length) {
2209
- for (const node of scriptSetupAst) {
2210
- if (node.type !== 'ImportDeclaration') {
2211
- walkIdentifiers(node, (id, parent) => {
2212
- if (refBindings[id.name] && !refIdentifiers.has(id)) {
2213
- if (isStaticProperty(parent) && parent.shorthand) {
2214
- // let binding used in a property shorthand
2215
- // { foo } -> { foo: foo.value }
2216
- // skip for destructure patterns
2217
- if (!parent.inPattern ||
2218
- isInDestructureAssignment(parent, parentStack)) {
2219
- s.appendLeft(id.end + startOffset, `: ${id.name}.value`);
2220
- }
2221
- }
2222
- else {
2223
- s.appendLeft(id.end + startOffset, '.value');
2224
- }
2225
- }
2226
- else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
2227
- // $xxx raw ref access variables, remove the $ prefix
2228
- s.remove(id.start + startOffset, id.start + startOffset + 1);
2229
- }
2230
- });
2231
- }
2232
- }
2233
- }
2234
- // 4. extract runtime props/emits code from setup context type
2235
- if (propsTypeDecl) {
2236
- extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
2237
- }
2238
- if (emitTypeDecl) {
2239
- extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits);
2240
- }
2241
- // 5. check useOptions args to make sure it doesn't reference setup scope
2242
- // variables
2243
- checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
2244
- checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS);
2245
- // 6. remove non-script content
2246
- if (script) {
2247
- if (startOffset < scriptStartOffset) {
2248
- // <script setup> before <script>
2249
- s.remove(0, startOffset);
2250
- s.remove(endOffset, scriptStartOffset);
2251
- s.remove(scriptEndOffset, source.length);
2252
- }
2253
- else {
2254
- // <script> before <script setup>
2255
- s.remove(0, scriptStartOffset);
2256
- s.remove(scriptEndOffset, startOffset);
2257
- s.remove(endOffset, source.length);
2258
- }
2259
- }
2260
- else {
2261
- // only <script setup>
2262
- s.remove(0, startOffset);
2263
- s.remove(endOffset, source.length);
2264
- }
2265
- // 7. analyze binding metadata
2266
- if (scriptAst) {
2267
- Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst));
2268
- }
2269
- if (propsRuntimeDecl) {
2270
- for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
2271
- bindingMetadata[key] = "props" /* PROPS */;
2272
- }
2273
- }
2274
- for (const key in typeDeclaredProps) {
2275
- bindingMetadata[key] = "props" /* PROPS */;
2276
- }
2277
- for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
2278
- if (isType)
2279
- continue;
2280
- bindingMetadata[key] =
2281
- (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
2282
- ? "setup-const" /* SETUP_CONST */
2283
- : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
2284
- }
2285
- for (const key in setupBindings) {
2286
- bindingMetadata[key] = setupBindings[key];
2287
- }
2288
- // 8. inject `useCssVars` calls
2289
- if (cssVars.length) {
2290
- helperImports.add(CSS_VARS_HELPER);
2291
- helperImports.add('unref');
2292
- s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
2293
- }
2294
- // 9. finalize setup() argument signature
2295
- let args = `__props`;
2296
- if (propsTypeDecl) {
2297
- args += `: ${scriptSetup.content.slice(propsTypeDecl.start, propsTypeDecl.end)}`;
2298
- }
2299
- // inject user assignment of props
2300
- // we use a default __props so that template expressions referencing props
2301
- // can use it directly
2302
- if (propsIdentifier) {
2303
- s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`);
2304
- }
2305
- if (emitIdentifier) {
2306
- args +=
2307
- emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`;
2308
- if (emitTypeDecl) {
2309
- args += `: {
2310
- emit: (${scriptSetup.content.slice(emitTypeDecl.start, emitTypeDecl.end)}),
2311
- slots: any,
2312
- attrs: any
2313
- }`;
2314
- }
2315
- }
2316
- // 10. generate return statement
2317
- let returned;
2318
- if (options.inlineTemplate) {
2319
- if (sfc.template && !sfc.template.src) {
2320
- if (options.templateOptions && options.templateOptions.ssr) {
2321
- hasInlinedSsrRenderFn = true;
2322
- }
2323
- // inline render function mode - we are going to compile the template and
2324
- // inline it right here
2325
- const { code, ast, preamble, tips, errors } = compileTemplate({
2326
- filename,
2327
- source: sfc.template.content,
2328
- inMap: sfc.template.map,
2329
- ...options.templateOptions,
2330
- id: scopeId,
2331
- scoped: sfc.styles.some(s => s.scoped),
2332
- isProd: options.isProd,
2333
- ssrCssVars: sfc.cssVars,
2334
- compilerOptions: {
2335
- ...(options.templateOptions &&
2336
- options.templateOptions.compilerOptions),
2337
- inline: true,
2338
- isTS,
2339
- bindingMetadata
2340
- }
2341
- });
2342
- if (tips.length) {
2343
- tips.forEach(warnOnce);
2344
- }
2345
- const err = errors[0];
2346
- if (typeof err === 'string') {
2347
- throw new Error(err);
2348
- }
2349
- else if (err) {
2350
- if (err.loc) {
2351
- err.message +=
2352
- `\n\n` +
2353
- sfc.filename +
2354
- '\n' +
2355
- shared.generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
2356
- `\n`;
2357
- }
2358
- throw err;
2359
- }
2360
- if (preamble) {
2361
- s.prepend(preamble);
2362
- }
2363
- // avoid duplicated unref import
2364
- // as this may get injected by the render function preamble OR the
2365
- // css vars codegen
2366
- if (ast && ast.helpers.includes(compilerCore.UNREF)) {
2367
- helperImports.delete('unref');
2368
- }
2369
- returned = code;
2370
- }
2371
- else {
2372
- returned = `() => {}`;
2373
- }
2374
- }
2375
- else {
2376
- // return bindings from setup
2377
- const allBindings = { ...setupBindings };
2378
- for (const key in userImports) {
2379
- if (!userImports[key].isType) {
2380
- allBindings[key] = true;
2381
- }
2382
- }
2383
- returned = `{ ${Object.keys(allBindings).join(', ')} }`;
2384
- }
2385
- s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
2386
- // 11. finalize default export
2387
- // expose: [] makes <script setup> components "closed" by default.
2388
- let runtimeOptions = `\n expose: [],`;
2389
- if (hasInheritAttrsFlag) {
2390
- runtimeOptions += `\n inheritAttrs: false,`;
2391
- }
2392
- if (hasInlinedSsrRenderFn) {
2393
- runtimeOptions += `\n __ssrInlineRender: true,`;
2394
- }
2395
- if (propsRuntimeDecl) {
2396
- runtimeOptions += `\n props: ${scriptSetup.content
2397
- .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
2398
- .trim()},`;
2399
- }
2400
- else if (propsTypeDecl) {
2401
- runtimeOptions += genRuntimeProps(typeDeclaredProps);
2402
- }
2403
- if (emitRuntimeDecl) {
2404
- runtimeOptions += `\n emits: ${scriptSetup.content
2405
- .slice(emitRuntimeDecl.start, emitRuntimeDecl.end)
2406
- .trim()},`;
2407
- }
2408
- else if (emitTypeDecl) {
2409
- runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
2410
- }
2411
- if (isTS) {
2412
- // for TS, make sure the exported type is still valid type with
2413
- // correct props information
2414
- // we have to use object spread for types to be merged properly
2415
- // user's TS setting should compile it down to proper targets
2416
- const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
2417
- // wrap setup code with function.
2418
- // export the content of <script setup> as a named export, `setup`.
2419
- // this allows `import { setup } from '*.vue'` for testing purposes.
2420
- s.prependLeft(startOffset, `\nexport default ${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n`);
2421
- s.appendRight(endOffset, `})`);
2422
- }
2423
- else {
2424
- if (defaultExport) {
2425
- // can't rely on spread operator in non ts mode
2426
- s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
2427
- s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
2428
- }
2429
- else {
2430
- s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
2431
- `${hasAwait ? `async ` : ``}setup(${args}) {\n`);
2432
- s.appendRight(endOffset, `}`);
2433
- }
2434
- }
2435
- // 12. finalize Vue helper imports
2436
- if (helperImports.size > 0) {
2437
- s.prepend(`import { ${[...helperImports]
2438
- .map(h => `${h} as _${h}`)
2439
- .join(', ')} } from 'vue'\n`);
2440
- }
2441
- s.trim();
2442
- return {
2443
- ...scriptSetup,
2444
- bindings: bindingMetadata,
2445
- content: s.toString(),
2446
- map: s.generateMap({
2447
- source: filename,
2448
- hires: true,
2449
- includeContent: true
2450
- }),
2451
- scriptAst,
2452
- scriptSetupAst
2453
- };
2454
- }
2455
- function walkDeclaration(node, bindings, userImportAlias) {
2456
- if (node.type === 'VariableDeclaration') {
2457
- const isConst = node.kind === 'const';
2458
- // export const foo = ...
2459
- for (const { id, init } of node.declarations) {
2460
- const isDefineCall = !!(isConst &&
2461
- (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT)));
2462
- if (id.type === 'Identifier') {
2463
- let bindingType;
2464
- if (
2465
- // if a declaration is a const literal, we can mark it so that
2466
- // the generated render fn code doesn't need to unref() it
2467
- isDefineCall ||
2468
- (isConst &&
2469
- canNeverBeRef(init, userImportAlias['reactive'] || 'reactive'))) {
2470
- bindingType = "setup-const" /* SETUP_CONST */;
2471
- }
2472
- else if (isConst) {
2473
- if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
2474
- bindingType = "setup-ref" /* SETUP_REF */;
2475
- }
2476
- else {
2477
- bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
2478
- }
2479
- }
2480
- else {
2481
- bindingType = "setup-let" /* SETUP_LET */;
2482
- }
2483
- bindings[id.name] = bindingType;
2484
- }
2485
- else if (id.type === 'ObjectPattern') {
2486
- walkObjectPattern(id, bindings, isConst, isDefineCall);
2487
- }
2488
- else if (id.type === 'ArrayPattern') {
2489
- walkArrayPattern(id, bindings, isConst, isDefineCall);
2490
- }
2491
- }
2492
- }
2493
- else if (node.type === 'FunctionDeclaration' ||
2494
- node.type === 'ClassDeclaration') {
2495
- // export function foo() {} / export class Foo {}
2496
- // export declarations must be named.
2497
- bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
2498
- }
2499
- }
2500
- function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
2501
- for (const p of node.properties) {
2502
- if (p.type === 'ObjectProperty') {
2503
- // key can only be Identifier in ObjectPattern
2504
- if (p.key.type === 'Identifier') {
2505
- if (p.key === p.value) {
2506
- // const { x } = ...
2507
- bindings[p.key.name] = isDefineCall
2508
- ? "setup-const" /* SETUP_CONST */
2509
- : isConst
2510
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2511
- : "setup-let" /* SETUP_LET */;
2512
- }
2513
- else {
2514
- walkPattern(p.value, bindings, isConst, isDefineCall);
2515
- }
2516
- }
2517
- }
2518
- else {
2519
- // ...rest
2520
- // argument can only be identifer when destructuring
2521
- bindings[p.argument.name] = isConst
2522
- ? "setup-const" /* SETUP_CONST */
2523
- : "setup-let" /* SETUP_LET */;
2524
- }
2525
- }
2526
- }
2527
- function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
2528
- for (const e of node.elements) {
2529
- e && walkPattern(e, bindings, isConst, isDefineCall);
2530
- }
2531
- }
2532
- function walkPattern(node, bindings, isConst, isDefineCall = false) {
2533
- if (node.type === 'Identifier') {
2534
- bindings[node.name] = isDefineCall
2535
- ? "setup-const" /* SETUP_CONST */
2536
- : isConst
2537
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2538
- : "setup-let" /* SETUP_LET */;
2539
- }
2540
- else if (node.type === 'RestElement') {
2541
- // argument can only be identifer when destructuring
2542
- bindings[node.argument.name] = isConst
2543
- ? "setup-const" /* SETUP_CONST */
2544
- : "setup-let" /* SETUP_LET */;
2545
- }
2546
- else if (node.type === 'ObjectPattern') {
2547
- walkObjectPattern(node, bindings, isConst);
2548
- }
2549
- else if (node.type === 'ArrayPattern') {
2550
- walkArrayPattern(node, bindings, isConst);
2551
- }
2552
- else if (node.type === 'AssignmentPattern') {
2553
- if (node.left.type === 'Identifier') {
2554
- bindings[node.left.name] = isDefineCall
2555
- ? "setup-const" /* SETUP_CONST */
2556
- : isConst
2557
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2558
- : "setup-let" /* SETUP_LET */;
2559
- }
2560
- else {
2561
- walkPattern(node.left, bindings, isConst);
2562
- }
2563
- }
2564
- }
2565
- function recordType(node, declaredTypes) {
2566
- if (node.type === 'TSInterfaceDeclaration') {
2567
- declaredTypes[node.id.name] = [`Object`];
2568
- }
2569
- else if (node.type === 'TSTypeAliasDeclaration') {
2570
- declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
2571
- }
2572
- else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
2573
- recordType(node.declaration, declaredTypes);
2574
- }
2575
- }
2576
- function extractRuntimeProps(node, props, declaredTypes) {
2577
- for (const m of node.members) {
2578
- if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
2579
- props[m.key.name] = {
2580
- key: m.key.name,
2581
- required: !m.optional,
2582
- type: m.typeAnnotation
2583
- ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
2584
- : [`null`]
2585
- };
2586
- }
2587
- }
2588
- }
2589
- function inferRuntimeType(node, declaredTypes) {
2590
- switch (node.type) {
2591
- case 'TSStringKeyword':
2592
- return ['String'];
2593
- case 'TSNumberKeyword':
2594
- return ['Number'];
2595
- case 'TSBooleanKeyword':
2596
- return ['Boolean'];
2597
- case 'TSObjectKeyword':
2598
- return ['Object'];
2599
- case 'TSTypeLiteral':
2600
- // TODO (nice to have) generate runtime property validation
2601
- return ['Object'];
2602
- case 'TSFunctionType':
2603
- return ['Function'];
2604
- case 'TSArrayType':
2605
- case 'TSTupleType':
2606
- // TODO (nice to have) generate runtime element type/length checks
2607
- return ['Array'];
2608
- case 'TSLiteralType':
2609
- switch (node.literal.type) {
2610
- case 'StringLiteral':
2611
- return ['String'];
2612
- case 'BooleanLiteral':
2613
- return ['Boolean'];
2614
- case 'NumericLiteral':
2615
- case 'BigIntLiteral':
2616
- return ['Number'];
2617
- default:
2618
- return [`null`];
2619
- }
2620
- case 'TSTypeReference':
2621
- if (node.typeName.type === 'Identifier') {
2622
- if (declaredTypes[node.typeName.name]) {
2623
- return declaredTypes[node.typeName.name];
2624
- }
2625
- switch (node.typeName.name) {
2626
- case 'Array':
2627
- case 'Function':
2628
- case 'Object':
2629
- case 'Set':
2630
- case 'Map':
2631
- case 'WeakSet':
2632
- case 'WeakMap':
2633
- return [node.typeName.name];
2634
- case 'Record':
2635
- case 'Partial':
2636
- case 'Readonly':
2637
- case 'Pick':
2638
- case 'Omit':
2639
- case 'Exclude':
2640
- case 'Extract':
2641
- case 'Required':
2642
- case 'InstanceType':
2643
- return ['Object'];
2644
- }
2645
- }
2646
- return [`null`];
2647
- case 'TSUnionType':
2648
- return [
2649
- ...new Set([].concat(node.types.map(t => inferRuntimeType(t, declaredTypes))))
2650
- ];
2651
- case 'TSIntersectionType':
2652
- return ['Object'];
2653
- default:
2654
- return [`null`]; // no runtime check
2655
- }
2656
- }
2657
- function genRuntimeProps(props) {
2658
- const keys = Object.keys(props);
2659
- if (!keys.length) {
2660
- return ``;
2661
- }
2662
- return `\n props: {\n ${keys
2663
- .map(key => {
2664
- const { type, required } = props[key];
2665
- return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required} }`;
2666
- })
2667
- .join(',\n ')}\n } as unknown as undefined,`;
2668
- }
2669
- function toRuntimeTypeString(types) {
2670
- return types.some(t => t === 'null')
2671
- ? `null`
2672
- : types.length > 1
2673
- ? `[${types.join(', ')}]`
2674
- : types[0];
2675
- }
2676
- function extractRuntimeEmits(node, emits) {
2677
- if (node.type === 'TSUnionType') {
2678
- for (let t of node.types) {
2679
- if (t.type === 'TSParenthesizedType')
2680
- t = t.typeAnnotation;
2681
- if (t.type === 'TSFunctionType') {
2682
- extractRuntimeEmits(t, emits);
2683
- }
2684
- }
2685
- return;
2686
- }
2687
- const eventName = node.parameters[0];
2688
- if (eventName.type === 'Identifier' &&
2689
- eventName.typeAnnotation &&
2690
- eventName.typeAnnotation.type === 'TSTypeAnnotation') {
2691
- const typeNode = eventName.typeAnnotation.typeAnnotation;
2692
- if (typeNode.type === 'TSLiteralType') {
2693
- emits.add(String(typeNode.literal.value));
2694
- }
2695
- else if (typeNode.type === 'TSUnionType') {
2696
- for (const t of typeNode.types) {
2697
- if (t.type === 'TSLiteralType') {
2698
- emits.add(String(t.literal.value));
2699
- }
2700
- }
2701
- }
2702
- }
2703
- }
2704
- function genRuntimeEmits(emits) {
2705
- return emits.size
2706
- ? `\n emits: [${Array.from(emits)
2707
- .map(p => JSON.stringify(p))
2708
- .join(', ')}] as unknown as undefined,`
2709
- : ``;
2710
- }
2711
- const parentStack = [];
2712
- /**
2713
- * Walk an AST and find identifiers that are variable references.
2714
- * This is largely the same logic with `transformExpressions` in compiler-core
2715
- * but with some subtle differences as this needs to handle a wider range of
2716
- * possible syntax.
2717
- */
2718
- function walkIdentifiers(root, onIdentifier) {
2719
- const knownIds = Object.create(null);
2720
- estreeWalker.walk(root, {
2721
- enter(node, parent) {
2722
- parent && parentStack.push(parent);
2723
- if (node.type === 'Identifier') {
2724
- if (!knownIds[node.name] && isRefIdentifier(node, parent)) {
2725
- onIdentifier(node, parent);
2726
- }
2727
- }
2728
- else if (isFunction(node)) {
2729
- // walk function expressions and add its arguments to known identifiers
2730
- // so that we don't prefix them
2731
- node.params.forEach(p => estreeWalker.walk(p, {
2732
- enter(child, parent) {
2733
- if (child.type === 'Identifier' &&
2734
- // do not record as scope variable if is a destructured key
2735
- !isStaticPropertyKey(child, parent) &&
2736
- // do not record if this is a default value
2737
- // assignment of a destructured variable
2738
- !(parent &&
2739
- parent.type === 'AssignmentPattern' &&
2740
- parent.right === child)) {
2741
- const { name } = child;
2742
- if (node.scopeIds && node.scopeIds.has(name)) {
2743
- return;
2744
- }
2745
- if (name in knownIds) {
2746
- knownIds[name]++;
2747
- }
2748
- else {
2749
- knownIds[name] = 1;
2750
- }
2751
- (node.scopeIds || (node.scopeIds = new Set())).add(name);
2752
- }
2753
- }
2754
- }));
2755
- }
2756
- else if (node.type === 'ObjectProperty' &&
2757
- parent.type === 'ObjectPattern') {
2758
- node.inPattern = true;
2759
- }
2760
- },
2761
- leave(node, parent) {
2762
- parent && parentStack.pop();
2763
- if (node.scopeIds) {
2764
- node.scopeIds.forEach((id) => {
2765
- knownIds[id]--;
2766
- if (knownIds[id] === 0) {
2767
- delete knownIds[id];
2768
- }
2769
- });
2770
- }
2771
- }
2772
- });
2773
- }
2774
- function isRefIdentifier(id, parent) {
2775
- // declaration id
2776
- if ((parent.type === 'VariableDeclarator' ||
2777
- parent.type === 'ClassDeclaration') &&
2778
- parent.id === id) {
2779
- return false;
2780
- }
2781
- if (isFunction(parent)) {
2782
- // function decalration/expression id
2783
- if (parent.id === id) {
2784
- return false;
2785
- }
2786
- // params list
2787
- if (parent.params.includes(id)) {
2788
- return false;
2789
- }
2790
- }
2791
- // property key
2792
- // this also covers object destructure pattern
2793
- if (isStaticPropertyKey(id, parent)) {
2794
- return false;
2795
- }
2796
- // non-assignment array destructure pattern
2797
- if (parent.type === 'ArrayPattern' &&
2798
- !isInDestructureAssignment(parent, parentStack)) {
2799
- return false;
2800
- }
2801
- // member expression property
2802
- if ((parent.type === 'MemberExpression' ||
2803
- parent.type === 'OptionalMemberExpression') &&
2804
- parent.property === id &&
2805
- !parent.computed) {
2806
- return false;
2807
- }
2808
- // is a special keyword but parsed as identifier
2809
- if (id.name === 'arguments') {
2810
- return false;
2811
- }
2812
- return true;
2813
- }
2814
- const isStaticProperty = (node) => node &&
2815
- (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
2816
- !node.computed;
2817
- const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
2818
- function isFunction(node) {
2819
- return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
2820
- }
2821
- function isCallOf(node, name) {
2822
- return !!(node &&
2823
- node.type === 'CallExpression' &&
2824
- node.callee.type === 'Identifier' &&
2825
- node.callee.name === name);
2826
- }
2827
- function canNeverBeRef(node, userReactiveImport) {
2828
- if (isCallOf(node, userReactiveImport)) {
2829
- return true;
2830
- }
2831
- switch (node.type) {
2832
- case 'UnaryExpression':
2833
- case 'BinaryExpression':
2834
- case 'ArrayExpression':
2835
- case 'ObjectExpression':
2836
- case 'FunctionExpression':
2837
- case 'ArrowFunctionExpression':
2838
- case 'UpdateExpression':
2839
- case 'ClassExpression':
2840
- case 'TaggedTemplateExpression':
2841
- return true;
2842
- case 'SequenceExpression':
2843
- return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
2844
- default:
2845
- if (node.type.endsWith('Literal')) {
2846
- return true;
2847
- }
2848
- return false;
2849
- }
2850
- }
2851
- function isInDestructureAssignment(parent, parentStack) {
2852
- if (parent &&
2853
- (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
2854
- let i = parentStack.length;
2855
- while (i--) {
2856
- const p = parentStack[i];
2857
- if (p.type === 'AssignmentExpression') {
2858
- const root = parentStack[0];
2859
- // if this is a ref: destructure, it should be treated like a
2860
- // variable decalration!
2861
- return !(root.type === 'LabeledStatement' && root.label.name === 'ref');
2862
- }
2863
- else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
2864
- break;
2865
- }
2866
- }
2867
- }
2868
- return false;
2869
- }
2870
- /**
2871
- * Analyze bindings in normal `<script>`
2872
- * Note that `compileScriptSetup` already analyzes bindings as part of its
2873
- * compilation process so this should only be used on single `<script>` SFCs.
2874
- */
2875
- function analyzeScriptBindings(ast) {
2876
- for (const node of ast) {
2877
- if (node.type === 'ExportDefaultDeclaration' &&
2878
- node.declaration.type === 'ObjectExpression') {
2879
- return analyzeBindingsFromOptions(node.declaration);
2880
- }
2881
- }
2882
- return {};
2883
- }
2884
- function analyzeBindingsFromOptions(node) {
2885
- const bindings = {};
2886
- for (const property of node.properties) {
2887
- if (property.type === 'ObjectProperty' &&
2888
- !property.computed &&
2889
- property.key.type === 'Identifier') {
2890
- // props
2891
- if (property.key.name === 'props') {
2892
- // props: ['foo']
2893
- // props: { foo: ... }
2894
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
2895
- bindings[key] = "props" /* PROPS */;
2896
- }
2897
- }
2898
- // inject
2899
- else if (property.key.name === 'inject') {
2900
- // inject: ['foo']
2901
- // inject: { foo: {} }
2902
- for (const key of getObjectOrArrayExpressionKeys(property.value)) {
2903
- bindings[key] = "options" /* OPTIONS */;
2904
- }
2905
- }
2906
- // computed & methods
2907
- else if (property.value.type === 'ObjectExpression' &&
2908
- (property.key.name === 'computed' || property.key.name === 'methods')) {
2909
- // methods: { foo() {} }
2910
- // computed: { foo() {} }
2911
- for (const key of getObjectExpressionKeys(property.value)) {
2912
- bindings[key] = "options" /* OPTIONS */;
2913
- }
2914
- }
2915
- }
2916
- // setup & data
2917
- else if (property.type === 'ObjectMethod' &&
2918
- property.key.type === 'Identifier' &&
2919
- (property.key.name === 'setup' || property.key.name === 'data')) {
2920
- for (const bodyItem of property.body.body) {
2921
- // setup() {
2922
- // return {
2923
- // foo: null
2924
- // }
2925
- // }
2926
- if (bodyItem.type === 'ReturnStatement' &&
2927
- bodyItem.argument &&
2928
- bodyItem.argument.type === 'ObjectExpression') {
2929
- for (const key of getObjectExpressionKeys(bodyItem.argument)) {
2930
- bindings[key] =
2931
- property.key.name === 'setup'
2932
- ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
2933
- : "data" /* DATA */;
2934
- }
2935
- }
2936
- }
2937
- }
2938
- }
2939
- return bindings;
2940
- }
2941
- function getObjectExpressionKeys(node) {
2942
- const keys = [];
2943
- for (const prop of node.properties) {
2944
- if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
2945
- !prop.computed) {
2946
- if (prop.key.type === 'Identifier') {
2947
- keys.push(prop.key.name);
2948
- }
2949
- else if (prop.key.type === 'StringLiteral') {
2950
- keys.push(prop.key.value);
2951
- }
2952
- }
2953
- }
2954
- return keys;
2955
- }
2956
- function getArrayExpressionKeys(node) {
2957
- const keys = [];
2958
- for (const element of node.elements) {
2959
- if (element && element.type === 'StringLiteral') {
2960
- keys.push(element.value);
2961
- }
2962
- }
2963
- return keys;
2964
- }
2965
- function getObjectOrArrayExpressionKeys(value) {
2966
- if (value.type === 'ArrayExpression') {
2967
- return getArrayExpressionKeys(value);
2968
- }
2969
- if (value.type === 'ObjectExpression') {
2970
- return getObjectExpressionKeys(value);
2971
- }
2972
- return [];
2973
- }
2974
-
2975
- exports.generateCodeFrame = compilerCore.generateCodeFrame;
2976
- exports.compileScript = compileScript;
2977
- exports.compileStyle = compileStyle;
2978
- exports.compileStyleAsync = compileStyleAsync;
2979
- exports.compileTemplate = compileTemplate;
2980
- exports.parse = parse;
2981
- exports.rewriteDefault = rewriteDefault;
2982
-
2983
- const compilerSfc_cjs = /*#__PURE__*/Object.freeze({
2984
- __proto__: null
2985
- });
2986
-
2987
514
  export { gqlPluckFromCodeString, gqlPluckFromCodeStringSync, parseCode };
2988
515
  //# sourceMappingURL=index.esm.js.map