From af9fc2bcff31d5baa413039818a9b3e011deccaf Mon Sep 17 00:00:00 2001 From: pikax Date: Sat, 3 Apr 2021 15:06:56 +0100 Subject: [PATCH 001/317] chore: move to typescript --- package.json | 2 +- src/compiler/{codeframe.js => codeframe.ts} | 13 +- src/compiler/codegen/{events.js => events.ts} | 55 +-- src/compiler/codegen/{index.js => index.ts} | 267 +++++++------- ...{create-compiler.js => create-compiler.ts} | 28 +- src/compiler/directives/{bind.js => bind.ts} | 6 +- .../directives/{index.js => index.ts} | 2 +- .../directives/{model.js => model.ts} | 39 +- src/compiler/directives/{on.js => on.ts} | 2 +- .../{error-detector.js => error-detector.ts} | 80 +++-- src/compiler/{helpers.js => helpers.ts} | 132 ++++--- src/compiler/{index.js => index.ts} | 4 +- src/compiler/{optimizer.js => optimizer.ts} | 50 +-- .../{entity-decoder.js => entity-decoder.ts} | 4 +- .../{filter-parser.js => filter-parser.ts} | 65 ++-- .../parser/{html-parser.js => html-parser.ts} | 81 +++-- src/compiler/parser/{index.js => index.ts} | 322 +++++++++-------- .../parser/{text-parser.js => text-parser.ts} | 19 +- .../{to-function.js => to-function.ts} | 42 ++- src/core/components/{index.js => index.ts} | 2 +- .../{keep-alive.js => keep-alive.ts} | 57 +-- src/core/{config.js => config.ts} | 47 ++- src/core/global-api/{assets.js => assets.ts} | 9 +- src/core/global-api/{extend.js => extend.ts} | 19 +- src/core/global-api/{index.js => index.ts} | 11 +- src/core/global-api/{mixin.js => mixin.ts} | 3 +- src/core/global-api/{use.js => use.ts} | 8 +- src/core/{index.js => index.ts} | 9 +- src/core/instance/{events.js => events.ts} | 58 +-- src/core/instance/{index.js => index.ts} | 7 +- src/core/instance/{init.js => init.ts} | 24 +- src/core/instance/{inject.js => inject.ts} | 37 +- .../instance/{lifecycle.js => lifecycle.ts} | 89 +++-- src/core/instance/{proxy.js => proxy.ts} | 57 +-- ...d-dynamic-keys.js => bind-dynamic-keys.ts} | 13 +- ...-listeners.js => bind-object-listeners.ts} | 11 +- ...d-object-props.js => bind-object-props.ts} | 24 +- .../{check-keycodes.js => check-keycodes.ts} | 6 +- .../render-helpers/{index.js => index.ts} | 2 +- .../{render-list.js => render-list.ts} | 21 +- .../{render-slot.js => render-slot.ts} | 21 +- .../{render-static.js => render-static.ts} | 14 +- .../{resolve-filter.js => resolve-filter.ts} | 4 +- ...coped-slots.js => resolve-scoped-slots.ts} | 16 +- .../{resolve-slots.js => resolve-slots.ts} | 21 +- src/core/instance/{render.js => render.ts} | 58 ++- src/core/instance/{state.js => state.ts} | 133 +++---- src/core/observer/{array.js => array.ts} | 4 +- src/core/observer/{dep.js => dep.ts} | 24 +- src/core/observer/{index.js => index.ts} | 82 +++-- .../observer/{scheduler.js => scheduler.ts} | 30 +- .../observer/{traverse.js => traverse.ts} | 10 +- src/core/observer/{watcher.js => watcher.ts} | 87 ++--- src/core/util/{debug.js => debug.ts} | 65 ++-- src/core/util/{env.js => env.ts} | 57 +-- src/core/util/{error.js => error.ts} | 12 +- src/core/util/{index.js => index.ts} | 0 src/core/util/{lang.js => lang.ts} | 10 +- src/core/util/{next-tick.js => next-tick.ts} | 22 +- src/core/util/{options.js => options.ts} | 186 +++++----- src/core/util/{perf.js => perf.ts} | 2 +- src/core/util/{props.js => props.ts} | 94 ++--- ...reate-component.js => create-component.ts} | 91 +++-- .../{create-element.js => create-element.ts} | 79 +++-- ...nent.js => create-functional-component.ts} | 63 ++-- .../{extract-props.js => extract-props.ts} | 34 +- ...-child.js => get-first-component-child.ts} | 5 +- src/core/vdom/helpers/{index.js => index.ts} | 0 src/core/vdom/helpers/is-async-placeholder.js | 5 - src/core/vdom/helpers/is-async-placeholder.ts | 8 + .../helpers/{merge-hook.js => merge-hook.ts} | 10 +- ...lize-children.js => normalize-children.ts} | 25 +- ...ped-slots.js => normalize-scoped-slots.ts} | 20 +- ...omponent.js => resolve-async-component.ts} | 62 ++-- ...pdate-listeners.js => update-listeners.ts} | 62 ++-- .../modules/{directives.js => directives.ts} | 32 +- src/core/vdom/modules/{index.js => index.ts} | 5 +- src/core/vdom/modules/{ref.js => ref.ts} | 16 +- src/core/vdom/{patch.js => patch.ts} | 333 ++++++++++++------ src/core/vdom/{vnode.js => vnode.ts} | 65 ++-- .../compiler/directives/{html.js => html.ts} | 2 +- .../directives/{index.js => index.ts} | 2 +- .../directives/{model.js => model.ts} | 79 +++-- .../compiler/directives/{text.js => text.ts} | 2 +- .../web/compiler/{index.js => index.ts} | 0 .../compiler/modules/{class.js => class.ts} | 18 +- .../compiler/modules/{index.js => index.ts} | 6 +- .../compiler/modules/{model.js => model.ts} | 20 +- .../compiler/modules/{style.js => style.ts} | 18 +- .../web/compiler/{options.js => options.ts} | 7 +- .../web/compiler/{util.js => util.ts} | 10 +- .../{entry-compiler.js => entry-compiler.ts} | 0 ...iler.js => entry-runtime-with-compiler.ts} | 37 +- .../{entry-runtime.js => entry-runtime.ts} | 0 ...erer.js => entry-server-basic-renderer.ts} | 3 +- src/platforms/web/entry-server-renderer.js | 27 -- src/platforms/web/entry-server-renderer.ts | 32 ++ .../runtime/{class-util.js => class-util.ts} | 8 +- .../runtime/components/{index.js => index.ts} | 2 +- ...ransition-group.js => transition-group.ts} | 90 +++-- .../{transition.js => transition.ts} | 87 +++-- .../runtime/directives/{index.js => index.ts} | 2 +- .../runtime/directives/{model.js => model.ts} | 49 +-- .../runtime/directives/{show.js => show.ts} | 19 +- .../web/runtime/{index.js => index.ts} | 13 +- .../runtime/modules/{attrs.js => attrs.ts} | 30 +- .../runtime/modules/{class.js => class.ts} | 25 +- .../modules/{dom-props.js => dom-props.ts} | 35 +- .../runtime/modules/{events.js => events.ts} | 28 +- .../runtime/modules/{index.js => index.ts} | 9 +- .../runtime/modules/{style.js => style.ts} | 38 +- .../modules/{transition.js => transition.ts} | 127 ++++--- src/platforms/web/runtime/node-ops.js | 59 ---- src/platforms/web/runtime/node-ops.ts | 68 ++++ .../web/runtime/{patch.js => patch.ts} | 0 ...{transition-util.js => transition-util.ts} | 111 +++--- .../web/server/{compiler.js => compiler.ts} | 5 +- .../server/directives/{index.js => index.ts} | 2 +- .../server/directives/{model.js => model.ts} | 9 +- .../server/directives/{show.js => show.ts} | 4 +- .../web/server/modules/{attrs.js => attrs.ts} | 19 +- .../web/server/modules/{class.js => class.ts} | 3 +- .../modules/{dom-props.js => dom-props.ts} | 7 +- .../web/server/modules/{index.js => index.ts} | 7 +- .../web/server/modules/{style.js => style.ts} | 5 +- src/platforms/web/server/util.js | 101 ------ src/platforms/web/server/util.ts | 99 ++++++ src/platforms/web/util/{attrs.js => attrs.ts} | 30 +- src/platforms/web/util/{class.js => class.ts} | 41 ++- .../web/util/{compat.js => compat.ts} | 6 +- src/platforms/web/util/element.js | 77 ---- src/platforms/web/util/element.ts | 78 ++++ src/platforms/web/util/{index.js => index.ts} | 7 +- src/platforms/web/util/{style.js => style.ts} | 21 +- .../directives/{index.js => index.ts} | 2 +- .../directives/{model.js => model.ts} | 11 +- .../weex/compiler/{index.js => index.ts} | 10 +- .../compiler/modules/{append.js => append.ts} | 11 +- .../compiler/modules/{class.js => class.ts} | 44 +-- .../compiler/modules/{index.js => index.ts} | 8 +- .../compiler/modules/{props.js => props.ts} | 8 +- .../{component-root.js => component-root.ts} | 2 +- .../{component.js => component.ts} | 5 +- .../recycle-list/{index.js => index.ts} | 16 +- .../{recycle-list.js => recycle-list.ts} | 3 +- .../modules/recycle-list/{text.js => text.ts} | 11 +- .../recycle-list/{v-bind.js => v-bind.ts} | 4 +- .../recycle-list/{v-for.js => v-for.ts} | 5 +- .../modules/recycle-list/{v-if.js => v-if.ts} | 15 +- .../modules/recycle-list/{v-on.js => v-on.ts} | 6 +- .../recycle-list/{v-once.js => v-once.ts} | 4 +- .../compiler/modules/{style.js => style.ts} | 63 ++-- .../{entry-compiler.js => entry-compiler.ts} | 0 ...{entry-framework.js => entry-framework.ts} | 63 ++-- ...me-factory.js => entry-runtime-factory.ts} | 0 .../runtime/components/{index.js => index.ts} | 2 +- .../weex/runtime/components/richtext.js | 82 ----- .../weex/runtime/components/richtext.ts | 90 +++++ ...ransition-group.js => transition-group.ts} | 68 ++-- .../{transition.js => transition.ts} | 2 +- .../weex/runtime/directives/index.js | 2 - .../weex/runtime/directives/index.ts | 1 + .../weex/runtime/{index.js => index.ts} | 15 +- .../runtime/modules/{attrs.js => attrs.ts} | 13 +- .../runtime/modules/{class.js => class.ts} | 29 +- .../runtime/modules/{events.js => events.ts} | 20 +- .../runtime/modules/{index.js => index.ts} | 8 +- .../runtime/modules/{style.js => style.ts} | 8 +- .../modules/{transition.js => transition.ts} | 118 +++++-- .../weex/runtime/{node-ops.js => node-ops.ts} | 32 +- .../weex/runtime/{patch.js => patch.ts} | 2 +- ...mplate.js => render-component-template.ts} | 18 +- ...tual-component.js => virtual-component.ts} | 37 +- .../runtime/{text-node.js => text-node.ts} | 2 +- .../weex/util/{element.js => element.ts} | 24 +- .../weex/util/{index.js => index.ts} | 7 +- .../weex/util/{parser.js => parser.ts} | 19 +- ...-renderer.js => create-bundle-renderer.ts} | 112 +++--- .../bundle-renderer/create-bundle-runner.js | 150 -------- .../bundle-renderer/create-bundle-runner.ts | 158 +++++++++ ...e-map-support.js => source-map-support.ts} | 38 +- ...c-renderer.js => create-basic-renderer.ts} | 12 +- ...{create-renderer.js => create-renderer.ts} | 90 +++-- .../{codegen.js => codegen.ts} | 91 +++-- .../{index.js => index.ts} | 4 +- .../{modules.js => modules.ts} | 89 +++-- .../{optimizer.js => optimizer.ts} | 42 +-- ...{runtime-helpers.js => runtime-helpers.ts} | 58 ++- .../{render-context.js => render-context.ts} | 88 +++-- .../{render-stream.js => render-stream.ts} | 57 +-- src/server/{render.js => render.ts} | 116 +++--- ...-mapper.js => create-async-file-mapper.ts} | 20 +- .../template-renderer/{index.js => index.ts} | 230 ++++++------ .../{parse-template.js => parse-template.ts} | 19 +- ...{template-stream.js => template-stream.ts} | 23 +- src/server/{util.js => util.ts} | 2 +- src/server/webpack-plugin/client.js | 65 ---- src/server/webpack-plugin/client.ts | 75 ++++ .../webpack-plugin/{server.js => server.ts} | 27 +- .../webpack-plugin/{util.js => util.ts} | 13 +- src/server/{write.js => write.ts} | 25 +- src/sfc/{parser.js => parser.ts} | 30 +- src/shared/{constants.js => constants.ts} | 10 +- src/shared/{util.js => util.ts} | 108 +++--- tsconfig.json | 43 +++ typescript/compiler.d.ts | 231 ++++++++++++ typescript/component.d.ts | 185 ++++++++++ typescript/global-api.d.ts | 28 ++ typescript/modules.d.ts | 47 +++ typescript/options.d.ts | 97 +++++ typescript/ssr.d.ts | 27 ++ typescript/vnode.d.ts | 86 +++++ typescript/weex.d.ts | 125 +++++++ yarn.lock | 8 +- 214 files changed, 5189 insertions(+), 3508 deletions(-) rename src/compiler/{codeframe.js => codeframe.ts} (82%) rename src/compiler/codegen/{events.js => events.ts} (79%) rename src/compiler/codegen/{index.js => index.ts} (72%) rename src/compiler/{create-compiler.js => create-compiler.ts} (70%) rename src/compiler/directives/{bind.js => bind.ts} (54%) rename src/compiler/directives/{index.js => index.ts} (89%) rename src/compiler/directives/{model.js => model.ts} (79%) rename src/compiler/directives/{on.js => on.ts} (79%) rename src/compiler/{error-detector.js => error-detector.ts} (63%) rename src/compiler/{helpers.js => helpers.ts} (66%) rename src/compiler/{index.js => index.ts} (93%) rename src/compiler/{optimizer.js => optimizer.ts} (74%) rename src/compiler/parser/{entity-decoder.js => entity-decoder.ts} (80%) rename src/compiler/parser/{filter-parser.js => filter-parser.ts} (57%) rename src/compiler/parser/{html-parser.js => html-parser.ts} (81%) rename src/compiler/parser/{index.js => index.ts} (77%) rename src/compiler/parser/{text-parser.js => text-parser.ts} (76%) rename src/compiler/{to-function.js => to-function.ts} (67%) rename src/core/components/{index.js => index.ts} (81%) rename src/core/components/{keep-alive.js => keep-alive.ts} (64%) rename src/core/{config.js => config.ts} (69%) rename src/core/global-api/{assets.js => assets.ts} (78%) rename src/core/global-api/{extend.js => extend.ts} (84%) rename src/core/global-api/{index.js => index.ts} (87%) rename src/core/global-api/{mixin.js => mixin.ts} (65%) rename src/core/global-api/{use.js => use.ts} (65%) rename src/core/{index.js => index.ts} (87%) rename src/core/instance/{events.js => events.ts} (67%) rename src/core/instance/{index.js => index.ts} (80%) rename src/core/instance/{init.js => init.ts} (82%) rename src/core/instance/{inject.js => inject.ts} (65%) rename src/core/instance/{lifecycle.js => lifecycle.ts} (81%) rename src/core/instance/{proxy.js => proxy.ts} (52%) rename src/core/instance/render-helpers/{bind-dynamic-keys.js => bind-dynamic-keys.ts} (77%) rename src/core/instance/render-helpers/{bind-object-listeners.js => bind-object-listeners.ts} (52%) rename src/core/instance/render-helpers/{bind-object-props.js => bind-object-props.ts} (68%) rename src/core/instance/render-helpers/{check-keycodes.js => check-keycodes.ts} (86%) rename src/core/instance/render-helpers/{index.js => index.ts} (95%) rename src/core/instance/render-helpers/{render-list.js => render-list.ts} (78%) rename src/core/instance/render-helpers/{render-slot.js => render-slot.ts} (67%) rename src/core/instance/render-helpers/{render-static.js => render-static.ts} (84%) rename src/core/instance/render-helpers/{resolve-filter.js => resolve-filter.ts} (72%) rename src/core/instance/render-helpers/{resolve-scoped-slots.js => resolve-scoped-slots.ts} (62%) rename src/core/instance/render-helpers/{resolve-slots.js => resolve-slots.ts} (69%) rename src/core/instance/{render.js => render.ts} (76%) rename src/core/instance/{state.js => state.ts} (73%) rename src/core/observer/{array.js => array.ts} (92%) rename src/core/observer/{dep.js => dep.ts} (78%) rename src/core/observer/{index.js => index.ts} (77%) rename src/core/observer/{scheduler.js => scheduler.ts} (90%) rename src/core/observer/{traverse.js => traverse.ts} (80%) rename src/core/observer/{watcher.js => watcher.ts} (80%) rename src/core/util/{debug.js => debug.ts} (55%) rename src/core/util/{env.js => env.ts} (64%) rename src/core/util/{error.js => error.ts} (87%) rename src/core/util/{index.js => index.ts} (100%) rename src/core/util/{lang.js => lang.ts} (80%) rename src/core/util/{next-tick.js => next-tick.ts} (89%) rename src/core/util/{options.js => options.ts} (71%) rename src/core/util/{perf.js => perf.ts} (93%) rename src/core/util/{props.js => props.ts} (76%) rename src/core/vdom/{create-component.js => create-component.ts} (79%) rename src/core/vdom/{create-element.js => create-element.ts} (67%) rename src/core/vdom/{create-functional-component.js => create-functional-component.ts} (76%) rename src/core/vdom/helpers/{extract-props.js => extract-props.ts} (59%) rename src/core/vdom/helpers/{get-first-component-child.js => get-first-component-child.ts} (73%) rename src/core/vdom/helpers/{index.js => index.ts} (100%) delete mode 100644 src/core/vdom/helpers/is-async-placeholder.js create mode 100644 src/core/vdom/helpers/is-async-placeholder.ts rename src/core/vdom/helpers/{merge-hook.js => merge-hook.ts} (82%) rename src/core/vdom/helpers/{normalize-children.js => normalize-children.ts} (84%) rename src/core/vdom/helpers/{normalize-scoped-slots.js => normalize-scoped-slots.ts} (85%) rename src/core/vdom/helpers/{resolve-async-component.js => resolve-async-component.ts} (70%) rename src/core/vdom/helpers/{update-listeners.js => update-listeners.ts} (63%) rename src/core/vdom/modules/{directives.js => directives.ts} (76%) rename src/core/vdom/modules/{index.js => index.ts} (61%) rename src/core/vdom/modules/{ref.js => ref.ts} (65%) rename src/core/vdom/{patch.js => patch.ts} (74%) rename src/core/vdom/{vnode.js => vnode.ts} (57%) rename src/platforms/web/compiler/directives/{html.js => html.ts} (66%) rename src/platforms/web/compiler/directives/{index.js => index.ts} (93%) rename src/platforms/web/compiler/directives/{model.js => model.ts} (74%) rename src/platforms/web/compiler/directives/{text.js => text.ts} (67%) rename src/platforms/web/compiler/{index.js => index.ts} (100%) rename src/platforms/web/compiler/modules/{class.js => class.ts} (67%) rename src/platforms/web/compiler/modules/{index.js => index.ts} (65%) rename src/platforms/web/compiler/modules/{model.js => model.ts} (88%) rename src/platforms/web/compiler/modules/{style.js => style.ts} (69%) rename src/platforms/web/compiler/{options.js => options.ts} (84%) rename src/platforms/web/compiler/{util.js => util.ts} (67%) rename src/platforms/web/{entry-compiler.js => entry-compiler.ts} (100%) rename src/platforms/web/{entry-runtime-with-compiler.js => entry-runtime-with-compiler.ts} (75%) rename src/platforms/web/{entry-runtime.js => entry-runtime.ts} (100%) rename src/platforms/web/{entry-server-basic-renderer.js => entry-server-basic-renderer.ts} (88%) delete mode 100644 src/platforms/web/entry-server-renderer.js create mode 100644 src/platforms/web/entry-server-renderer.ts rename src/platforms/web/runtime/{class-util.js => class-util.ts} (82%) rename src/platforms/web/runtime/components/{index.js => index.ts} (86%) rename src/platforms/web/runtime/components/{transition-group.js => transition-group.ts} (75%) rename src/platforms/web/runtime/components/{transition.js => transition.ts} (68%) rename src/platforms/web/runtime/directives/{index.js => index.ts} (91%) rename src/platforms/web/runtime/directives/{model.js => model.ts} (77%) rename src/platforms/web/runtime/directives/{show.js => show.ts} (71%) rename src/platforms/web/runtime/{index.js => index.ts} (86%) rename src/platforms/web/runtime/modules/{attrs.js => attrs.ts} (85%) rename src/platforms/web/runtime/modules/{class.js => class.ts} (60%) rename src/platforms/web/runtime/modules/{dom-props.js => dom-props.ts} (81%) rename src/platforms/web/runtime/modules/{events.js => events.ts} (87%) rename src/platforms/web/runtime/modules/{index.js => index.ts} (69%) rename src/platforms/web/runtime/modules/{style.js => style.ts} (75%) rename src/platforms/web/runtime/modules/{transition.js => transition.ts} (74%) delete mode 100644 src/platforms/web/runtime/node-ops.js create mode 100644 src/platforms/web/runtime/node-ops.ts rename src/platforms/web/runtime/{patch.js => patch.ts} (100%) rename src/platforms/web/runtime/{transition-util.js => transition-util.ts} (62%) rename src/platforms/web/server/{compiler.js => compiler.ts} (70%) rename src/platforms/web/server/directives/{index.js => index.ts} (90%) rename src/platforms/web/server/directives/{model.js => model.ts} (82%) rename src/platforms/web/server/directives/{show.js => show.ts} (61%) rename src/platforms/web/server/modules/{attrs.js => attrs.ts} (78%) rename src/platforms/web/server/modules/{class.js => class.ts} (62%) rename src/platforms/web/server/modules/{dom-props.js => dom-props.ts} (89%) rename src/platforms/web/server/modules/{index.js => index.ts} (67%) rename src/platforms/web/server/modules/{style.js => style.ts} (84%) delete mode 100644 src/platforms/web/server/util.js create mode 100644 src/platforms/web/server/util.ts rename src/platforms/web/util/{attrs.js => attrs.ts} (62%) rename src/platforms/web/util/{class.js => class.ts} (53%) rename src/platforms/web/util/{compat.js => compat.ts} (77%) delete mode 100644 src/platforms/web/util/element.js create mode 100644 src/platforms/web/util/element.ts rename src/platforms/web/util/{index.js => index.ts} (72%) rename src/platforms/web/util/{style.js => style.ts} (71%) rename src/platforms/weex/compiler/directives/{index.js => index.ts} (84%) mode change 100755 => 100644 rename src/platforms/weex/compiler/directives/{model.js => model.ts} (82%) rename src/platforms/weex/compiler/{index.js => index.ts} (86%) rename src/platforms/weex/compiler/modules/{append.js => append.ts} (72%) rename src/platforms/weex/compiler/modules/{class.js => class.ts} (63%) rename src/platforms/weex/compiler/modules/{index.js => index.ts} (69%) rename src/platforms/weex/compiler/modules/{props.js => props.ts} (85%) rename src/platforms/weex/compiler/modules/recycle-list/{component-root.js => component-root.ts} (81%) rename src/platforms/weex/compiler/modules/recycle-list/{component.js => component.ts} (72%) rename src/platforms/weex/compiler/modules/recycle-list/{index.js => index.ts} (72%) rename src/platforms/weex/compiler/modules/recycle-list/{recycle-list.js => recycle-list.ts} (92%) rename src/platforms/weex/compiler/modules/recycle-list/{text.js => text.ts} (69%) rename src/platforms/weex/compiler/modules/recycle-list/{v-bind.js => v-bind.ts} (83%) rename src/platforms/weex/compiler/modules/recycle-list/{v-for.js => v-for.ts} (80%) rename src/platforms/weex/compiler/modules/recycle-list/{v-if.js => v-if.ts} (78%) rename src/platforms/weex/compiler/modules/recycle-list/{v-on.js => v-on.ts} (77%) rename src/platforms/weex/compiler/modules/recycle-list/{v-once.js => v-once.ts} (74%) rename src/platforms/weex/compiler/modules/{style.js => style.ts} (57%) rename src/platforms/weex/{entry-compiler.js => entry-compiler.ts} (100%) rename src/platforms/weex/{entry-framework.js => entry-framework.ts} (78%) rename src/platforms/weex/{entry-runtime-factory.js => entry-runtime-factory.ts} (100%) rename src/platforms/weex/runtime/components/{index.js => index.ts} (89%) delete mode 100644 src/platforms/weex/runtime/components/richtext.js create mode 100644 src/platforms/weex/runtime/components/richtext.ts rename src/platforms/weex/runtime/components/{transition-group.js => transition-group.ts} (73%) rename src/platforms/weex/runtime/components/{transition.js => transition.ts} (89%) delete mode 100755 src/platforms/weex/runtime/directives/index.js create mode 100644 src/platforms/weex/runtime/directives/index.ts rename src/platforms/weex/runtime/{index.js => index.ts} (80%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{attrs.js => attrs.ts} (71%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{class.js => class.ts} (71%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{events.js => events.ts} (69%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{index.js => index.ts} (68%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{style.js => style.ts} (90%) mode change 100755 => 100644 rename src/platforms/weex/runtime/modules/{transition.js => transition.ts} (70%) rename src/platforms/weex/runtime/{node-ops.js => node-ops.ts} (59%) mode change 100755 => 100644 rename src/platforms/weex/runtime/{patch.js => patch.ts} (94%) rename src/platforms/weex/runtime/recycle-list/{render-component-template.js => render-component-template.ts} (55%) rename src/platforms/weex/runtime/recycle-list/{virtual-component.js => virtual-component.ts} (81%) rename src/platforms/weex/runtime/{text-node.js => text-node.ts} (77%) rename src/platforms/weex/util/{element.js => element.ts} (58%) rename src/platforms/weex/util/{index.js => index.ts} (88%) mode change 100755 => 100644 rename src/platforms/weex/util/{parser.js => parser.ts} (75%) rename src/server/bundle-renderer/{create-bundle-renderer.js => create-bundle-renderer.ts} (57%) delete mode 100644 src/server/bundle-renderer/create-bundle-runner.js create mode 100644 src/server/bundle-renderer/create-bundle-runner.ts rename src/server/bundle-renderer/{source-map-support.js => source-map-support.ts} (52%) rename src/server/{create-basic-renderer.js => create-basic-renderer.ts} (74%) rename src/server/{create-renderer.js => create-renderer.ts} (62%) rename src/server/optimizing-compiler/{codegen.js => codegen.ts} (78%) rename src/server/optimizing-compiler/{index.js => index.ts} (90%) rename src/server/optimizing-compiler/{modules.js => modules.ts} (52%) rename src/server/optimizing-compiler/{optimizer.js => optimizer.ts} (77%) rename src/server/optimizing-compiler/{runtime-helpers.js => runtime-helpers.ts} (73%) rename src/server/{render-context.js => render-context.ts} (67%) rename src/server/{render-stream.js => render-stream.ts} (63%) rename src/server/{render.js => render.ts} (80%) rename src/server/template-renderer/{create-async-file-mapper.js => create-async-file-mapper.ts} (74%) rename src/server/template-renderer/{index.js => index.ts} (53%) rename src/server/template-renderer/{parse-template.js => parse-template.ts} (67%) rename src/server/template-renderer/{template-stream.js => template-stream.ts} (81%) rename src/server/{util.js => util.ts} (91%) delete mode 100644 src/server/webpack-plugin/client.js create mode 100644 src/server/webpack-plugin/client.ts rename src/server/webpack-plugin/{server.js => server.ts} (76%) rename src/server/webpack-plugin/{util.js => util.ts} (66%) rename src/server/{write.js => write.ts} (66%) rename src/sfc/{parser.js => parser.ts} (83%) rename src/shared/{constants.js => constants.ts} (71%) rename src/shared/{util.js => util.ts} (70%) create mode 100644 tsconfig.json create mode 100644 typescript/compiler.d.ts create mode 100644 typescript/component.d.ts create mode 100644 typescript/global-api.d.ts create mode 100644 typescript/modules.d.ts create mode 100644 typescript/options.d.ts create mode 100644 typescript/ssr.d.ts create mode 100644 typescript/vnode.d.ts create mode 100644 typescript/weex.d.ts diff --git a/package.json b/package.json index 7d40666d05c..62d894d5bdb 100644 --- a/package.json +++ b/package.json @@ -136,7 +136,7 @@ "serialize-javascript": "^3.1.0", "shelljs": "^0.8.1", "terser": "^3.10.2", - "typescript": "^3.6.4", + "typescript": "^4.2.2", "webpack": "~4.28.4", "weex-js-runtime": "^0.23.6", "weex-styler": "^0.3.0", diff --git a/src/compiler/codeframe.js b/src/compiler/codeframe.ts similarity index 82% rename from src/compiler/codeframe.js rename to src/compiler/codeframe.ts index 513d318fcc1..037e07ea23c 100644 --- a/src/compiler/codeframe.js +++ b/src/compiler/codeframe.ts @@ -2,20 +2,22 @@ const range = 2 -export function generateCodeFrame ( +export function generateCodeFrame( source: string, start: number = 0, end: number = source.length ): string { const lines = source.split(/\r?\n/) let count = 0 - const res = [] + const res: string[] = [] for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1 if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue - res.push(`${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}`) + res.push( + `${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}` + ) const lineLength = lines[j].length if (j === i) { // push underline @@ -36,10 +38,11 @@ export function generateCodeFrame ( return res.join('\n') } -function repeat (str, n) { +function repeat(str, n) { let result = '' if (n > 0) { - while (true) { // eslint-disable-line + while (true) { + // eslint-disable-line if (n & 1) result += str n >>>= 1 if (n <= 0) break diff --git a/src/compiler/codegen/events.js b/src/compiler/codegen/events.ts similarity index 79% rename from src/compiler/codegen/events.js rename to src/compiler/codegen/events.ts index 4b0776115a0..8e4a747d3fc 100644 --- a/src/compiler/codegen/events.js +++ b/src/compiler/codegen/events.ts @@ -1,5 +1,7 @@ /* @flow */ +import { __WEEX__ } from 'typescript/weex' + const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function(?:\s+[\w$]+)?\s*\(/ const fnInvokeRE = /\([^)]*?\);*$/ const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/ @@ -14,7 +16,7 @@ const keyCodes: { [key: string]: number | Array } = { left: 37, right: 39, down: 40, - 'delete': [8, 46] + delete: [8, 46], } // KeyboardEvent.key aliases @@ -31,13 +33,13 @@ const keyNames: { [key: string]: string | Array } = { right: ['Right', 'ArrowRight'], down: ['Down', 'ArrowDown'], // #9112: IE11 uses `Del` for Delete key name. - 'delete': ['Backspace', 'Delete', 'Del'] + delete: ['Backspace', 'Delete', 'Del'], } // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once -const genGuard = condition => `if(${condition})return null;` +const genGuard = (condition) => `if(${condition})return null;` const modifierCode: { [key: string]: string } = { stop: '$event.stopPropagation();', @@ -49,10 +51,10 @@ const modifierCode: { [key: string]: string } = { meta: genGuard(`!$event.metaKey`), left: genGuard(`'button' in $event && $event.button !== 0`), middle: genGuard(`'button' in $event && $event.button !== 1`), - right: genGuard(`'button' in $event && $event.button !== 2`) + right: genGuard(`'button' in $event && $event.button !== 2`), } -export function genHandlers ( +export function genHandlers( events: ASTElementHandlers, isNative: boolean ): string { @@ -61,6 +63,7 @@ export function genHandlers ( let dynamicHandlers = `` for (const name in events) { const handlerCode = genHandler(events[name]) + //@ts-expect-error if (events[name] && events[name].dynamic) { dynamicHandlers += `${name},${handlerCode},` } else { @@ -77,34 +80,42 @@ export function genHandlers ( // Generate handler code with binding params on Weex /* istanbul ignore next */ -function genWeexHandler (params: Array, handlerCode: string) { +function genWeexHandler(params: Array, handlerCode: string) { let innerHandlerCode = handlerCode - const exps = params.filter(exp => simplePathRE.test(exp) && exp !== '$event') - const bindings = exps.map(exp => ({ '@binding': exp })) + const exps = params.filter( + (exp) => simplePathRE.test(exp) && exp !== '$event' + ) + const bindings = exps.map((exp) => ({ '@binding': exp })) const args = exps.map((exp, i) => { const key = `$_${i + 1}` innerHandlerCode = innerHandlerCode.replace(exp, key) return key }) args.push('$event') - return '{\n' + + return ( + '{\n' + `handler:function(${args.join(',')}){${innerHandlerCode}},\n` + `params:${JSON.stringify(bindings)}\n` + '}' + ) } -function genHandler (handler: ASTElementHandler | Array): string { +function genHandler( + handler: ASTElementHandler | Array +): string { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { - return `[${handler.map(handler => genHandler(handler)).join(',')}]` + return `[${handler.map((handler) => genHandler(handler)).join(',')}]` } const isMethodPath = simplePathRE.test(handler.value) const isFunctionExpression = fnExpRE.test(handler.value) - const isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, '')) + const isFunctionInvocation = simplePathRE.test( + handler.value.replace(fnInvokeRE, '') + ) if (!handler.modifiers) { if (isMethodPath || isFunctionExpression) { @@ -120,7 +131,7 @@ function genHandler (handler: ASTElementHandler | Array): str } else { let code = '' let genModifierCode = '' - const keys = [] + const keys: string[] = [] for (const key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key] @@ -129,11 +140,11 @@ function genHandler (handler: ASTElementHandler | Array): str keys.push(key) } } else if (key === 'exact') { - const modifiers: ASTModifiers = (handler.modifiers: any) + const modifiers = handler.modifiers genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] - .filter(keyModifier => !modifiers[keyModifier]) - .map(keyModifier => `$event.${keyModifier}Key`) + .filter((keyModifier) => !modifiers[keyModifier]) + .map((keyModifier) => `$event.${keyModifier}Key`) .join('||') ) } else { @@ -150,10 +161,10 @@ function genHandler (handler: ASTElementHandler | Array): str const handlerCode = isMethodPath ? `return ${handler.value}.apply(null, arguments)` : isFunctionExpression - ? `return (${handler.value}).apply(null, arguments)` - : isFunctionInvocation - ? `return ${handler.value}` - : handler.value + ? `return (${handler.value}).apply(null, arguments)` + : isFunctionInvocation + ? `return ${handler.value}` + : handler.value /* istanbul ignore if */ if (__WEEX__ && handler.params) { return genWeexHandler(handler.params, code + handlerCode) @@ -162,7 +173,7 @@ function genHandler (handler: ASTElementHandler | Array): str } } -function genKeyFilter (keys: Array): string { +function genKeyFilter(keys: Array): string { return ( // make sure the key filters only apply to KeyboardEvents // #9441: can't use 'keyCode' in $event because Chrome autofill fires fake @@ -172,7 +183,7 @@ function genKeyFilter (keys: Array): string { ) } -function genFilterCode (key: string): string { +function genFilterCode(key: string): string { const keyVal = parseInt(key, 10) if (keyVal) { return `$event.keyCode!==${keyVal}` diff --git a/src/compiler/codegen/index.js b/src/compiler/codegen/index.ts similarity index 72% rename from src/compiler/codegen/index.js rename to src/compiler/codegen/index.ts index c4f0195c7ff..e7cc7bd1185 100644 --- a/src/compiler/codegen/index.js +++ b/src/compiler/codegen/index.ts @@ -6,29 +6,35 @@ import { camelize, no, extend } from 'shared/util' import { baseWarn, pluckModuleFunction } from '../helpers' import { emptySlotScopeToken } from '../parser/index' -type TransformFunction = (el: ASTElement, code: string) => string; -type DataGenFunction = (el: ASTElement) => string; -type DirectiveFunction = (el: ASTElement, dir: ASTDirective, warn: Function) => boolean; +type TransformFunction = (el: ASTElement, code: string) => string +type DataGenFunction = (el: ASTElement) => string +type DirectiveFunction = ( + el: ASTElement, + dir: ASTDirective, + warn: Function +) => boolean export class CodegenState { - options: CompilerOptions; - warn: Function; - transforms: Array; - dataGenFns: Array; - directives: { [key: string]: DirectiveFunction }; - maybeComponent: (el: ASTElement) => boolean; - onceId: number; - staticRenderFns: Array; - pre: boolean; - - constructor (options: CompilerOptions) { + options: CompilerOptions + warn: Function + transforms: Array + dataGenFns: Array + directives: { [key: string]: DirectiveFunction } + maybeComponent: (el: ASTElement) => boolean + onceId: number + staticRenderFns: Array + pre: boolean + + constructor(options: CompilerOptions) { this.options = options this.warn = options.warn || baseWarn + //@ts-expect-error `this.transforms ` is a different type than `options.modules.transformCode` this.transforms = pluckModuleFunction(options.modules, 'transformCode') this.dataGenFns = pluckModuleFunction(options.modules, 'genData') this.directives = extend(extend({}, baseDirectives), options.directives) const isReservedTag = options.isReservedTag || no - this.maybeComponent = (el: ASTElement) => !!el.component || !isReservedTag(el.tag) + this.maybeComponent = (el: ASTElement) => + !!el.component || !isReservedTag(el.tag) this.onceId = 0 this.staticRenderFns = [] this.pre = false @@ -36,24 +42,28 @@ export class CodegenState { } export type CodegenResult = { - render: string, + render: string staticRenderFns: Array -}; +} -export function generate ( +export function generate( ast: ASTElement | void, options: CompilerOptions ): CodegenResult { const state = new CodegenState(options) // fix #11483, Root level ` : '' } - renderScripts (context: Object): string { + renderScripts(context: Object): string { if (this.clientManifest) { const initial = this.preloadFiles.filter(({ file }) => isJS(file)) - const async = (this.getUsedAsyncFiles(context) || []).filter(({ file }) => isJS(file)) + const async = (this.getUsedAsyncFiles(context) || []).filter(({ file }) => + isJS(file) + ) const needed = [initial[0]].concat(async, initial.slice(1)) - return needed.map(({ file }) => { - return `` - }).join('') + return needed + .map(({ file }) => { + return `` + }) + .join('') } else { return '' } } - getUsedAsyncFiles (context: Object): ?Array { - if (!context._mappedFiles && context._registeredComponents && this.mapFiles) { - const registered = Array.from(context._registeredComponents) + getUsedAsyncFiles(context: Record): Array | undefined { + if ( + !context._mappedFiles && + context._registeredComponents && + this.mapFiles + ) { + const registered: any[] = Array.from(context._registeredComponents) context._mappedFiles = this.mapFiles(registered).map(normalizeFile) } return context._mappedFiles } // create a transform stream - createStream (context: ?Object): TemplateStream { + createStream(context: Record | undefined): TemplateStream { if (!this.parsedTemplate) { throw new Error('createStream cannot be called without a template.') } + //@ts-expect-error return new TemplateStream(this, this.parsedTemplate, context || {}) } } -function normalizeFile (file: string): Resource { +function normalizeFile(file: string): Resource { const withoutQuery = file.replace(/\?.*/, '') const extension = path.extname(withoutQuery).slice(1) return { file, extension, fileWithoutQuery: withoutQuery, - asType: getPreloadType(extension) + asType: getPreloadType(extension), } } -function getPreloadType (ext: string): string { +function getPreloadType(ext: string): string { if (ext === 'js') { return 'script' } else if (ext === 'css') { diff --git a/src/server/template-renderer/parse-template.js b/src/server/template-renderer/parse-template.ts similarity index 67% rename from src/server/template-renderer/parse-template.js rename to src/server/template-renderer/parse-template.ts index 1ccfe899620..d200655e560 100644 --- a/src/server/template-renderer/parse-template.js +++ b/src/server/template-renderer/parse-template.ts @@ -3,18 +3,18 @@ const compile = require('lodash.template') const compileOptions = { escape: /{{([^{][\s\S]+?[^}])}}/g, - interpolate: /{{{([\s\S]+?)}}}/g + interpolate: /{{{([\s\S]+?)}}}/g, } export type ParsedTemplate = { - head: (data: any) => string; - neck: (data: any) => string; - tail: (data: any) => string; -}; + head: (data: any) => string + neck: (data: any) => string + tail: (data: any) => string +} -export function parseTemplate ( +export function parseTemplate( template: string, - contentPlaceholder?: string = '' + contentPlaceholder: string = '' ): ParsedTemplate { if (typeof template === 'object') { return template @@ -37,6 +37,9 @@ export function parseTemplate ( return { head: compile(template.slice(0, i), compileOptions), neck: compile(template.slice(i, j), compileOptions), - tail: compile(template.slice(j + contentPlaceholder.length), compileOptions) + tail: compile( + template.slice(j + contentPlaceholder.length), + compileOptions + ), } } diff --git a/src/server/template-renderer/template-stream.js b/src/server/template-renderer/template-stream.ts similarity index 81% rename from src/server/template-renderer/template-stream.js rename to src/server/template-renderer/template-stream.ts index ed4db78f65a..8644f09ff13 100644 --- a/src/server/template-renderer/template-stream.js +++ b/src/server/template-renderer/template-stream.ts @@ -1,20 +1,21 @@ /* @flow */ -const Transform = require('stream').Transform +// const Transform = require("stream").Transform; import type TemplateRenderer from './index' import type { ParsedTemplate } from './parse-template' +import { Transform } from 'stream' export default class TemplateStream extends Transform { - started: boolean; - renderer: TemplateRenderer; - template: ParsedTemplate; - context: Object; - inject: boolean; + started: boolean + renderer: TemplateRenderer + template: ParsedTemplate + context: Record + inject: boolean - constructor ( + constructor( renderer: TemplateRenderer, template: ParsedTemplate, - context: Object + context: Record ) { super() this.started = false @@ -24,7 +25,7 @@ export default class TemplateStream extends Transform { this.inject = renderer.inject } - _transform (data: Buffer | string, encoding: string, done: Function) { + _transform(data: Buffer | string, encoding: string, done: Function) { if (!this.started) { this.emit('beforeStart') this.start() @@ -33,7 +34,7 @@ export default class TemplateStream extends Transform { done() } - start () { + start() { this.started = true this.push(this.template.head(this.context)) @@ -59,7 +60,7 @@ export default class TemplateStream extends Transform { this.push(this.template.neck(this.context)) } - _flush (done: Function) { + _flush(done: Function) { this.emit('beforeEnd') if (this.inject) { diff --git a/src/server/util.js b/src/server/util.ts similarity index 91% rename from src/server/util.js rename to src/server/util.ts index 908f8c9df06..3f85530f137 100644 --- a/src/server/util.js +++ b/src/server/util.ts @@ -4,7 +4,7 @@ export const isJS = (file: string): boolean => /\.js(\?[^.]+)?$/.test(file) export const isCSS = (file: string): boolean => /\.css(\?[^.]+)?$/.test(file) -export function createPromiseCallback () { +export function createPromiseCallback() { let resolve, reject const promise: Promise = new Promise((_resolve, _reject) => { resolve = _resolve diff --git a/src/server/webpack-plugin/client.js b/src/server/webpack-plugin/client.js deleted file mode 100644 index ae2a2498672..00000000000 --- a/src/server/webpack-plugin/client.js +++ /dev/null @@ -1,65 +0,0 @@ -const hash = require('hash-sum') -const uniq = require('lodash.uniq') -import { isJS, isCSS, onEmit } from './util' - -export default class VueSSRClientPlugin { - constructor (options = {}) { - this.options = Object.assign({ - filename: 'vue-ssr-client-manifest.json' - }, options) - } - - apply (compiler) { - onEmit(compiler, 'vue-client-plugin', (compilation, cb) => { - const stats = compilation.getStats().toJson() - - const allFiles = uniq(stats.assets - .map(a => a.name)) - - const initialFiles = uniq(Object.keys(stats.entrypoints) - .map(name => stats.entrypoints[name].assets) - .reduce((assets, all) => all.concat(assets), []) - .filter((file) => isJS(file) || isCSS(file))) - - const asyncFiles = allFiles - .filter((file) => isJS(file) || isCSS(file)) - .filter(file => initialFiles.indexOf(file) < 0) - - const manifest = { - publicPath: stats.publicPath, - all: allFiles, - initial: initialFiles, - async: asyncFiles, - modules: { /* [identifier: string]: Array */ } - } - - const assetModules = stats.modules.filter(m => m.assets.length) - const fileToIndex = file => manifest.all.indexOf(file) - stats.modules.forEach(m => { - // ignore modules duplicated in multiple chunks - if (m.chunks.length === 1) { - const cid = m.chunks[0] - const chunk = stats.chunks.find(c => c.id === cid) - if (!chunk || !chunk.files) { - return - } - const id = m.identifier.replace(/\s\w+$/, '') // remove appended hash - const files = manifest.modules[hash(id)] = chunk.files.map(fileToIndex) - // find all asset modules associated with the same chunk - assetModules.forEach(m => { - if (m.chunks.some(id => id === cid)) { - files.push.apply(files, m.assets.map(fileToIndex)) - } - }) - } - }) - - const json = JSON.stringify(manifest, null, 2) - compilation.assets[this.options.filename] = { - source: () => json, - size: () => json.length - } - cb() - }) - } -} diff --git a/src/server/webpack-plugin/client.ts b/src/server/webpack-plugin/client.ts new file mode 100644 index 00000000000..344bd82817d --- /dev/null +++ b/src/server/webpack-plugin/client.ts @@ -0,0 +1,75 @@ +const hash = require('hash-sum') +const uniq = require('lodash.uniq') +import { isJS, isCSS, onEmit } from './util' + +export default class VueSSRClientPlugin { + constructor(options = {}) { + //@ts-expect-error + this.options = Object.assign( + { + filename: 'vue-ssr-client-manifest.json', + }, + options + ) + } + + apply(compiler) { + onEmit(compiler, 'vue-client-plugin', (compilation, cb) => { + const stats = compilation.getStats().toJson() + + const allFiles = uniq(stats.assets.map((a) => a.name)) + + const initialFiles = uniq( + Object.keys(stats.entrypoints) + .map((name) => stats.entrypoints[name].assets) + .reduce((assets, all) => all.concat(assets), []) + .filter((file) => isJS(file) || isCSS(file)) + ) + + const asyncFiles = allFiles + .filter((file) => isJS(file) || isCSS(file)) + .filter((file) => initialFiles.indexOf(file) < 0) + + const manifest = { + publicPath: stats.publicPath, + all: allFiles, + initial: initialFiles, + async: asyncFiles, + modules: { + /* [identifier: string]: Array */ + }, + } + + const assetModules = stats.modules.filter((m) => m.assets.length) + const fileToIndex = (file) => manifest.all.indexOf(file) + stats.modules.forEach((m) => { + // ignore modules duplicated in multiple chunks + if (m.chunks.length === 1) { + const cid = m.chunks[0] + const chunk = stats.chunks.find((c) => c.id === cid) + if (!chunk || !chunk.files) { + return + } + const id = m.identifier.replace(/\s\w+$/, '') // remove appended hash + const files = (manifest.modules[hash(id)] = chunk.files.map( + fileToIndex + )) + // find all asset modules associated with the same chunk + assetModules.forEach((m) => { + if (m.chunks.some((id) => id === cid)) { + files.push.apply(files, m.assets.map(fileToIndex)) + } + }) + } + }) + + const json = JSON.stringify(manifest, null, 2) + //@ts-expect-error + compilation.assets[this.options.filename] = { + source: () => json, + size: () => json.length, + } + cb() + }) + } +} diff --git a/src/server/webpack-plugin/server.js b/src/server/webpack-plugin/server.ts similarity index 76% rename from src/server/webpack-plugin/server.js rename to src/server/webpack-plugin/server.ts index 305b4bab58b..2693328417f 100644 --- a/src/server/webpack-plugin/server.js +++ b/src/server/webpack-plugin/server.ts @@ -1,13 +1,17 @@ import { validate, isJS, onEmit } from './util' export default class VueSSRServerPlugin { - constructor (options = {}) { - this.options = Object.assign({ - filename: 'vue-ssr-server-bundle.json' - }, options) + constructor(options = {}) { + //@ts-expect-error + this.options = Object.assign( + { + filename: 'vue-ssr-server-bundle.json', + }, + options + ) } - apply (compiler) { + apply(compiler) { validate(compiler) onEmit(compiler, 'vue-server-plugin', (compilation, cb) => { @@ -25,7 +29,7 @@ export default class VueSSRServerPlugin { if (entryAssets.length > 1) { throw new Error( `Server-side bundle should have one single entry file. ` + - `Avoid using CommonsChunkPlugin in the server config.` + `Avoid using CommonsChunkPlugin in the server config.` ) } @@ -39,25 +43,28 @@ export default class VueSSRServerPlugin { const bundle = { entry, files: {}, - maps: {} + maps: {}, } - stats.assets.forEach(asset => { + stats.assets.forEach((asset) => { if (isJS(asset.name)) { bundle.files[asset.name] = compilation.assets[asset.name].source() } else if (asset.name.match(/\.js\.map$/)) { - bundle.maps[asset.name.replace(/\.map$/, '')] = JSON.parse(compilation.assets[asset.name].source()) + bundle.maps[asset.name.replace(/\.map$/, '')] = JSON.parse( + compilation.assets[asset.name].source() + ) } // do not emit anything else for server delete compilation.assets[asset.name] }) const json = JSON.stringify(bundle, null, 2) + //@ts-expect-error const filename = this.options.filename compilation.assets[filename] = { source: () => json, - size: () => json.length + size: () => json.length, } cb() diff --git a/src/server/webpack-plugin/util.js b/src/server/webpack-plugin/util.ts similarity index 66% rename from src/server/webpack-plugin/util.js rename to src/server/webpack-plugin/util.ts index 94a204a22b2..4146cb11535 100644 --- a/src/server/webpack-plugin/util.js +++ b/src/server/webpack-plugin/util.ts @@ -1,22 +1,25 @@ const { red, yellow } = require('chalk') const prefix = `[vue-server-renderer-webpack-plugin]` -const warn = exports.warn = msg => console.error(red(`${prefix} ${msg}\n`)) -const tip = exports.tip = msg => console.log(yellow(`${prefix} ${msg}\n`)) +const warn = (exports.warn = (msg) => console.error(red(`${prefix} ${msg}\n`))) +const tip = (exports.tip = (msg) => console.log(yellow(`${prefix} ${msg}\n`))) -export const validate = compiler => { +export const validate = (compiler) => { if (compiler.options.target !== 'node') { warn('webpack config `target` should be "node".') } - if (compiler.options.output && compiler.options.output.libraryTarget !== 'commonjs2') { + if ( + compiler.options.output && + compiler.options.output.libraryTarget !== 'commonjs2' + ) { warn('webpack config `output.libraryTarget` should be "commonjs2".') } if (!compiler.options.externals) { tip( 'It is recommended to externalize dependencies in the server build for ' + - 'better build performance.' + 'better build performance.' ) } } diff --git a/src/server/write.js b/src/server/write.ts similarity index 66% rename from src/server/write.js rename to src/server/write.ts index 27a5e8a2667..5148d1ef1e9 100644 --- a/src/server/write.js +++ b/src/server/write.ts @@ -1,25 +1,26 @@ /* @flow */ const MAX_STACK_DEPTH = 800 -const noop = _ => _ +const noop = (_) => _ -const defer = typeof process !== 'undefined' && process.nextTick - ? process.nextTick - : typeof Promise !== 'undefined' - ? fn => Promise.resolve().then(fn) +const defer = + typeof process !== 'undefined' && process.nextTick + ? process.nextTick + : typeof Promise !== 'undefined' + ? (fn) => Promise.resolve().then(fn) : typeof setTimeout !== 'undefined' - ? setTimeout - : noop + ? setTimeout + : noop if (defer === noop) { throw new Error( 'Your JavaScript runtime does not support any asynchronous primitives ' + - 'that are required by vue-server-renderer. Please use a polyfill for ' + - 'either Promise or setTimeout.' + 'that are required by vue-server-renderer. Please use a polyfill for ' + + 'either Promise or setTimeout.' ) } -export function createWriteFunction ( +export function createWriteFunction( write: (text: string, next: Function) => boolean, onError: Function ): Function { @@ -32,7 +33,9 @@ export function createWriteFunction ( if (waitForNext !== true) { if (stackDepth >= MAX_STACK_DEPTH) { defer(() => { - try { next() } catch (e) { + try { + next() + } catch (e) { onError(e) } }) diff --git a/src/sfc/parser.js b/src/sfc/parser.ts similarity index 83% rename from src/sfc/parser.js rename to src/sfc/parser.ts index 59c5fc3a2c0..6ef98558354 100644 --- a/src/sfc/parser.js +++ b/src/sfc/parser.ts @@ -11,21 +11,21 @@ const isSpecialTag = makeMap('script,style,template', true) /** * Parse a single-file component (*.vue) file into an SFC Descriptor Object. */ -export function parseComponent ( +export function parseComponent( content: string, - options?: Object = {} + options: Record = {} ): SFCDescriptor { const sfc: SFCDescriptor = { template: null, script: null, styles: [], customBlocks: [], - errors: [] + errors: [], } let depth = 0 - let currentBlock: ?SFCBlock = null + let currentBlock: SFCBlock | null = null - let warn = msg => { + let warn: any = (msg) => { sfc.errors.push(msg) } @@ -42,7 +42,7 @@ export function parseComponent ( } } - function start ( + function start( tag: string, attrs: Array, unary: boolean, @@ -57,7 +57,7 @@ export function parseComponent ( attrs: attrs.reduce((cumulated, { name, value }) => { cumulated[name] = value || true return cumulated - }, {}) + }, {}), } if (isSpecialTag(tag)) { checkAttrs(currentBlock, attrs) @@ -66,7 +66,8 @@ export function parseComponent ( } else { sfc[tag] = currentBlock } - } else { // custom blocks + } else { + // custom blocks sfc.customBlocks.push(currentBlock) } } @@ -75,7 +76,7 @@ export function parseComponent ( } } - function checkAttrs (block: SFCBlock, attrs: Array) { + function checkAttrs(block: SFCBlock, attrs: Array) { for (let i = 0; i < attrs.length; i++) { const attr = attrs[i] if (attr.name === 'lang') { @@ -93,11 +94,12 @@ export function parseComponent ( } } - function end (tag: string, start: number) { + function end(tag: string, start: number) { if (depth === 1 && currentBlock) { currentBlock.end = start let text = content.slice(currentBlock.start, currentBlock.end) if (options.deindent !== false) { + //@ts-expect-error text = deindent(text) } // pad content so that linters and pre-processors can output correct @@ -111,14 +113,12 @@ export function parseComponent ( depth-- } - function padContent (block: SFCBlock, pad: true | "line" | "space") { + function padContent(block: SFCBlock, pad: true | 'line' | 'space') { if (pad === 'space') { return content.slice(0, block.start).replace(replaceRE, ' ') } else { const offset = content.slice(0, block.start).split(splitRE).length - const padChar = block.type === 'script' && !block.lang - ? '//\n' - : '\n' + const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n' return Array(offset).join(padChar) } } @@ -127,7 +127,7 @@ export function parseComponent ( warn, start, end, - outputSourceRange: options.outputSourceRange + outputSourceRange: options.outputSourceRange, }) return sfc diff --git a/src/shared/constants.js b/src/shared/constants.ts similarity index 71% rename from src/shared/constants.js rename to src/shared/constants.ts index a8b15e043dd..e4814c0f773 100644 --- a/src/shared/constants.js +++ b/src/shared/constants.ts @@ -1,10 +1,6 @@ export const SSR_ATTR = 'data-server-rendered' -export const ASSET_TYPES = [ - 'component', - 'directive', - 'filter' -] +export const ASSET_TYPES = ['component', 'directive', 'filter'] as const export const LIFECYCLE_HOOKS = [ 'beforeCreate', @@ -18,5 +14,5 @@ export const LIFECYCLE_HOOKS = [ 'activated', 'deactivated', 'errorCaptured', - 'serverPrefetch' -] + 'serverPrefetch', +] as const diff --git a/src/shared/util.js b/src/shared/util.ts similarity index 70% rename from src/shared/util.js rename to src/shared/util.ts index 9f240c77b14..49059d6acb4 100644 --- a/src/shared/util.js +++ b/src/shared/util.ts @@ -4,26 +4,26 @@ export const emptyObject = Object.freeze({}) // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. -export function isUndef (v: any): boolean %checks { +export function isUndef(v: any): v is undefined | null { return v === undefined || v === null } -export function isDef (v: any): boolean %checks { +export function isDef(v: T): v is NonNullable { return v !== undefined && v !== null } -export function isTrue (v: any): boolean %checks { +export function isTrue(v: any): boolean { return v === true } -export function isFalse (v: any): boolean %checks { +export function isFalse(v: any): boolean { return v === false } /** * Check if value is primitive. */ -export function isPrimitive (value: any): boolean %checks { +export function isPrimitive(value: any): boolean { return ( typeof value === 'string' || typeof value === 'number' || @@ -38,7 +38,7 @@ export function isPrimitive (value: any): boolean %checks { * Objects from primitive values when we know the value * is a JSON-compliant type. */ -export function isObject (obj: mixed): boolean %checks { +export function isObject(obj: any): boolean { return obj !== null && typeof obj === 'object' } @@ -47,7 +47,7 @@ export function isObject (obj: mixed): boolean %checks { */ const _toString = Object.prototype.toString -export function toRawType (value: any): string { +export function toRawType(value: any): string { return _toString.call(value).slice(8, -1) } @@ -55,23 +55,23 @@ export function toRawType (value: any): string { * Strict object type check. Only returns true * for plain JavaScript objects. */ -export function isPlainObject (obj: any): boolean { +export function isPlainObject(obj: any): boolean { return _toString.call(obj) === '[object Object]' } -export function isRegExp (v: any): boolean { +export function isRegExp(v: any): v is RegExp { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ -export function isValidArrayIndex (val: any): boolean { +export function isValidArrayIndex(val: any): boolean { const n = parseFloat(String(val)) return n >= 0 && Math.floor(n) === n && isFinite(val) } -export function isPromise (val: any): boolean { +export function isPromise(val: any): boolean { return ( isDef(val) && typeof val.then === 'function' && @@ -82,19 +82,19 @@ export function isPromise (val: any): boolean { /** * Convert a value to a string that is actually rendered. */ -export function toString (val: any): string { +export function toString(val: any): string { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) - ? JSON.stringify(val, null, 2) - : String(val) + ? JSON.stringify(val, null, 2) + : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ -export function toNumber (val: string): number | string { +export function toNumber(val: string): number | string { const n = parseFloat(val) return isNaN(n) ? val : n } @@ -103,18 +103,16 @@ export function toNumber (val: string): number | string { * Make a map and return a function for checking if a key * is in that map. */ -export function makeMap ( +export function makeMap( str: string, expectsLowerCase?: boolean -): (key: string) => true | void { +): (key: string) => true | undefined { const map = Object.create(null) const list: Array = str.split(',') for (let i = 0; i < list.length; i++) { map[list[i]] = true } - return expectsLowerCase - ? val => map[val.toLowerCase()] - : val => map[val] + return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val] } /** @@ -130,7 +128,7 @@ export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is') /** * Remove an item from an array. */ -export function remove (arr: Array, item: any): Array | void { +export function remove(arr: Array, item: any): Array | void { if (arr.length) { const index = arr.indexOf(item) if (index > -1) { @@ -143,19 +141,19 @@ export function remove (arr: Array, item: any): Array | void { * Check whether an object has the property. */ const hasOwnProperty = Object.prototype.hasOwnProperty -export function hasOwn (obj: Object | Array<*>, key: string): boolean { +export function hasOwn(obj: Object | Array, key: string): boolean { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ -export function cached (fn: F): F { - const cache = Object.create(null) - return (function cachedFn (str: string) { +export function cached(fn: (str: string) => R): (sr: string) => R { + const cache: Record = Object.create(null) + return function cachedFn(str: string) { const hit = cache[str] return hit || (cache[str] = fn(str)) - }: any) + } } /** @@ -163,7 +161,7 @@ export function cached (fn: F): F { */ const camelizeRE = /-(\w)/g export const camelize = cached((str: string): string => { - return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '') + return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')) }) /** @@ -190,8 +188,8 @@ export const hyphenate = cached((str: string): string => { */ /* istanbul ignore next */ -function polyfillBind (fn: Function, ctx: Object): Function { - function boundFn (a) { +function polyfillBind(fn: Function, ctx: Object): Function { + function boundFn(a: any) { const l = arguments.length return l ? l > 1 @@ -204,18 +202,17 @@ function polyfillBind (fn: Function, ctx: Object): Function { return boundFn } -function nativeBind (fn: Function, ctx: Object): Function { +function nativeBind(fn: Function, ctx: Object): Function { return fn.bind(ctx) } -export const bind = Function.prototype.bind - ? nativeBind - : polyfillBind +// @ts-expect-error bind cannot be `undefined` +export const bind = Function.prototype.bind ? nativeBind : polyfillBind /** * Convert an Array-like object to a real Array. */ -export function toArray (list: any, start?: number): Array { +export function toArray(list: any, start?: number): Array { start = start || 0 let i = list.length - start const ret: Array = new Array(i) @@ -228,7 +225,10 @@ export function toArray (list: any, start?: number): Array { /** * Mix properties into target object. */ -export function extend (to: Object, _from: ?Object): Object { +export function extend( + to: Record, + _from?: Record +): Record { for (const key in _from) { to[key] = _from[key] } @@ -238,7 +238,7 @@ export function extend (to: Object, _from: ?Object): Object { /** * Merge an Array of Objects into a single Object. */ -export function toObject (arr: Array): Object { +export function toObject(arr: Array): object { const res = {} for (let i = 0; i < arr.length; i++) { if (arr[i]) { @@ -255,7 +255,7 @@ export function toObject (arr: Array): Object { * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ -export function noop (a?: any, b?: any, c?: any) {} +export function noop(a?: any, b?: any, c?: any) {} /** * Always return false. @@ -272,17 +272,19 @@ export const identity = (_: any) => _ /** * Generate a string containing static keys from compiler modules. */ -export function genStaticKeys (modules: Array): string { - return modules.reduce((keys, m) => { - return keys.concat(m.staticKeys || []) - }, []).join(',') +export function genStaticKeys(modules: Array): string { + return modules + .reduce((keys, m) => { + return keys.concat(m.staticKeys || []) + }, [] as string[]) + .join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ -export function looseEqual (a: any, b: any): boolean { +export function looseEqual(a: any, b: any): boolean { if (a === b) return true const isObjectA = isObject(a) const isObjectB = isObject(b) @@ -291,17 +293,23 @@ export function looseEqual (a: any, b: any): boolean { const isArrayA = Array.isArray(a) const isArrayB = Array.isArray(b) if (isArrayA && isArrayB) { - return a.length === b.length && a.every((e, i) => { - return looseEqual(e, b[i]) - }) + return ( + a.length === b.length && + a.every((e: any, i: any) => { + return looseEqual(e, b[i]) + }) + ) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { const keysA = Object.keys(a) const keysB = Object.keys(b) - return keysA.length === keysB.length && keysA.every(key => { - return looseEqual(a[key], b[key]) - }) + return ( + keysA.length === keysB.length && + keysA.every((key) => { + return looseEqual(a[key], b[key]) + }) + ) } else { /* istanbul ignore next */ return false @@ -322,7 +330,7 @@ export function looseEqual (a: any, b: any): boolean { * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ -export function looseIndexOf (arr: Array, val: mixed): number { +export function looseIndexOf(arr: Array, val: unknown): number { for (let i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) return i } @@ -332,7 +340,7 @@ export function looseIndexOf (arr: Array, val: mixed): number { /** * Ensure a function is called only once. */ -export function once (fn: Function): Function { +export function once(fn: Function): Function { let called = false return function () { if (!called) { diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000000..3c4378bb070 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,43 @@ +{ + "compilerOptions": { + "baseUrl": ".", + "outDir": "dist", + "sourceMap": false, + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "allowJs": true, + "strict": true, + "noImplicitAny": false, + "noImplicitThis": false, + "noUnusedLocals": true, + "experimentalDecorators": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "removeComments": false, + "jsx": "preserve", + "lib": ["esnext", "dom"], + "types": ["jest", "puppeteer", "node"], + "rootDir": ".", + "paths": { + "compiler/*": ["src/compiler/*"], + "core/*": ["src/core/*"], + "platforms/*": ["src/platforms/*"], + "server/*": ["src/server/*"], + "sfc/*": ["src/sfc/*"], + "shared/*": ["src/shared/*"], + + "web/*": ["src/platforms/web/*"], + "weex/*": ["src/platforms/weex/*"] + } + }, + "include": [ + "typescript", + "src", + // "packages/runtime-dom/types/jsx.d.ts", + // "packages/*/__tests__", + "test-dts" + ], + + "exclude": ["flow"] +} diff --git a/typescript/compiler.d.ts b/typescript/compiler.d.ts new file mode 100644 index 00000000000..b4e2eb72be7 --- /dev/null +++ b/typescript/compiler.d.ts @@ -0,0 +1,231 @@ +declare type CompilerOptions = { + warn?: Function; // allow customizing warning in different environments; e.g. node + modules?: Array; // platform specific modules; e.g. style; class + directives?: { [key: string]: Function }; // platform specific directives + staticKeys?: string; // a list of AST properties to be considered static; for optimization + isUnaryTag?: (tag: string) => boolean | null; // check if a tag is unary for the platform + canBeLeftOpenTag?: (tag: string) => boolean | null; // check if a tag can be left opened + isReservedTag?: (tag: string) => boolean | null; // check if a tag is a native for the platform + preserveWhitespace?: boolean; // preserve whitespace between elements? (Deprecated) + whitespace?: "preserve" | "condense"; // whitespace handling strategy + optimize?: boolean; // optimize static content? + + // web specific + mustUseProp?: ( + tag: string, + type: string | null, + name: string + ) => boolean; // check if an attribute should be bound as a property + isPreTag?: (attr: string) => boolean | null; // check if a tag needs to preserve whitespace + getTagNamespace?: (tag: string) => string | null; // check the namespace for a tag + expectHTML?: boolean; // only false for non-web builds + isFromDOM?: boolean; + shouldDecodeTags?: boolean; + shouldDecodeNewlines?: boolean; + shouldDecodeNewlinesForHref?: boolean; + outputSourceRange?: boolean; + + // runtime user-configurable + delimiters?: [string, string]; // template delimiters + comments?: boolean; // preserve comments in template + + // for ssr optimization compiler + scopeId?: string; +}; + +declare type WarningMessage = { + msg: string; + start?: number; + end?: number; +}; + +declare type CompiledResult = { + ast: ASTElement | null; + render: string; + staticRenderFns: Array; + stringRenderFns?: Array; + errors?: Array; + tips?: Array; +}; + +declare type ModuleOptions = { + // transform an AST node before any attributes are processed + // returning an ASTElement from pre/transforms replaces the element + preTransformNode: (el: ASTElement) => ASTElement | null; + // transform an AST node after built-ins like v-if, v-for are processed + transformNode: (el: ASTElement) => ASTElement | null; + // transform an AST node after its children have been processed + // cannot return replacement in postTransform because tree is already finalized + postTransformNode: (el: ASTElement) => void; + genData: (el: ASTElement) => string; // generate extra data string for an element + transformCode?: (el: ASTElement, code: string) => string; // further transform generated code for an element + staticKeys?: Array; // AST properties to be considered static +}; + +declare type ASTModifiers = { [key: string]: boolean }; +declare type ASTIfCondition = { exp: string | null; block: ASTElement }; +declare type ASTIfConditions = Array; + +declare type ASTAttr = { + name: string; + value: any; + dynamic?: boolean; + start?: number; + end?: number; +}; + +declare type ASTElementHandler = { + value: string; + params?: Array; + modifiers: ASTModifiers | null; + dynamic?: boolean; + start?: number; + end?: number; +}; + +declare type ASTElementHandlers = { + [key: string]: ASTElementHandler | Array; +}; + +declare type ASTDirective = { + name: string; + rawName: string; + value: string; + arg: string | null; + isDynamicArg: boolean; + modifiers: ASTModifiers | null; + start?: number; + end?: number; +}; + +declare type ASTNode = ASTElement | ASTText | ASTExpression; + +declare type ASTElement = { + type: 1; + tag: string; + attrsList: Array; + attrsMap: { [key: string]: any }; + rawAttrsMap: { [key: string]: ASTAttr }; + parent: ASTElement | void; + children: Array; + + start?: number; + end?: number; + + processed?: true; + + static?: boolean; + staticRoot?: boolean; + staticInFor?: boolean; + staticProcessed?: boolean; + hasBindings?: boolean; + + text?: string; + attrs?: Array; + dynamicAttrs?: Array; + props?: Array; + plain?: boolean; + pre?: true; + ns?: string; + + component?: string; + inlineTemplate?: true; + transitionMode?: string | null; + slotName?: string | null; + slotTarget?: string | null; + slotTargetDynamic?: boolean; + slotScope?: string | null; + scopedSlots?: { [name: string]: ASTElement }; + + ref?: string; + refInFor?: boolean; + + if?: string; + ifProcessed?: boolean; + elseif?: string; + else?: true; + ifConditions?: ASTIfConditions; + + for?: string; + forProcessed?: boolean; + key?: string; + alias?: string; + iterator1?: string; + iterator2?: string; + + staticClass?: string; + classBinding?: string; + staticStyle?: string; + styleBinding?: string; + events?: ASTElementHandlers; + nativeEvents?: ASTElementHandlers; + + transition?: string | true; + transitionOnAppear?: boolean; + + model?: { + value: string; + callback: string; + expression: string; + }; + + directives?: Array; + + forbidden?: true; + once?: true; + onceProcessed?: boolean; + wrapData?: (code: string) => string; + wrapListeners?: (code: string) => string; + + // 2.4 ssr optimization + ssrOptimizability?: number; + + // weex specific + appendAsTree?: boolean; +}; + +declare type ASTExpression = { + type: 2; + expression: string; + text: string; + tokens: Array; + static?: boolean; + // 2.4 ssr optimization + ssrOptimizability?: number; + start?: number; + end?: number; +}; + +declare type ASTText = { + type: 3; + text: string; + static?: boolean; + isComment?: boolean; + // 2.4 ssr optimization + ssrOptimizability?: number; + start?: number; + end?: number; +}; + +// SFC-parser related declarations + +// an object format describing a single-file component +declare type SFCDescriptor = { + template: SFCBlock | null; + script: SFCBlock | null; + styles: Array; + customBlocks: Array; + errors: Array; +}; + +declare type SFCBlock = { + type: string; + content: string; + attrs: { [attribute: string]: string }; + start?: number; + end?: number; + lang?: string; + src?: string; + scoped?: boolean; + module?: string | boolean; +}; diff --git a/typescript/component.d.ts b/typescript/component.d.ts new file mode 100644 index 00000000000..f1fb9955c45 --- /dev/null +++ b/typescript/component.d.ts @@ -0,0 +1,185 @@ +import type { Config } from "../src/core/config"; +import type VNode from "../src/core/vdom/vnode"; +import type Watcher from "../src/core/observer/watcher"; +import { ComponentOptions } from "./options"; +import { ScopedSlotsData, VNodeChildren, VNodeData } from "./vnode"; + +declare class Component { + // constructor information + static cid: number; + static options: Object; + // extend + static extend: (options: Object) => Function; + static superOptions: Object; + static extendOptions: Object; + static sealedOptions: Object; + static super: Component; + // assets + static directive: ( + id: string, + def?: Function | Object + ) => Function | Object | void; + static component: (id: string, def?: Component | Object) => Component; + static filter: (id: string, def?: Function) => Function | void; + // functional context constructor + static FunctionalRenderContext: Function; + + // public properties + $el: any; // so that we can attach __vue__ to it + $data: Object; + $props: Object; + $options: ComponentOptions; + $parent: Component | undefined; + $root: Component; + $children: Array; + $refs: { + [key: string]: Component | Element | Array | undefined; + }; + $slots: { [key: string]: Array }; + $scopedSlots: { [key: string]: () => VNodeChildren }; + $vnode: VNode; // the placeholder node for the component in parent's render tree + $attrs: { [key: string]: string }; + $listeners: { [key: string]: Function | Array }; + $isServer: boolean; + + // public methods + $mount: (el?: Element | string, hydrating?: boolean) => Component; + $forceUpdate: () => void; + $destroy: () => void; + $set: (target: Object | Array, key: string | number, val: T) => T; + $delete: (target: Object | Array, key: string | number) => void; + $watch: ( + expOrFn: string | Function, + cb: Function, + options?: Object + ) => Function; + $on: (event: string | Array, fn: Function) => Component; + $once: (event: string, fn: Function) => Component; + $off: (event?: string | Array, fn?: Function) => Component; + $emit: (event: string, ...args: Array) => Component; + $nextTick: (fn: Function) => void | Promise; + $createElement: ( + tag?: string | Component, + data?: Object, + children?: VNodeChildren + ) => VNode; + + // private properties + _uid: number | string; + _name: string; // this only exists in dev mode + _isVue: true; + _self: Component; + _renderProxy: Component; + _renderContext?: Component; + _watcher: Watcher; + _watchers: Array; + _computedWatchers: { [key: string]: Watcher }; + _data: Object; + _props: Object; + _events: Record; + _inactive: boolean | null; + _directInactive: boolean; + _isMounted: boolean; + _isDestroyed: boolean; + _isBeingDestroyed: boolean; + _vnode?: VNode; // self root node + _staticTrees?: Array; // v-once cached trees + _hasHookEvent: boolean; + _provided?: Object; + // _virtualComponents?: { [key: string]: Component }; + + // private methods + + // lifecycle + _init: Function; + _mount: (el?: Element | void, hydrating?: boolean) => Component; + _update: (vnode: VNode, hydrating?: boolean) => void; + + // rendering + _render: () => VNode; + + __patch__: ( + a: Element | VNode | void, + b: VNode | null, + hydrating?: boolean, + removeOnly?: boolean, + parentElm?: any, + refElm?: any + ) => any; + + // createElement + + // _c is internal that accepts `normalizationType` optimization hint + _c: ( + vnode?: VNode, + data?: VNodeData, + children?: VNodeChildren, + normalizationType?: number + ) => VNode | void; + + // renderStatic + _m: (index: number, isInFor?: boolean) => VNode | VNodeChildren; + // markOnce + _o: ( + vnode: VNode | Array, + index: number, + key: string + ) => VNode | VNodeChildren; + // toString + _s: (value: any) => string; + // text to VNode + _v: (value: string | number) => VNode; + // toNumber + _n: (value: string) => number | string; + // empty vnode + _e: () => VNode; + // loose equal + _q: (a: any, b: any) => boolean; + // loose indexOf + _i: (arr: Array, val: any) => number; + // resolveFilter + _f: (id: string) => Function; + // renderList + _l: (val: any, render: Function) => Array | null; + // renderSlot + _t: ( + name: string, + fallback?: Array, + props?: Object + ) => Array | null; + // apply v-bind object + _b: ( + data: any, + tag: string, + value: any, + asProp: boolean, + isSync?: boolean + ) => VNodeData; + // apply v-on object + _g: (data: any, value: any) => VNodeData; + // check custom keyCode + _k: ( + eventKeyCode: number, + key: string, + builtInAlias?: number | Array, + eventKeyName?: string + ) => boolean | null; + // resolve scoped slots + _u: ( + scopedSlots: ScopedSlotsData, + res?: Object + ) => { [key: string]: Function }; + + // SSR specific + _ssrNode: Function; + _ssrList: Function; + _ssrEscape: Function; + _ssrAttr: Function; + _ssrAttrs: Function; + _ssrDOMProps: Function; + _ssrClass: Function; + _ssrStyle: Function; + + // allow dynamic method registration + [key: string]: any; +} diff --git a/typescript/global-api.d.ts b/typescript/global-api.d.ts new file mode 100644 index 00000000000..1a34774f155 --- /dev/null +++ b/typescript/global-api.d.ts @@ -0,0 +1,28 @@ +import { Config } from "../src/core/config"; +import { Component } from "./component"; + +declare interface GlobalAPI { + cid: number; + options: Record; + config: Config; + util: Object; + + extend: (options: Object) => Component; + set: (target: Object | Array, key: string | number, value: T) => T; + delete: (target: Object | Array, key: string | number) => void; + nextTick: (fn: Function, context?: Object) => void | Promise; + use: (plugin: Function | Object) => GlobalAPI; + mixin: (mixin: Object) => GlobalAPI; + compile: ( + template: string + ) => { render: Function; staticRenderFns: Array }; + + directive: (id: string, def?: Function | Object) => Function | Object | void; + component: (id: string, def?: Component | Object) => Component; + filter: (id: string, def?: Function) => Function | void; + + observable: (value: T) => T; + + // allow dynamic method registration + [key: string]: any; +} diff --git a/typescript/modules.d.ts b/typescript/modules.d.ts new file mode 100644 index 00000000000..deb38b7a8f1 --- /dev/null +++ b/typescript/modules.d.ts @@ -0,0 +1,47 @@ +declare module 'he' { + function escape(html: string): string + function decode(html: string): string +} + +declare module 'source-map' { + class SourceMapGenerator { + setSourceContent(filename: string, content: string): void + addMapping(mapping: Object): void + toString(): string + } + class SourceMapConsumer { + constructor(map: Object) + originalPositionFor(position: { + line: number + column: number + }): { + source: string | null + line: number | null + column: number | null + } + } +} + +declare module 'lru-cache' { + var exports: { + (): any + } +} + +declare module 'de-indent' { + var exports: { + (input: string): string + } +} + +declare module 'serialize-javascript' { + var exports: { + (input: string, options: { isJSON: boolean }): string + } +} + +declare module 'lodash.template' { + var exports: { + (input: string, options: { interpolate: RegExp; escape: RegExp }): Function + } +} diff --git a/typescript/options.d.ts b/typescript/options.d.ts new file mode 100644 index 00000000000..02c88cec834 --- /dev/null +++ b/typescript/options.d.ts @@ -0,0 +1,97 @@ +import VNode from "../src/core/vdom/vnode"; +import { Component } from "./component"; + +declare type InternalComponentOptions = { + _isComponent: true; + parent: Component; + _parentVnode: VNode; + render?: Function; + staticRenderFns?: Array; +}; + +type InjectKey = string | Symbol; + +declare type ComponentOptions = { + componentId?: string; + + // data + data: object | Function | void; + props?: { [key: string]: PropOptions }; + propsData?: object; + computed?: { + [key: string]: + | Function + | { + get?: Function; + set?: Function; + cache?: boolean; + }; + }; + methods?: { [key: string]: Function }; + watch?: { [key: string]: Function | string }; + + // DOM + el?: string | Element; + template?: string; + render: (h: () => VNode) => VNode; + renderError?: (h: () => VNode, err: Error) => VNode; + staticRenderFns?: Array<() => VNode>; + + // lifecycle + beforeCreate?: Function; + created?: Function; + beforeMount?: Function; + mounted?: Function; + beforeUpdate?: Function; + updated?: Function; + activated?: Function; + deactivated?: Function; + beforeDestroy?: Function; + destroyed?: Function; + errorCaptured?: () => boolean | void; + serverPrefetch?: Function; + + // assets + directives?: { [key: string]: object }; + components?: { [key: string]: Component }; + transitions?: { [key: string]: object }; + filters?: { [key: string]: Function }; + + // context + provide?: Record | (() => Record); + inject?: + | { [key: string]: InjectKey | { from?: InjectKey; default?: any } } + | Array; + + // component v-model customization + model?: { + prop?: string; + event?: string; + }; + + // misc + parent?: Component; + mixins?: Array; + name?: string; + extends?: Component | object; + delimiters?: [string, string]; + comments?: boolean; + inheritAttrs?: boolean; + + // private + _isComponent?: true; + _propKeys?: Array; + _parentVnode?: VNode; + _parentListeners?: object | null; + _renderChildren?: Array | null; + _componentTag: string | null; + _scopeId: string | null; + _base: Component; +}; + +declare type PropOptions = { + type: Function | Array | null; + default: any; + required: boolean | null; + validator: Function | null; +}; diff --git a/typescript/ssr.d.ts b/typescript/ssr.d.ts new file mode 100644 index 00000000000..2f351f2164c --- /dev/null +++ b/typescript/ssr.d.ts @@ -0,0 +1,27 @@ +import VNode from "../src/core/vdom/vnode"; +import { Component } from "./component"; + +declare type ComponentWithCacheContext = { + type: "ComponentWithCache"; + bufferIndex: number; + buffer: Array; + key: string; +}; + +declare type ElementContext = { + type: "Element"; + children: Array; + rendered: number; + endTag: string; + total: number; +}; + +declare type ComponentContext = { + type: "Component"; + prevActive: Component; +}; + +declare type RenderState = + | ComponentContext + | ComponentWithCacheContext + | ElementContext; diff --git a/typescript/vnode.d.ts b/typescript/vnode.d.ts new file mode 100644 index 00000000000..ca45d5fd3e9 --- /dev/null +++ b/typescript/vnode.d.ts @@ -0,0 +1,86 @@ +import VNode from "../src/core/vdom/vnode"; +import { Component } from "./component"; + +declare type VNodeChildren = + | Array + | string; + +declare type VNodeComponentOptions = { + Ctor: Component; + propsData?: Object; + listeners?: Object; + children?: Array; + tag?: string; +}; + +declare type MountedComponentVNode = { + context: Component; + componentOptions: VNodeComponentOptions; + componentInstance: Component; + parent: VNode; + data: VNodeData; +}; + +// interface for vnodes in update modules +declare type VNodeWithData = { + tag: string; + data: VNodeData; + children: Array; + text: void; + elm: any; + ns: string | void; + context: Component; + key: string | number | undefined; + parent?: VNodeWithData; + componentOptions?: VNodeComponentOptions; + componentInstance?: Component; + isRootInsert: boolean; +}; + +declare interface VNodeData { + key?: string | number; + slot?: string; + ref?: string; + is?: string; + pre?: boolean; + tag?: string; + staticClass?: string; + class?: any; + staticStyle?: { [key: string]: any }; + style?: string | Array | Object; + normalizedStyle?: Object; + props?: { [key: string]: any }; + attrs?: { [key: string]: string }; + domProps?: { [key: string]: any }; + hook?: { [key: string]: Function }; + on?: { [key: string]: Function | Array }; + nativeOn?: { [key: string]: Function | Array }; + transition?: Object; + show?: boolean; // marker for v-show + inlineTemplate?: { + render: Function; + staticRenderFns: Array; + }; + directives?: Array; + keepAlive?: boolean; + scopedSlots?: { [key: string]: Function }; + model?: { + value: any; + callback: Function; + }; +} + +declare type VNodeDirective = { + name: string; + rawName: string; + value?: any; + oldValue?: any; + arg?: string; + oldArg?: string; + modifiers?: ASTModifiers; + def?: Object; +}; + +declare type ScopedSlotsData = Array< + { key: string; fn: Function } | ScopedSlotsData +>; diff --git a/typescript/weex.d.ts b/typescript/weex.d.ts new file mode 100644 index 00000000000..ea138db3587 --- /dev/null +++ b/typescript/weex.d.ts @@ -0,0 +1,125 @@ +import { Component } from "./component"; +import { GlobalAPI } from "./global-api"; + +// global flag to be compiled away +declare var __WEEX__: boolean; + +// global object in Weex +declare var WXEnvironment: WeexEnvironment; + +declare type Weex = { + config: WeexConfigAPI; + document: WeexDocument; + requireModule: (name: string) => Object | void; + supports: (condition: string) => boolean | void; + isRegisteredModule: (name: string, method?: string) => boolean; + isRegisteredComponent: (name: string) => boolean; +}; + +declare type WeexConfigAPI = { + bundleUrl: string; // === weex.document.URL + bundleType: string; + env: WeexEnvironment; // === WXEnvironment +}; + +declare type WeexEnvironment = { + platform: string; // could be "Web", "iOS", "Android" + weexVersion: string; // the version of WeexSDK + + osName: string; // could be "iOS", "Android" or others + osVersion: string; + appName: string; // mobile app name or browser name + appVersion: string; + + // information about current running device + deviceModel: string; // phone device model + deviceWidth: number; + deviceHeight: number; + scale: number; + + // only available on the web + userAgent?: string; + dpr?: number; + rem?: number; +}; + +declare interface WeexDocument { + id: string; + URL: string; + taskCenter: WeexTaskCenter; + + open: () => void; + close: () => void; + createElement: (tagName: string, props?: Object) => WeexElement; + createComment: (text: string) => Object; + fireEvent: (type: string) => void; + destroy: () => void; +} + +declare interface WeexTaskCenter { + instanceId: string; + callbackManager: Object; + send: (type: string, params: Object, args: Array, options?: Object) => void; + registerHook: (componentId: string, type: string, hook: string, fn: Function) => void; + updateData: (componentId: string, data: Object | void, callback?: Function) => void; +} + +declare interface WeexElement { + nodeType: number; + nodeId: string; + type: string; + ref: string; + text?: string; + + parentNode: WeexElement | void; + children: Array; + previousSibling: WeexElement | void; + nextSibling: WeexElement | void; + + appendChild: (node: WeexElement) => void; + removeChild: (node: WeexElement, preserved?: boolean) => void; + insertBefore: (node: WeexElement, before: WeexElement) => void; + insertAfter: (node: WeexElement, after: WeexElement) => void; + setAttr: (key: string, value: any, silent?: boolean) => void; + setAttrs: (attrs: Object, silent?: boolean) => void; + setStyle: (key: string, value: any, silent?: boolean) => void; + setStyles: (attrs: Object, silent?: boolean) => void; + addEvent: (type: string, handler: Function, args?: Array) => void; + removeEvent: (type: string) => void; + fireEvent: (type: string) => void; + destroy: () => void; +} + +declare type WeexInstanceOption = { + instanceId: string; + config: WeexConfigAPI; + document: WeexDocument; + Vue?: GlobalAPI; + app?: Component; + data?: Object; +}; + +declare type WeexRuntimeContext = { + weex: Weex; + service: Object; + BroadcastChannel?: Function; +}; + +declare type WeexInstanceContext = { + Vue: GlobalAPI; + + // DEPRECATED + setTimeout?: Function; + clearTimeout?: Function; + setInterval?: Function; + clearInterval?: Function; +}; + +declare type WeexCompilerOptions = CompilerOptions & { + // whether to compile special template for + recyclable?: boolean; +}; + +declare type WeexCompiledResult = CompiledResult & { + '@render'?: string; +}; diff --git a/yarn.lock b/yarn.lock index df84403791f..f03c1e11303 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7988,10 +7988,10 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@^3.6.4: - version "3.6.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.6.4.tgz#b18752bb3792bc1a0281335f7f6ebf1bbfc5b91d" - integrity sha512-unoCll1+l+YK4i4F8f22TaNVPRHcD9PA3yCuZ8g5e0qGqlVlJ/8FSateOLLSagn+Yg5+ZwuPkL8LFUc0Jcvksg== +typescript@^4.2.2: + version "4.2.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.3.tgz#39062d8019912d43726298f09493d598048c1ce3" + integrity sha512-qOcYwxaByStAWrBf4x0fibwZvMRG+r4cQoTjbPtUlrWjBHbmCAww1i448U0GJ+3cNNEtebDteo/cHOR3xJ4wEw== uglify-js@^3.1.4: version "3.13.0" From 65b683a5e1429a19d87c7aec9cce4093f1684336 Mon Sep 17 00:00:00 2001 From: pikax Date: Sat, 3 Apr 2021 16:36:50 +0100 Subject: [PATCH 002/317] fix build --- dist/vue.common.dev.js | 20149 ++++++++------- dist/vue.common.prod.js | 4 +- dist/vue.esm.browser.js | 20244 ++++++++-------- dist/vue.esm.browser.min.js | 4 +- dist/vue.esm.js | 20224 ++++++++------- dist/vue.js | 20149 ++++++++------- dist/vue.min.js | 4 +- dist/vue.runtime.common.dev.js | 13572 +++++------ dist/vue.runtime.common.prod.js | 4 +- dist/vue.runtime.esm.js | 13628 +++++------ dist/vue.runtime.js | 13572 +++++------ dist/vue.runtime.min.js | 4 +- package.json | 1 + packages/vue-server-renderer/basic.js | 14185 +++++------ packages/vue-server-renderer/build.dev.js | 15922 ++++++------ packages/vue-server-renderer/build.prod.js | 2 +- packages/vue-server-renderer/client-plugin.js | 136 +- packages/vue-server-renderer/server-plugin.js | 160 +- packages/vue-template-compiler/browser.js | 8423 +++---- packages/vue-template-compiler/build.js | 8564 +++---- scripts/config.js | 63 +- src/compiler/codegen/events.ts | 2 - src/compiler/parser/index.ts | 2 +- src/core/config.ts | 10 +- src/core/index.ts | 1 - src/core/instance/index.ts | 10 +- src/core/instance/lifecycle.ts | 6 +- src/core/instance/proxy.ts | 2 +- src/core/instance/render.ts | 13 +- src/core/instance/state.ts | 15 +- src/core/observer/index.ts | 2 +- src/core/util/props.ts | 1 - src/core/vdom/create-component.ts | 1 - src/core/vdom/create-element.ts | 1 - src/core/vdom/create-functional-component.ts | 4 +- src/core/vdom/helpers/update-listeners.ts | 1 - src/core/vdom/patch.ts | 1 - src/global.d.ts | 22 + src/platforms/web/compiler/modules/model.ts | 2 +- .../web/entry-runtime-with-compiler.ts | 1 - src/platforms/web/runtime/index.ts | 5 +- src/platforms/web/runtime/modules/style.ts | 1 - src/platforms/web/server/directives/model.ts | 1 + src/platforms/web/server/modules/attrs.ts | 1 + src/platforms/web/server/modules/dom-props.ts | 1 + src/platforms/web/util/attrs.ts | 4 +- tsconfig.json | 9 +- typescript/component.d.ts | 42 +- typescript/global-api.d.ts | 1 + typescript/weex.d.ts | 2 +- yarn.lock | 137 + 51 files changed, 79270 insertions(+), 90045 deletions(-) create mode 100644 src/global.d.ts diff --git a/dist/vue.common.dev.js b/dist/vue.common.dev.js index 41f17e2f943..d2b34780db6 100644 --- a/dist/vue.common.dev.js +++ b/dist/vue.common.dev.js @@ -1,193 +1,159 @@ /*! * Vue.js v2.6.12 - * (c) 2014-2020 Evan You + * (c) 2014-2021 Evan You * Released under the MIT License. */ 'use strict'; -/* */ - +/* @flow */ var emptyObject = Object.freeze({}); - // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. -function isUndef (v) { - return v === undefined || v === null +function isUndef(v) { + return v === undefined || v === null; } - -function isDef (v) { - return v !== undefined && v !== null +function isDef(v) { + return v !== undefined && v !== null; } - -function isTrue (v) { - return v === true +function isTrue(v) { + return v === true; } - -function isFalse (v) { - return v === false +function isFalse(v) { + return v === false; } - /** * Check if value is primitive. */ -function isPrimitive (value) { - return ( - typeof value === 'string' || - typeof value === 'number' || - // $flow-disable-line - typeof value === 'symbol' || - typeof value === 'boolean' - ) +function isPrimitive(value) { + return (typeof value === 'string' || + typeof value === 'number' || + // $flow-disable-line + typeof value === 'symbol' || + typeof value === 'boolean'); } - /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ -function isObject (obj) { - return obj !== null && typeof obj === 'object' +function isObject(obj) { + return obj !== null && typeof obj === 'object'; } - /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; - -function toRawType (value) { - return _toString.call(value).slice(8, -1) +function toRawType(value) { + return _toString.call(value).slice(8, -1); } - /** * Strict object type check. Only returns true * for plain JavaScript objects. */ -function isPlainObject (obj) { - return _toString.call(obj) === '[object Object]' +function isPlainObject(obj) { + return _toString.call(obj) === '[object Object]'; } - -function isRegExp (v) { - return _toString.call(v) === '[object RegExp]' +function isRegExp(v) { + return _toString.call(v) === '[object RegExp]'; } - /** * Check if val is a valid array index. */ -function isValidArrayIndex (val) { - var n = parseFloat(String(val)); - return n >= 0 && Math.floor(n) === n && isFinite(val) +function isValidArrayIndex(val) { + var n = parseFloat(String(val)); + return n >= 0 && Math.floor(n) === n && isFinite(val); } - -function isPromise (val) { - return ( - isDef(val) && - typeof val.then === 'function' && - typeof val.catch === 'function' - ) +function isPromise(val) { + return (isDef(val) && + typeof val.then === 'function' && + typeof val.catch === 'function'); } - /** * Convert a value to a string that is actually rendered. */ -function toString (val) { - return val == null - ? '' - : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) - ? JSON.stringify(val, null, 2) - : String(val) +function toString(val) { + return val == null + ? '' + : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) + ? JSON.stringify(val, null, 2) + : String(val); } - /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ -function toNumber (val) { - var n = parseFloat(val); - return isNaN(n) ? val : n +function toNumber(val) { + var n = parseFloat(val); + return isNaN(n) ? val : n; } - /** * Make a map and return a function for checking if a key * is in that map. */ -function makeMap ( - str, - expectsLowerCase -) { - var map = Object.create(null); - var list = str.split(','); - for (var i = 0; i < list.length; i++) { - map[list[i]] = true; - } - return expectsLowerCase - ? function (val) { return map[val.toLowerCase()]; } - : function (val) { return map[val]; } +function makeMap(str, expectsLowerCase) { + var map = Object.create(null); + var list = str.split(','); + for (var i = 0; i < list.length; i++) { + map[list[i]] = true; + } + return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; }; } - /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); - /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); - /** * Remove an item from an array. */ -function remove (arr, item) { - if (arr.length) { - var index = arr.indexOf(item); - if (index > -1) { - return arr.splice(index, 1) +function remove(arr, item) { + if (arr.length) { + var index = arr.indexOf(item); + if (index > -1) { + return arr.splice(index, 1); + } } - } } - /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; -function hasOwn (obj, key) { - return hasOwnProperty.call(obj, key) +function hasOwn(obj, key) { + return hasOwnProperty.call(obj, key); } - /** * Create a cached version of a pure function. */ -function cached (fn) { - var cache = Object.create(null); - return (function cachedFn (str) { - var hit = cache[str]; - return hit || (cache[str] = fn(str)) - }) +function cached(fn) { + var cache = Object.create(null); + return function cachedFn(str) { + var hit = cache[str]; + return hit || (cache[str] = fn(str)); + }; } - /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { - return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) + return str.replace(camelizeRE, function (_, c) { return (c ? c.toUpperCase() : ''); }); }); - /** * Capitalize a string. */ var capitalize = cached(function (str) { - return str.charAt(0).toUpperCase() + str.slice(1) + return str.charAt(0).toUpperCase() + str.slice(1); }); - /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { - return str.replace(hyphenateRE, '-$1').toLowerCase() + return str.replace(hyphenateRE, '-$1').toLowerCase(); }); - /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore @@ -195,1113 +161,987 @@ var hyphenate = cached(function (str) { * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ - /* istanbul ignore next */ -function polyfillBind (fn, ctx) { - function boundFn (a) { - var l = arguments.length; - return l - ? l > 1 - ? fn.apply(ctx, arguments) - : fn.call(ctx, a) - : fn.call(ctx) - } - - boundFn._length = fn.length; - return boundFn -} - -function nativeBind (fn, ctx) { - return fn.bind(ctx) -} - -var bind = Function.prototype.bind - ? nativeBind - : polyfillBind; - +function polyfillBind(fn, ctx) { + function boundFn(a) { + var l = arguments.length; + return l + ? l > 1 + ? fn.apply(ctx, arguments) + : fn.call(ctx, a) + : fn.call(ctx); + } + boundFn._length = fn.length; + return boundFn; +} +function nativeBind(fn, ctx) { + return fn.bind(ctx); +} +// @ts-expect-error bind cannot be `undefined` +var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ -function toArray (list, start) { - start = start || 0; - var i = list.length - start; - var ret = new Array(i); - while (i--) { - ret[i] = list[i + start]; - } - return ret +function toArray(list, start) { + start = start || 0; + var i = list.length - start; + var ret = new Array(i); + while (i--) { + ret[i] = list[i + start]; + } + return ret; } - /** * Mix properties into target object. */ -function extend (to, _from) { - for (var key in _from) { - to[key] = _from[key]; - } - return to +function extend(to, _from) { + for (var key in _from) { + to[key] = _from[key]; + } + return to; } - /** * Merge an Array of Objects into a single Object. */ -function toObject (arr) { - var res = {}; - for (var i = 0; i < arr.length; i++) { - if (arr[i]) { - extend(res, arr[i]); +function toObject(arr) { + var res = {}; + for (var i = 0; i < arr.length; i++) { + if (arr[i]) { + extend(res, arr[i]); + } } - } - return res + return res; } - /* eslint-disable no-unused-vars */ - /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ -function noop (a, b, c) {} - +function noop(a, b, c) { } /** * Always return false. */ var no = function (a, b, c) { return false; }; - /* eslint-enable no-unused-vars */ - /** * Return the same value. */ var identity = function (_) { return _; }; - /** * Generate a string containing static keys from compiler modules. */ -function genStaticKeys (modules) { - return modules.reduce(function (keys, m) { - return keys.concat(m.staticKeys || []) - }, []).join(',') +function genStaticKeys(modules) { + return modules + .reduce(function (keys, m) { + return keys.concat(m.staticKeys || []); + }, []) + .join(','); } - /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ -function looseEqual (a, b) { - if (a === b) { return true } - var isObjectA = isObject(a); - var isObjectB = isObject(b); - if (isObjectA && isObjectB) { - try { - var isArrayA = Array.isArray(a); - var isArrayB = Array.isArray(b); - if (isArrayA && isArrayB) { - return a.length === b.length && a.every(function (e, i) { - return looseEqual(e, b[i]) - }) - } else if (a instanceof Date && b instanceof Date) { - return a.getTime() === b.getTime() - } else if (!isArrayA && !isArrayB) { - var keysA = Object.keys(a); - var keysB = Object.keys(b); - return keysA.length === keysB.length && keysA.every(function (key) { - return looseEqual(a[key], b[key]) - }) - } else { - /* istanbul ignore next */ - return false - } - } catch (e) { - /* istanbul ignore next */ - return false +function looseEqual(a, b) { + if (a === b) + { return true; } + var isObjectA = isObject(a); + var isObjectB = isObject(b); + if (isObjectA && isObjectB) { + try { + var isArrayA = Array.isArray(a); + var isArrayB = Array.isArray(b); + if (isArrayA && isArrayB) { + return (a.length === b.length && + a.every(function (e, i) { + return looseEqual(e, b[i]); + })); + } + else if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime(); + } + else if (!isArrayA && !isArrayB) { + var keysA = Object.keys(a); + var keysB = Object.keys(b); + return (keysA.length === keysB.length && + keysA.every(function (key) { + return looseEqual(a[key], b[key]); + })); + } + else { + /* istanbul ignore next */ + return false; + } + } + catch (e) { + /* istanbul ignore next */ + return false; + } + } + else if (!isObjectA && !isObjectB) { + return String(a) === String(b); + } + else { + return false; } - } else if (!isObjectA && !isObjectB) { - return String(a) === String(b) - } else { - return false - } } - /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ -function looseIndexOf (arr, val) { - for (var i = 0; i < arr.length; i++) { - if (looseEqual(arr[i], val)) { return i } - } - return -1 +function looseIndexOf(arr, val) { + for (var i = 0; i < arr.length; i++) { + if (looseEqual(arr[i], val)) + { return i; } + } + return -1; } - /** * Ensure a function is called only once. */ -function once (fn) { - var called = false; - return function () { - if (!called) { - called = true; - fn.apply(this, arguments); - } - } +function once(fn) { + var called = false; + return function () { + if (!called) { + called = true; + fn.apply(this, arguments); + } + }; } var SSR_ATTR = 'data-server-rendered'; - -var ASSET_TYPES = [ - 'component', - 'directive', - 'filter' -]; - +var ASSET_TYPES = ['component', 'directive', 'filter']; var LIFECYCLE_HOOKS = [ - 'beforeCreate', - 'created', - 'beforeMount', - 'mounted', - 'beforeUpdate', - 'updated', - 'beforeDestroy', - 'destroyed', - 'activated', - 'deactivated', - 'errorCaptured', - 'serverPrefetch' -]; - -/* */ - - - -var config = ({ - /** - * Option merge strategies (used in core/util/options) - */ - // $flow-disable-line - optionMergeStrategies: Object.create(null), - - /** - * Whether to suppress warnings. - */ - silent: false, - - /** - * Show production mode tip message on boot? - */ - productionTip: "development" !== 'production', - - /** - * Whether to enable devtools - */ - devtools: "development" !== 'production', - - /** - * Whether to record perf - */ - performance: false, - - /** - * Error handler for watcher errors - */ - errorHandler: null, - - /** - * Warn handler for watcher warns - */ - warnHandler: null, - - /** - * Ignore certain custom elements - */ - ignoredElements: [], - - /** - * Custom user key aliases for v-on - */ - // $flow-disable-line - keyCodes: Object.create(null), - - /** - * Check if a tag is reserved so that it cannot be registered as a - * component. This is platform-dependent and may be overwritten. - */ - isReservedTag: no, - - /** - * Check if an attribute is reserved so that it cannot be used as a component - * prop. This is platform-dependent and may be overwritten. - */ - isReservedAttr: no, - - /** - * Check if a tag is an unknown element. - * Platform-dependent. - */ - isUnknownElement: no, - - /** - * Get the namespace of an element - */ - getTagNamespace: noop, - - /** - * Parse the real tag name for the specific platform. - */ - parsePlatformTagName: identity, - - /** - * Check if an attribute must be bound using property, e.g. value - * Platform-dependent. - */ - mustUseProp: no, - - /** - * Perform updates asynchronously. Intended to be used by Vue Test Utils - * This will significantly reduce performance if set to false. - */ - async: true, - - /** - * Exposed for legacy reasons - */ - _lifecycleHooks: LIFECYCLE_HOOKS -}); - -/* */ + 'beforeCreate', + 'created', + 'beforeMount', + 'mounted', + 'beforeUpdate', + 'updated', + 'beforeDestroy', + 'destroyed', + 'activated', + 'deactivated', + 'errorCaptured', + 'serverPrefetch' ]; + +/* @flow */ +var config = { + /** + * Option merge strategies (used in core/util/options) + */ + // $flow-disable-line + optionMergeStrategies: Object.create(null), + /** + * Whether to suppress warnings. + */ + silent: false, + /** + * Show production mode tip message on boot? + */ + productionTip: "development" !== 'production', + /** + * Whether to enable devtools + */ + devtools: "development" !== 'production', + /** + * Whether to record perf + */ + performance: false, + /** + * Error handler for watcher errors + */ + errorHandler: null, + /** + * Warn handler for watcher warns + */ + warnHandler: null, + /** + * Ignore certain custom elements + */ + ignoredElements: [], + /** + * Custom user key aliases for v-on + */ + // $flow-disable-line + keyCodes: Object.create(null), + /** + * Check if a tag is reserved so that it cannot be registered as a + * component. This is platform-dependent and may be overwritten. + */ + isReservedTag: no, + /** + * Check if an attribute is reserved so that it cannot be used as a component + * prop. This is platform-dependent and may be overwritten. + */ + isReservedAttr: no, + /** + * Check if a tag is an unknown element. + * Platform-dependent. + */ + isUnknownElement: no, + /** + * Get the namespace of an element + */ + getTagNamespace: noop, + /** + * Parse the real tag name for the specific platform. + */ + parsePlatformTagName: identity, + /** + * Check if an attribute must be bound using property, e.g. value + * Platform-dependent. + */ + mustUseProp: no, + /** + * Perform updates asynchronously. Intended to be used by Vue Test Utils + * This will significantly reduce performance if set to false. + */ + async: true, + /** + * Exposed for legacy reasons + */ + _lifecycleHooks: LIFECYCLE_HOOKS, +}; +/* @flow */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; - /** * Check if a string starts with $ or _ */ -function isReserved (str) { - var c = (str + '').charCodeAt(0); - return c === 0x24 || c === 0x5F +function isReserved(str) { + var c = (str + '').charCodeAt(0); + return c === 0x24 || c === 0x5f; } - /** * Define a property. */ -function def (obj, key, val, enumerable) { - Object.defineProperty(obj, key, { - value: val, - enumerable: !!enumerable, - writable: true, - configurable: true - }); +function def(obj, key, val, enumerable) { + Object.defineProperty(obj, key, { + value: val, + enumerable: !!enumerable, + writable: true, + configurable: true, + }); } - /** * Parse simple path. */ var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); -function parsePath (path) { - if (bailRE.test(path)) { - return - } - var segments = path.split('.'); - return function (obj) { - for (var i = 0; i < segments.length; i++) { - if (!obj) { return } - obj = obj[segments[i]]; - } - return obj - } +function parsePath(path) { + if (bailRE.test(path)) { + return; + } + var segments = path.split('.'); + return function (obj) { + for (var i = 0; i < segments.length; i++) { + if (!obj) + { return; } + obj = obj[segments[i]]; + } + return obj; + }; } -/* */ - +/* @flow */ // can we use __proto__? var hasProto = '__proto__' in {}; - // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; -var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; +// @ts-ignore +var inWeex = +// @ts-ignore +typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; +// @ts-ignore var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; -var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); -var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); +var isAndroid = (UA && UA.indexOf('android') > 0) || weexPlatform === 'android'; +var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || weexPlatform === 'ios'; var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); - // Firefox has a "watch" function on Object.prototype... -var nativeWatch = ({}).watch; - +// @ts-ignore +var nativeWatch = {}.watch; var supportsPassive = false; if (inBrowser) { - try { - var opts = {}; - Object.defineProperty(opts, 'passive', ({ - get: function get () { - /* istanbul ignore next */ - supportsPassive = true; - } - })); // https://github.com/facebook/flow/issues/285 - window.addEventListener('test-passive', null, opts); - } catch (e) {} + try { + var opts = {}; + Object.defineProperty(opts, 'passive', { + get: function get() { + /* istanbul ignore next */ + supportsPassive = true; + }, + }); // https://github.com/facebook/flow/issues/285 + // @ts-ignore + window.addEventListener('test-passive', null, opts); + } + catch (e) { } } - // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { - if (_isServer === undefined) { - /* istanbul ignore if */ - if (!inBrowser && !inWeex && typeof global !== 'undefined') { - // detect presence of vue-server-renderer and avoid - // Webpack shimming the process - _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; - } else { - _isServer = false; - } - } - return _isServer + if (_isServer === undefined) { + /* istanbul ignore if */ + if (!inBrowser && !inWeex && typeof global !== 'undefined') { + // detect presence of vue-server-renderer and avoid + // Webpack shimming the process + _isServer = + global['process'] && global['process'].env.VUE_ENV === 'server'; + } + else { + _isServer = false; + } + } + return _isServer; }; - // detect devtools +// @ts-ignore TODO decalre this types var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; - /* istanbul ignore next */ -function isNative (Ctor) { - return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) -} - -var hasSymbol = - typeof Symbol !== 'undefined' && isNative(Symbol) && - typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); - -var _Set; -/* istanbul ignore if */ // $flow-disable-line -if (typeof Set !== 'undefined' && isNative(Set)) { - // use native Set when available. - _Set = Set; -} else { - // a non-standard Set polyfill that only works with primitive keys. - _Set = /*@__PURE__*/(function () { - function Set () { - this.set = Object.create(null); - } - Set.prototype.has = function has (key) { - return this.set[key] === true - }; - Set.prototype.add = function add (key) { - this.set[key] = true; - }; - Set.prototype.clear = function clear () { - this.set = Object.create(null); - }; +function isNative(Ctor) { + return typeof Ctor === 'function' && /native code/.test(Ctor.toString()); +} +var hasSymbol = typeof Symbol !== 'undefined' && + isNative(Symbol) && + typeof Reflect !== 'undefined' && + isNative(Reflect.ownKeys); +var _Set; // $flow-disable-line +/* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { + // use native Set when available. + _Set = Set; +} +else { + // a non-standard Set polyfill that only works with primitive keys. + _Set = /*@__PURE__*/(function () { + function Set() { + this.set = Object.create(null); + } + Set.prototype.has = function has (key) { + return this.set[key] === true; + }; + Set.prototype.add = function add (key) { + this.set[key] = true; + }; + Set.prototype.clear = function clear () { + this.set = Object.create(null); + }; - return Set; - }()); + return Set; + }()); } -/* */ - +/* @flow */ var warn = noop; var tip = noop; -var generateComponentTrace = (noop); // work around flow check -var formatComponentName = (noop); - +var generateComponentTrace; // work around flow check +var formatComponentName; { - var hasConsole = typeof console !== 'undefined'; - var classifyRE = /(?:^|[-_])(\w)/g; - var classify = function (str) { return str - .replace(classifyRE, function (c) { return c.toUpperCase(); }) - .replace(/[-_]/g, ''); }; - - warn = function (msg, vm) { - var trace = vm ? generateComponentTrace(vm) : ''; - - if (config.warnHandler) { - config.warnHandler.call(null, msg, vm, trace); - } else if (hasConsole && (!config.silent)) { - console.error(("[Vue warn]: " + msg + trace)); - } - }; - - tip = function (msg, vm) { - if (hasConsole && (!config.silent)) { - console.warn("[Vue tip]: " + msg + ( - vm ? generateComponentTrace(vm) : '' - )); - } - }; - - formatComponentName = function (vm, includeFile) { - if (vm.$root === vm) { - return '' - } - var options = typeof vm === 'function' && vm.cid != null - ? vm.options - : vm._isVue - ? vm.$options || vm.constructor.options - : vm; - var name = options.name || options._componentTag; - var file = options.__file; - if (!name && file) { - var match = file.match(/([^/\\]+)\.vue$/); - name = match && match[1]; - } - - return ( - (name ? ("<" + (classify(name)) + ">") : "") + - (file && includeFile !== false ? (" at " + file) : '') - ) - }; - - var repeat = function (str, n) { - var res = ''; - while (n) { - if (n % 2 === 1) { res += str; } - if (n > 1) { str += str; } - n >>= 1; - } - return res - }; - - generateComponentTrace = function (vm) { - if (vm._isVue && vm.$parent) { - var tree = []; - var currentRecursiveSequence = 0; - while (vm) { - if (tree.length > 0) { - var last = tree[tree.length - 1]; - if (last.constructor === vm.constructor) { - currentRecursiveSequence++; - vm = vm.$parent; - continue - } else if (currentRecursiveSequence > 0) { - tree[tree.length - 1] = [last, currentRecursiveSequence]; - currentRecursiveSequence = 0; - } - } - tree.push(vm); - vm = vm.$parent; - } - return '\n\nfound in\n\n' + tree - .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) - ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") - : formatComponentName(vm))); }) - .join('\n') - } else { - return ("\n\n(found in " + (formatComponentName(vm)) + ")") - } - }; -} - -/* */ + var hasConsole = typeof console !== 'undefined'; + var classifyRE = /(?:^|[-_])(\w)/g; + var classify = function (str) { return str.replace(classifyRE, function (c) { return c.toUpperCase(); }).replace(/[-_]/g, ''); }; + warn = function (msg, vm) { + var trace = vm ? generateComponentTrace(vm) : ''; + if (config.warnHandler) { + config.warnHandler.call(null, msg, vm, trace); + } + else if (hasConsole && !config.silent) { + console.error(("[Vue warn]: " + msg + trace)); + } + }; + tip = function (msg, vm) { + if (hasConsole && !config.silent) { + console.warn("[Vue tip]: " + msg + (vm ? generateComponentTrace(vm) : '')); + } + }; + formatComponentName = function (vm, includeFile) { + if (vm.$root === vm) { + return ''; + } + var options = + // @ts-ignore + typeof vm === 'function' && vm.cid != null + ? // @ts-ignore + vm.options + : vm._isVue + ? // @ts-ignore + vm.$options || vm.constructor.options + : vm; + var name = options.name || options._componentTag; + var file = options.__file; + if (!name && file) { + var match = file.match(/([^/\\]+)\.vue$/); + name = match && match[1]; + } + return ((name ? ("<" + (classify(name)) + ">") : "") + + (file && includeFile !== false ? (" at " + file) : '')); + }; + var repeat = function (str, n) { + var res = ''; + while (n) { + if (n % 2 === 1) + { res += str; } + if (n > 1) + { str += str; } + n >>= 1; + } + return res; + }; + generateComponentTrace = function (vm) { + // @ts-ignore + if (vm._isVue && vm.$parent) { + var tree = []; + var currentRecursiveSequence = 0; + while (vm) { + if (tree.length > 0) { + var last = tree[tree.length - 1]; + if (last.constructor === vm.constructor) { + currentRecursiveSequence++; + vm = vm.$parent; + continue; + } + else if (currentRecursiveSequence > 0) { + tree[tree.length - 1] = [last, currentRecursiveSequence]; + currentRecursiveSequence = 0; + } + } + tree.push(vm); + vm = vm.$parent; + } + return ('\n\nfound in\n\n' + + tree + .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) + ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") + : formatComponentName(vm))); }) + .join('\n')); + } + else { + return ("\n\n(found in " + (formatComponentName(vm)) + ")"); + } + }; +} var uid = 0; - /** * A dep is an observable that can have multiple * directives subscribing to it. */ -var Dep = function Dep () { - this.id = uid++; - this.subs = []; +var Dep = function Dep() { + this.id = uid++; + this.subs = []; }; - Dep.prototype.addSub = function addSub (sub) { - this.subs.push(sub); + this.subs.push(sub); }; - Dep.prototype.removeSub = function removeSub (sub) { - remove(this.subs, sub); + remove(this.subs, sub); }; - Dep.prototype.depend = function depend () { - if (Dep.target) { - Dep.target.addDep(this); - } + if (Dep.target) { + Dep.target.addDep(this); + } }; - Dep.prototype.notify = function notify () { - // stabilize the subscriber list first - var subs = this.subs.slice(); - if (!config.async) { - // subs aren't sorted in scheduler if not running async - // we need to sort them now to make sure they fire in correct - // order - subs.sort(function (a, b) { return a.id - b.id; }); - } - for (var i = 0, l = subs.length; i < l; i++) { - subs[i].update(); - } + // stabilize the subscriber list first + var subs = this.subs.slice(); + if (!config.async) { + // subs aren't sorted in scheduler if not running async + // we need to sort them now to make sure they fire in correct + // order + subs.sort(function (a, b) { return a.id - b.id; }); + } + for (var i = 0, l = subs.length; i < l; i++) { + subs[i].update(); + } }; - // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; - -function pushTarget (target) { - targetStack.push(target); - Dep.target = target; -} - -function popTarget () { - targetStack.pop(); - Dep.target = targetStack[targetStack.length - 1]; -} - -/* */ - -var VNode = function VNode ( - tag, - data, - children, - text, - elm, - context, - componentOptions, - asyncFactory -) { - this.tag = tag; - this.data = data; - this.children = children; - this.text = text; - this.elm = elm; - this.ns = undefined; - this.context = context; - this.fnContext = undefined; - this.fnOptions = undefined; - this.fnScopeId = undefined; - this.key = data && data.key; - this.componentOptions = componentOptions; - this.componentInstance = undefined; - this.parent = undefined; - this.raw = false; - this.isStatic = false; - this.isRootInsert = true; - this.isComment = false; - this.isCloned = false; - this.isOnce = false; - this.asyncFactory = asyncFactory; - this.asyncMeta = undefined; - this.isAsyncPlaceholder = false; +function pushTarget(target) { + targetStack.push(target); + Dep.target = target; +} +function popTarget() { + targetStack.pop(); + Dep.target = targetStack[targetStack.length - 1]; +} + +var VNode = function VNode(tag, data, children, text, elm, context, componentOptions, asyncFactory) { + this.tag = tag; + this.data = data; + this.children = children; + this.text = text; + this.elm = elm; + this.ns = undefined; + this.context = context; + this.fnContext = undefined; + this.fnOptions = undefined; + this.fnScopeId = undefined; + this.key = data && data.key; + this.componentOptions = componentOptions; + this.componentInstance = undefined; + this.parent = undefined; + this.raw = false; + this.isStatic = false; + this.isRootInsert = true; + this.isComment = false; + this.isCloned = false; + this.isOnce = false; + this.asyncFactory = asyncFactory; + this.asyncMeta = undefined; + this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; - // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { - return this.componentInstance + return this.componentInstance; }; Object.defineProperties( VNode.prototype, prototypeAccessors ); - var createEmptyVNode = function (text) { - if ( text === void 0 ) text = ''; + if ( text === void 0 ) text = ''; - var node = new VNode(); - node.text = text; - node.isComment = true; - return node + var node = new VNode(); + node.text = text; + node.isComment = true; + return node; }; - -function createTextVNode (val) { - return new VNode(undefined, undefined, undefined, String(val)) +function createTextVNode(val) { + return new VNode(undefined, undefined, undefined, String(val)); } - // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. -function cloneVNode (vnode) { - var cloned = new VNode( - vnode.tag, - vnode.data, +function cloneVNode(vnode) { + var cloned = new VNode( + //@ts-expect-error void type not valid here + vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. - vnode.children && vnode.children.slice(), - vnode.text, - vnode.elm, - vnode.context, - vnode.componentOptions, - vnode.asyncFactory - ); - cloned.ns = vnode.ns; - cloned.isStatic = vnode.isStatic; - cloned.key = vnode.key; - cloned.isComment = vnode.isComment; - cloned.fnContext = vnode.fnContext; - cloned.fnOptions = vnode.fnOptions; - cloned.fnScopeId = vnode.fnScopeId; - cloned.asyncMeta = vnode.asyncMeta; - cloned.isCloned = true; - return cloned + vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory); + cloned.ns = vnode.ns; + cloned.isStatic = vnode.isStatic; + cloned.key = vnode.key; + cloned.isComment = vnode.isComment; + cloned.fnContext = vnode.fnContext; + cloned.fnOptions = vnode.fnOptions; + cloned.fnScopeId = vnode.fnScopeId; + cloned.asyncMeta = vnode.asyncMeta; + cloned.isCloned = true; + return cloned; } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ - var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); - var methodsToPatch = [ - 'push', - 'pop', - 'shift', - 'unshift', - 'splice', - 'sort', - 'reverse' -]; - + 'push', + 'pop', + 'shift', + 'unshift', + 'splice', + 'sort', + 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { - // cache original method - var original = arrayProto[method]; - def(arrayMethods, method, function mutator () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - var result = original.apply(this, args); - var ob = this.__ob__; - var inserted; - switch (method) { - case 'push': - case 'unshift': - inserted = args; - break - case 'splice': - inserted = args.slice(2); - break - } - if (inserted) { ob.observeArray(inserted); } - // notify change - ob.dep.notify(); - return result - }); + // cache original method + var original = arrayProto[method]; + def(arrayMethods, method, function mutator() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var result = original.apply(this, args); + var ob = this.__ob__; + var inserted; + switch (method) { + case 'push': + case 'unshift': + inserted = args; + break; + case 'splice': + inserted = args.slice(2); + break; + } + if (inserted) + { ob.observeArray(inserted); } + // notify change + ob.dep.notify(); + return result; + }); }); -/* */ - var arrayKeys = Object.getOwnPropertyNames(arrayMethods); - /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; - -function toggleObserving (value) { - shouldObserve = value; +function toggleObserving(value) { + shouldObserve = value; } - /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ -var Observer = function Observer (value) { - this.value = value; - this.dep = new Dep(); - this.vmCount = 0; - def(value, '__ob__', this); - if (Array.isArray(value)) { - if (hasProto) { - protoAugment(value, arrayMethods); - } else { - copyAugment(value, arrayMethods, arrayKeys); - } - this.observeArray(value); - } else { - this.walk(value); - } +var Observer = function Observer(value) { + this.value = value; + this.dep = new Dep(); + this.vmCount = 0; + def(value, '__ob__', this); + if (Array.isArray(value)) { + if (hasProto) { + protoAugment(value, arrayMethods); + } + else { + copyAugment(value, arrayMethods, arrayKeys); + } + this.observeArray(value); + } + else { + this.walk(value); + } }; - /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { - defineReactive$$1(obj, keys[i]); - } + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + defineReactive$$1(obj, keys[i]); + } }; - /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { - for (var i = 0, l = items.length; i < l; i++) { - observe(items[i]); - } + for (var i = 0, l = items.length; i < l; i++) { + observe(items[i]); + } }; - // helpers - /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ -function protoAugment (target, src) { - /* eslint-disable no-proto */ - target.__proto__ = src; - /* eslint-enable no-proto */ +function protoAugment(target, src) { + /* eslint-disable no-proto */ + target.__proto__ = src; + /* eslint-enable no-proto */ } - /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ -function copyAugment (target, src, keys) { - for (var i = 0, l = keys.length; i < l; i++) { - var key = keys[i]; - def(target, key, src[key]); - } +function copyAugment(target, src, keys) { + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + def(target, key, src[key]); + } } - /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ -function observe (value, asRootData) { - if (!isObject(value) || value instanceof VNode) { - return - } - var ob; - if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { - ob = value.__ob__; - } else if ( - shouldObserve && - !isServerRendering() && - (Array.isArray(value) || isPlainObject(value)) && - Object.isExtensible(value) && - !value._isVue - ) { - ob = new Observer(value); - } - if (asRootData && ob) { - ob.vmCount++; - } - return ob +function observe(value, asRootData) { + if (!isObject(value) || value instanceof VNode) { + return; + } + var ob; + if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { + ob = value.__ob__; + } + else if (shouldObserve && + !isServerRendering() && + (Array.isArray(value) || isPlainObject(value)) && + Object.isExtensible(value) && + !value._isVue) { + ob = new Observer(value); + } + if (asRootData && ob) { + ob.vmCount++; + } + return ob; } - /** * Define a reactive property on an Object. */ -function defineReactive$$1 ( - obj, - key, - val, - customSetter, - shallow -) { - var dep = new Dep(); - - var property = Object.getOwnPropertyDescriptor(obj, key); - if (property && property.configurable === false) { - return - } - - // cater for pre-defined getter/setters - var getter = property && property.get; - var setter = property && property.set; - if ((!getter || setter) && arguments.length === 2) { - val = obj[key]; - } - - var childOb = !shallow && observe(val); - Object.defineProperty(obj, key, { - enumerable: true, - configurable: true, - get: function reactiveGetter () { - var value = getter ? getter.call(obj) : val; - if (Dep.target) { - dep.depend(); - if (childOb) { - childOb.dep.depend(); - if (Array.isArray(value)) { - dependArray(value); - } - } - } - return value - }, - set: function reactiveSetter (newVal) { - var value = getter ? getter.call(obj) : val; - /* eslint-disable no-self-compare */ - if (newVal === value || (newVal !== newVal && value !== value)) { - return - } - /* eslint-enable no-self-compare */ - if (customSetter) { - customSetter(); - } - // #7981: for accessor properties without setter - if (getter && !setter) { return } - if (setter) { - setter.call(obj, newVal); - } else { - val = newVal; - } - childOb = !shallow && observe(newVal); - dep.notify(); - } - }); +function defineReactive$$1(obj, key, val, customSetter, shallow) { + var dep = new Dep(); + var property = Object.getOwnPropertyDescriptor(obj, key); + if (property && property.configurable === false) { + return; + } + // cater for pre-defined getter/setters + var getter = property && property.get; + var setter = property && property.set; + if ((!getter || setter) && arguments.length === 2) { + val = obj[key]; + } + var childOb = !shallow && observe(val); + Object.defineProperty(obj, key, { + enumerable: true, + configurable: true, + get: function reactiveGetter() { + var value = getter ? getter.call(obj) : val; + if (Dep.target) { + dep.depend(); + if (childOb) { + childOb.dep.depend(); + if (Array.isArray(value)) { + dependArray(value); + } + } + } + return value; + }, + set: function reactiveSetter(newVal) { + var value = getter ? getter.call(obj) : val; + /* eslint-disable no-self-compare */ + if (newVal === value || (newVal !== newVal && value !== value)) { + return; + } + /* eslint-enable no-self-compare */ + if (customSetter) { + customSetter(); + } + // #7981: for accessor properties without setter + if (getter && !setter) + { return; } + if (setter) { + setter.call(obj, newVal); + } + else { + val = newVal; + } + childOb = !shallow && observe(newVal); + dep.notify(); + }, + }); } - /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ -function set (target, key, val) { - if (isUndef(target) || isPrimitive(target) - ) { - warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); - } - if (Array.isArray(target) && isValidArrayIndex(key)) { - target.length = Math.max(target.length, key); - target.splice(key, 1, val); - return val - } - if (key in target && !(key in Object.prototype)) { - target[key] = val; - return val - } - var ob = (target).__ob__; - if (target._isVue || (ob && ob.vmCount)) { - warn( - 'Avoid adding reactive properties to a Vue instance or its root $data ' + - 'at runtime - declare it upfront in the data option.' - ); - return val - } - if (!ob) { - target[key] = val; - return val - } - defineReactive$$1(ob.value, key, val); - ob.dep.notify(); - return val +function set(target, key, val) { + if (isUndef(target) || isPrimitive(target)) { + warn(("Cannot set reactive property on undefined, null, or primitive value: " + target)); + } + if (Array.isArray(target) && isValidArrayIndex(key)) { + target.length = Math.max(target.length, key); + target.splice(key, 1, val); + return val; + } + if (key in target && !(key in Object.prototype)) { + target[key] = val; + return val; + } + var ob = target.__ob__; + // @ts-ignore + if (target._isVue || (ob && ob.vmCount)) { + warn('Avoid adding reactive properties to a Vue instance or its root $data ' + + 'at runtime - declare it upfront in the data option.'); + return val; + } + if (!ob) { + target[key] = val; + return val; + } + defineReactive$$1(ob.value, key, val); + ob.dep.notify(); + return val; } - /** * Delete a property and trigger change if necessary. */ -function del (target, key) { - if (isUndef(target) || isPrimitive(target) - ) { - warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); - } - if (Array.isArray(target) && isValidArrayIndex(key)) { - target.splice(key, 1); - return - } - var ob = (target).__ob__; - if (target._isVue || (ob && ob.vmCount)) { - warn( - 'Avoid deleting properties on a Vue instance or its root $data ' + - '- just set it to null.' - ); - return - } - if (!hasOwn(target, key)) { - return - } - delete target[key]; - if (!ob) { - return - } - ob.dep.notify(); +function del(target, key) { + if (isUndef(target) || isPrimitive(target)) { + warn(("Cannot delete reactive property on undefined, null, or primitive value: " + target)); + } + if (Array.isArray(target) && isValidArrayIndex(key)) { + target.splice(key, 1); + return; + } + var ob = target.__ob__; + //@ts-ignore + if (target._isVue || (ob && ob.vmCount)) { + warn('Avoid deleting properties on a Vue instance or its root $data ' + + '- just set it to null.'); + return; + } + if (!hasOwn(target, key)) { + return; + } + delete target[key]; + if (!ob) { + return; + } + ob.dep.notify(); } - /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ -function dependArray (value) { - for (var e = (void 0), i = 0, l = value.length; i < l; i++) { - e = value[i]; - e && e.__ob__ && e.__ob__.dep.depend(); - if (Array.isArray(e)) { - dependArray(e); +function dependArray(value) { + for (var e = (void 0), i = 0, l = value.length; i < l; i++) { + e = value[i]; + e && e.__ob__ && e.__ob__.dep.depend(); + if (Array.isArray(e)) { + dependArray(e); + } } - } } -/* */ - +/* @flow */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; - /** * Options with restrictions */ { - strats.el = strats.propsData = function (parent, child, vm, key) { - if (!vm) { - warn( - "option \"" + key + "\" can only be used during instance " + - 'creation with the `new` keyword.' - ); - } - return defaultStrat(parent, child) - }; + strats.el = strats.propsData = function (parent, child, vm, key) { + if (!vm) { + warn("option \"" + key + "\" can only be used during instance " + + 'creation with the `new` keyword.'); + } + return defaultStrat(parent, child); + }; } - /** * Helper that recursively merges two data objects together. */ -function mergeData (to, from) { - if (!from) { return to } - var key, toVal, fromVal; - - var keys = hasSymbol - ? Reflect.ownKeys(from) - : Object.keys(from); - - for (var i = 0; i < keys.length; i++) { - key = keys[i]; - // in case the object is already observed... - if (key === '__ob__') { continue } - toVal = to[key]; - fromVal = from[key]; - if (!hasOwn(to, key)) { - set(to, key, fromVal); - } else if ( - toVal !== fromVal && - isPlainObject(toVal) && - isPlainObject(fromVal) - ) { - mergeData(toVal, fromVal); - } - } - return to +function mergeData(to, from) { + if (!from) + { return to; } + var key, toVal, fromVal; + var keys = hasSymbol + ? Reflect.ownKeys(from) + : Object.keys(from); + for (var i = 0; i < keys.length; i++) { + key = keys[i]; + // in case the object is already observed... + if (key === '__ob__') + { continue; } + toVal = to[key]; + fromVal = from[key]; + if (!hasOwn(to, key)) { + set(to, key, fromVal); + } + else if (toVal !== fromVal && + isPlainObject(toVal) && + isPlainObject(fromVal)) { + mergeData(toVal, fromVal); + } + } + return to; } - /** * Data */ -function mergeDataOrFn ( - parentVal, - childVal, - vm -) { - if (!vm) { - // in a Vue.extend merge, both should be functions - if (!childVal) { - return parentVal - } - if (!parentVal) { - return childVal - } - // when parentVal & childVal are both present, - // we need to return a function that returns the - // merged result of both functions... no need to - // check if parentVal is a function here because - // it has to be a function to pass previous merges. - return function mergedDataFn () { - return mergeData( - typeof childVal === 'function' ? childVal.call(this, this) : childVal, - typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal - ) - } - } else { - return function mergedInstanceDataFn () { - // instance merge - var instanceData = typeof childVal === 'function' - ? childVal.call(vm, vm) - : childVal; - var defaultData = typeof parentVal === 'function' - ? parentVal.call(vm, vm) - : parentVal; - if (instanceData) { - return mergeData(instanceData, defaultData) - } else { - return defaultData - } - } - } -} - -strats.data = function ( - parentVal, - childVal, - vm -) { - if (!vm) { - if (childVal && typeof childVal !== 'function') { - warn( - 'The "data" option should be a function ' + - 'that returns a per-instance value in component ' + - 'definitions.', - vm - ); - - return parentVal - } - return mergeDataOrFn(parentVal, childVal) - } - - return mergeDataOrFn(parentVal, childVal, vm) +function mergeDataOrFn(parentVal, childVal, vm) { + if (!vm) { + // in a Vue.extend merge, both should be functions + if (!childVal) { + return parentVal; + } + if (!parentVal) { + return childVal; + } + // when parentVal & childVal are both present, + // we need to return a function that returns the + // merged result of both functions... no need to + // check if parentVal is a function here because + // it has to be a function to pass previous merges. + return function mergedDataFn() { + return mergeData( + // @ts-ignore + typeof childVal === 'function' ? childVal.call(this, this) : childVal, + // @ts-ignore + typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal); + }; + } + else { + return function mergedInstanceDataFn() { + // instance merge + var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; + var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; + if (instanceData) { + return mergeData(instanceData, defaultData); + } + else { + return defaultData; + } + }; + } +} +strats.data = function (parentVal, childVal, vm) { + if (!vm) { + if (childVal && typeof childVal !== 'function') { + warn('The "data" option should be a function ' + + 'that returns a per-instance value in component ' + + 'definitions.', vm); + return parentVal; + } + return mergeDataOrFn(parentVal, childVal); + } + return mergeDataOrFn(parentVal, childVal, vm); }; - /** * Hooks and props are merged as arrays. */ -function mergeHook ( - parentVal, - childVal -) { - var res = childVal - ? parentVal - ? parentVal.concat(childVal) - : Array.isArray(childVal) - ? childVal - : [childVal] - : parentVal; - return res - ? dedupeHooks(res) - : res -} - -function dedupeHooks (hooks) { - var res = []; - for (var i = 0; i < hooks.length; i++) { - if (res.indexOf(hooks[i]) === -1) { - res.push(hooks[i]); - } - } - return res +function mergeHook(parentVal, childVal) { + var res = childVal + ? parentVal + ? parentVal.concat(childVal) + : Array.isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + var res = []; + for (var i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; } - LIFECYCLE_HOOKS.forEach(function (hook) { - strats[hook] = mergeHook; + strats[hook] = mergeHook; }); - /** * Assets * @@ -1309,609 +1149,540 @@ LIFECYCLE_HOOKS.forEach(function (hook) { * a three-way merge between constructor options, instance * options and parent options. */ -function mergeAssets ( - parentVal, - childVal, - vm, - key -) { - var res = Object.create(parentVal || null); - if (childVal) { - assertObjectType(key, childVal, vm); - return extend(res, childVal) - } else { - return res - } +function mergeAssets(parentVal, childVal, vm, key) { + var res = Object.create(parentVal || null); + if (childVal) { + assertObjectType(key, childVal, vm); + return extend(res, childVal); + } + else { + return res; + } } - ASSET_TYPES.forEach(function (type) { - strats[type + 's'] = mergeAssets; + strats[type + 's'] = mergeAssets; }); - /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ -strats.watch = function ( - parentVal, - childVal, - vm, - key -) { - // work around Firefox's Object.prototype.watch... - if (parentVal === nativeWatch) { parentVal = undefined; } - if (childVal === nativeWatch) { childVal = undefined; } - /* istanbul ignore if */ - if (!childVal) { return Object.create(parentVal || null) } - { - assertObjectType(key, childVal, vm); - } - if (!parentVal) { return childVal } - var ret = {}; - extend(ret, parentVal); - for (var key$1 in childVal) { - var parent = ret[key$1]; - var child = childVal[key$1]; - if (parent && !Array.isArray(parent)) { - parent = [parent]; - } - ret[key$1] = parent - ? parent.concat(child) - : Array.isArray(child) ? child : [child]; - } - return ret +strats.watch = function (parentVal, childVal, vm, key) { + // work around Firefox's Object.prototype.watch... + //@ts-expect-error work around + if (parentVal === nativeWatch) + { parentVal = undefined; } + //@ts-expect-error work around + if (childVal === nativeWatch) + { childVal = undefined; } + /* istanbul ignore if */ + if (!childVal) + { return Object.create(parentVal || null); } + { + assertObjectType(key, childVal, vm); + } + if (!parentVal) + { return childVal; } + var ret = {}; + extend(ret, parentVal); + for (var key$1 in childVal) { + var parent = ret[key$1]; + var child = childVal[key$1]; + if (parent && !Array.isArray(parent)) { + parent = [parent]; + } + ret[key$1] = parent + ? parent.concat(child) + : Array.isArray(child) + ? child + : [child]; + } + return ret; }; - /** * Other object hashes. */ -strats.props = -strats.methods = -strats.inject = -strats.computed = function ( - parentVal, - childVal, - vm, - key -) { - if (childVal && "development" !== 'production') { - assertObjectType(key, childVal, vm); - } - if (!parentVal) { return childVal } - var ret = Object.create(null); - extend(ret, parentVal); - if (childVal) { extend(ret, childVal); } - return ret +strats.props = strats.methods = strats.inject = strats.computed = function (parentVal, childVal, vm, key) { + if (childVal && "development" !== 'production') { + assertObjectType(key, childVal, vm); + } + if (!parentVal) + { return childVal; } + var ret = Object.create(null); + extend(ret, parentVal); + if (childVal) + { extend(ret, childVal); } + return ret; }; strats.provide = mergeDataOrFn; - /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { - return childVal === undefined - ? parentVal - : childVal + return childVal === undefined ? parentVal : childVal; }; - /** * Validate component names */ -function checkComponents (options) { - for (var key in options.components) { - validateComponentName(key); - } +function checkComponents(options) { + for (var key in options.components) { + validateComponentName(key); + } } - -function validateComponentName (name) { - if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { - warn( - 'Invalid component name: "' + name + '". Component names ' + - 'should conform to valid custom element name in html5 specification.' - ); - } - if (isBuiltInTag(name) || config.isReservedTag(name)) { - warn( - 'Do not use built-in or reserved HTML elements as component ' + - 'id: ' + name - ); - } +function validateComponentName(name) { + if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { + warn('Invalid component name: "' + + name + + '". Component names ' + + 'should conform to valid custom element name in html5 specification.'); + } + if (isBuiltInTag(name) || config.isReservedTag(name)) { + warn('Do not use built-in or reserved HTML elements as component ' + + 'id: ' + + name); + } } - /** * Ensure all props option syntax are normalized into the * Object-based format. */ -function normalizeProps (options, vm) { - var props = options.props; - if (!props) { return } - var res = {}; - var i, val, name; - if (Array.isArray(props)) { - i = props.length; - while (i--) { - val = props[i]; - if (typeof val === 'string') { - name = camelize(val); - res[name] = { type: null }; - } else { - warn('props must be strings when using array syntax.'); - } - } - } else if (isPlainObject(props)) { - for (var key in props) { - val = props[key]; - name = camelize(key); - res[name] = isPlainObject(val) - ? val - : { type: val }; - } - } else { - warn( - "Invalid value for option \"props\": expected an Array or an Object, " + - "but got " + (toRawType(props)) + ".", - vm - ); - } - options.props = res; -} - +function normalizeProps(options, vm) { + var props = options.props; + if (!props) + { return; } + var res = {}; + var i, val, name; + if (Array.isArray(props)) { + i = props.length; + while (i--) { + val = props[i]; + if (typeof val === 'string') { + name = camelize(val); + res[name] = { type: null }; + } + else { + warn('props must be strings when using array syntax.'); + } + } + } + else if (isPlainObject(props)) { + for (var key in props) { + val = props[key]; + name = camelize(key); + res[name] = isPlainObject(val) ? val : { type: val }; + } + } + else { + warn("Invalid value for option \"props\": expected an Array or an Object, " + + "but got " + (toRawType(props)) + ".", vm); + } + options.props = res; +} /** * Normalize all injections into Object-based format */ -function normalizeInject (options, vm) { - var inject = options.inject; - if (!inject) { return } - var normalized = options.inject = {}; - if (Array.isArray(inject)) { - for (var i = 0; i < inject.length; i++) { - normalized[inject[i]] = { from: inject[i] }; - } - } else if (isPlainObject(inject)) { - for (var key in inject) { - var val = inject[key]; - normalized[key] = isPlainObject(val) - ? extend({ from: key }, val) - : { from: val }; - } - } else { - warn( - "Invalid value for option \"inject\": expected an Array or an Object, " + - "but got " + (toRawType(inject)) + ".", - vm - ); - } +function normalizeInject(options, vm) { + var inject = options.inject; + if (!inject) + { return; } + var normalized = (options.inject = {}); + if (Array.isArray(inject)) { + for (var i = 0; i < inject.length; i++) { + normalized[inject[i]] = { from: inject[i] }; + } + } + else if (isPlainObject(inject)) { + for (var key in inject) { + var val = inject[key]; + normalized[key] = isPlainObject(val) + ? extend({ from: key }, val) + : { from: val }; + } + } + else { + warn("Invalid value for option \"inject\": expected an Array or an Object, " + + "but got " + (toRawType(inject)) + ".", vm); + } } - /** * Normalize raw function directives into object format. */ -function normalizeDirectives (options) { - var dirs = options.directives; - if (dirs) { - for (var key in dirs) { - var def$$1 = dirs[key]; - if (typeof def$$1 === 'function') { - dirs[key] = { bind: def$$1, update: def$$1 }; - } - } - } -} - -function assertObjectType (name, value, vm) { - if (!isPlainObject(value)) { - warn( - "Invalid value for option \"" + name + "\": expected an Object, " + - "but got " + (toRawType(value)) + ".", - vm - ); - } +function normalizeDirectives(options) { + var dirs = options.directives; + if (dirs) { + for (var key in dirs) { + var def$$1 = dirs[key]; + if (typeof def$$1 === 'function') { + dirs[key] = { bind: def$$1, update: def$$1 }; + } + } + } +} +function assertObjectType(name, value, vm) { + if (!isPlainObject(value)) { + warn("Invalid value for option \"" + name + "\": expected an Object, " + + "but got " + (toRawType(value)) + ".", vm); + } } - /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ -function mergeOptions ( - parent, - child, - vm -) { - { - checkComponents(child); - } - - if (typeof child === 'function') { - child = child.options; - } - - normalizeProps(child, vm); - normalizeInject(child, vm); - normalizeDirectives(child); - - // Apply extends and mixins on the child options, - // but only if it is a raw options object that isn't - // the result of another mergeOptions call. - // Only merged options has the _base property. - if (!child._base) { - if (child.extends) { - parent = mergeOptions(parent, child.extends, vm); - } - if (child.mixins) { - for (var i = 0, l = child.mixins.length; i < l; i++) { - parent = mergeOptions(parent, child.mixins[i], vm); - } - } - } - - var options = {}; - var key; - for (key in parent) { - mergeField(key); - } - for (key in child) { - if (!hasOwn(parent, key)) { - mergeField(key); - } - } - function mergeField (key) { - var strat = strats[key] || defaultStrat; - options[key] = strat(parent[key], child[key], vm, key); - } - return options +function mergeOptions(parent, child, vm) { + { + checkComponents(child); + } + if (typeof child === 'function') { + // @ts-expect-error + child = child.options; + } + normalizeProps(child, vm); + normalizeInject(child, vm); + normalizeDirectives(child); + // Apply extends and mixins on the child options, + // but only if it is a raw options object that isn't + // the result of another mergeOptions call. + // Only merged options has the _base property. + if (!child._base) { + if (child.extends) { + parent = mergeOptions(parent, child.extends, vm); + } + if (child.mixins) { + for (var i = 0, l = child.mixins.length; i < l; i++) { + parent = mergeOptions(parent, child.mixins[i], vm); + } + } + } + var options = {}; + var key; + for (key in parent) { + mergeField(key); + } + for (key in child) { + if (!hasOwn(parent, key)) { + mergeField(key); + } + } + function mergeField(key) { + var strat = strats[key] || defaultStrat; + options[key] = strat(parent[key], child[key], vm, key); + } + return options; } - /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ -function resolveAsset ( - options, - type, - id, - warnMissing -) { - /* istanbul ignore if */ - if (typeof id !== 'string') { - return - } - var assets = options[type]; - // check local registration variations first - if (hasOwn(assets, id)) { return assets[id] } - var camelizedId = camelize(id); - if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } - var PascalCaseId = capitalize(camelizedId); - if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } - // fallback to prototype chain - var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; - if (warnMissing && !res) { - warn( - 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, - options - ); - } - return res -} - -/* */ - - - -function validateProp ( - key, - propOptions, - propsData, - vm -) { - var prop = propOptions[key]; - var absent = !hasOwn(propsData, key); - var value = propsData[key]; - // boolean casting - var booleanIndex = getTypeIndex(Boolean, prop.type); - if (booleanIndex > -1) { - if (absent && !hasOwn(prop, 'default')) { - value = false; - } else if (value === '' || value === hyphenate(key)) { - // only cast empty string / same name to boolean if - // boolean has higher priority - var stringIndex = getTypeIndex(String, prop.type); - if (stringIndex < 0 || booleanIndex < stringIndex) { - value = true; - } - } - } - // check default value - if (value === undefined) { - value = getPropDefaultValue(vm, prop, key); - // since the default value is a fresh copy, - // make sure to observe it. - var prevShouldObserve = shouldObserve; - toggleObserving(true); - observe(value); - toggleObserving(prevShouldObserve); - } - { - assertProp(prop, key, value, vm, absent); - } - return value +function resolveAsset(options, type, id, warnMissing) { + /* istanbul ignore if */ + if (typeof id !== 'string') { + return; + } + var assets = options[type]; + // check local registration variations first + if (hasOwn(assets, id)) + { return assets[id]; } + var camelizedId = camelize(id); + if (hasOwn(assets, camelizedId)) + { return assets[camelizedId]; } + var PascalCaseId = capitalize(camelizedId); + if (hasOwn(assets, PascalCaseId)) + { return assets[PascalCaseId]; } + // fallback to prototype chain + var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; + if (warnMissing && !res) { + warn('Failed to resolve ' + type.slice(0, -1) + ': ' + id, options); + } + return res; +} + +/* @flow */ +function validateProp(key, propOptions, propsData, vm) { + var prop = propOptions[key]; + var absent = !hasOwn(propsData, key); + var value = propsData[key]; + // boolean casting + var booleanIndex = getTypeIndex(Boolean, prop.type); + if (booleanIndex > -1) { + if (absent && !hasOwn(prop, 'default')) { + value = false; + } + else if (value === '' || value === hyphenate(key)) { + // only cast empty string / same name to boolean if + // boolean has higher priority + var stringIndex = getTypeIndex(String, prop.type); + if (stringIndex < 0 || booleanIndex < stringIndex) { + value = true; + } + } + } + // check default value + if (value === undefined) { + value = getPropDefaultValue(vm, prop, key); + // since the default value is a fresh copy, + // make sure to observe it. + var prevShouldObserve = shouldObserve; + toggleObserving(true); + observe(value); + toggleObserving(prevShouldObserve); + } + { + assertProp(prop, key, value, vm, absent); + } + return value; } - /** * Get the default value of a prop. */ -function getPropDefaultValue (vm, prop, key) { - // no default, return undefined - if (!hasOwn(prop, 'default')) { - return undefined - } - var def = prop.default; - // warn against non-factory defaults for Object & Array - if (isObject(def)) { - warn( - 'Invalid default value for prop "' + key + '": ' + - 'Props with type Object/Array must use a factory function ' + - 'to return the default value.', - vm - ); - } - // the raw prop value was also undefined from previous render, - // return previous default value to avoid unnecessary watcher trigger - if (vm && vm.$options.propsData && - vm.$options.propsData[key] === undefined && - vm._props[key] !== undefined - ) { - return vm._props[key] - } - // call factory function for non-Function types - // a value is Function if its prototype is function even across different execution context - return typeof def === 'function' && getType(prop.type) !== 'Function' - ? def.call(vm) - : def +function getPropDefaultValue(vm, prop, key) { + // no default, return undefined + if (!hasOwn(prop, 'default')) { + return undefined; + } + var def = prop.default; + // warn against non-factory defaults for Object & Array + if (isObject(def)) { + warn('Invalid default value for prop "' + + key + + '": ' + + 'Props with type Object/Array must use a factory function ' + + 'to return the default value.', vm); + } + // the raw prop value was also undefined from previous render, + // return previous default value to avoid unnecessary watcher trigger + if (vm && + vm.$options.propsData && + vm.$options.propsData[key] === undefined && + vm._props[key] !== undefined) { + return vm._props[key]; + } + // call factory function for non-Function types + // a value is Function if its prototype is function even across different execution context + return typeof def === 'function' && getType(prop.type) !== 'Function' + ? def.call(vm) + : def; } - /** * Assert whether a prop is valid. */ -function assertProp ( - prop, - name, - value, - vm, - absent -) { - if (prop.required && absent) { - warn( - 'Missing required prop: "' + name + '"', - vm - ); - return - } - if (value == null && !prop.required) { - return - } - var type = prop.type; - var valid = !type || type === true; - var expectedTypes = []; - if (type) { - if (!Array.isArray(type)) { - type = [type]; - } - for (var i = 0; i < type.length && !valid; i++) { - var assertedType = assertType(value, type[i]); - expectedTypes.push(assertedType.expectedType || ''); - valid = assertedType.valid; - } - } - - if (!valid) { - warn( - getInvalidTypeMessage(name, value, expectedTypes), - vm - ); - return - } - var validator = prop.validator; - if (validator) { - if (!validator(value)) { - warn( - 'Invalid prop: custom validator check failed for prop "' + name + '".', - vm - ); - } - } -} - -var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; - -function assertType (value, type) { - var valid; - var expectedType = getType(type); - if (simpleCheckRE.test(expectedType)) { - var t = typeof value; - valid = t === expectedType.toLowerCase(); - // for primitive wrapper objects - if (!valid && t === 'object') { - valid = value instanceof type; - } - } else if (expectedType === 'Object') { - valid = isPlainObject(value); - } else if (expectedType === 'Array') { - valid = Array.isArray(value); - } else { - valid = value instanceof type; - } - return { - valid: valid, - expectedType: expectedType - } +function assertProp(prop, name, value, vm, absent) { + if (prop.required && absent) { + warn('Missing required prop: "' + name + '"', vm); + return; + } + if (value == null && !prop.required) { + return; + } + var type = prop.type; + // @ts-ignore + var valid = !type || type === true; + var expectedTypes = []; + if (type) { + if (!Array.isArray(type)) { + type = [type]; + } + for (var i = 0; i < type.length && !valid; i++) { + var assertedType = assertType(value, type[i], vm); + expectedTypes.push(assertedType.expectedType || ''); + valid = assertedType.valid; + } + } + var haveExpectedTypes = expectedTypes.some(function (t) { return t; }); + if (!valid && haveExpectedTypes) { + warn(getInvalidTypeMessage(name, value, expectedTypes), vm); + return; + } + var validator = prop.validator; + if (validator) { + if (!validator(value)) { + warn('Invalid prop: custom validator check failed for prop "' + name + '".', vm); + } + } } - +var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol|BigInt)$/; +function assertType(value, type, vm) { + var valid; + var expectedType = getType(type); + if (simpleCheckRE.test(expectedType)) { + var t = typeof value; + valid = t === expectedType.toLowerCase(); + // for primitive wrapper objects + if (!valid && t === 'object') { + valid = value instanceof type; + } + } + else if (expectedType === 'Object') { + valid = isPlainObject(value); + } + else if (expectedType === 'Array') { + valid = Array.isArray(value); + } + else { + try { + valid = value instanceof type; + } + catch (e) { + warn('Invalid prop type: "' + String(type) + '" is not a constructor', vm); + valid = false; + } + } + return { + valid: valid, + expectedType: expectedType, + }; +} +var functionTypeCheckRE = /^\s*function (\w+)/; /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ -function getType (fn) { - var match = fn && fn.toString().match(/^\s*function (\w+)/); - return match ? match[1] : '' -} - -function isSameType (a, b) { - return getType(a) === getType(b) -} - -function getTypeIndex (type, expectedTypes) { - if (!Array.isArray(expectedTypes)) { - return isSameType(expectedTypes, type) ? 0 : -1 - } - for (var i = 0, len = expectedTypes.length; i < len; i++) { - if (isSameType(expectedTypes[i], type)) { - return i - } - } - return -1 -} - -function getInvalidTypeMessage (name, value, expectedTypes) { - var message = "Invalid prop: type check failed for prop \"" + name + "\"." + - " Expected " + (expectedTypes.map(capitalize).join(', ')); - var expectedType = expectedTypes[0]; - var receivedType = toRawType(value); - var expectedValue = styleValue(value, expectedType); - var receivedValue = styleValue(value, receivedType); - // check if we need to specify expected value - if (expectedTypes.length === 1 && - isExplicable(expectedType) && - !isBoolean(expectedType, receivedType)) { - message += " with value " + expectedValue; - } - message += ", got " + receivedType + " "; - // check if we need to specify received value - if (isExplicable(receivedType)) { - message += "with value " + receivedValue + "."; - } - return message -} - -function styleValue (value, type) { - if (type === 'String') { - return ("\"" + value + "\"") - } else if (type === 'Number') { - return ("" + (Number(value))) - } else { - return ("" + value) - } -} - -function isExplicable (value) { - var explicitTypes = ['string', 'number', 'boolean']; - return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) -} - -function isBoolean () { - var args = [], len = arguments.length; - while ( len-- ) args[ len ] = arguments[ len ]; - - return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) -} - -/* */ - -function handleError (err, vm, info) { - // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. - // See: https://github.com/vuejs/vuex/issues/1505 - pushTarget(); - try { - if (vm) { - var cur = vm; - while ((cur = cur.$parent)) { - var hooks = cur.$options.errorCaptured; - if (hooks) { - for (var i = 0; i < hooks.length; i++) { - try { - var capture = hooks[i].call(cur, err, vm, info) === false; - if (capture) { return } - } catch (e) { - globalHandleError(e, cur, 'errorCaptured hook'); - } - } +function getType(fn) { + var match = fn && fn.toString().match(functionTypeCheckRE); + return match ? match[1] : ''; +} +function isSameType(a, b) { + return getType(a) === getType(b); +} +function getTypeIndex(type, expectedTypes) { + if (!Array.isArray(expectedTypes)) { + return isSameType(expectedTypes, type) ? 0 : -1; + } + for (var i = 0, len = expectedTypes.length; i < len; i++) { + if (isSameType(expectedTypes[i], type)) { + return i; } - } } - globalHandleError(err, vm, info); - } finally { - popTarget(); - } -} - -function invokeWithErrorHandling ( - handler, - context, - args, - vm, - info -) { - var res; - try { - res = args ? handler.apply(context, args) : handler.call(context); - if (res && !res._isVue && isPromise(res) && !res._handled) { - res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); - // issue #9511 - // avoid catch triggering multiple times when nested calls - res._handled = true; - } - } catch (e) { - handleError(e, vm, info); - } - return res -} - -function globalHandleError (err, vm, info) { - if (config.errorHandler) { - try { - return config.errorHandler.call(null, err, vm, info) - } catch (e) { - // if the user intentionally throws the original error in the handler, - // do not log it twice - if (e !== err) { - logError(e, null, 'config.errorHandler'); - } + return -1; +} +function getInvalidTypeMessage(name, value, expectedTypes) { + var message = "Invalid prop: type check failed for prop \"" + name + "\"." + + " Expected " + (expectedTypes.map(capitalize).join(', ')); + var expectedType = expectedTypes[0]; + var receivedType = toRawType(value); + // check if we need to specify expected value + if (expectedTypes.length === 1 && + isExplicable(expectedType) && + isExplicable(typeof value) && + !isBoolean(expectedType, receivedType)) { + message += " with value " + (styleValue(value, expectedType)); + } + message += ", got " + receivedType + " "; + // check if we need to specify received value + if (isExplicable(receivedType)) { + message += "with value " + (styleValue(value, receivedType)) + "."; + } + return message; +} +function styleValue(value, type) { + if (type === 'String') { + return ("\"" + value + "\""); + } + else if (type === 'Number') { + return ("" + (Number(value))); + } + else { + return ("" + value); } - } - logError(err, vm, info); } +var EXPLICABLE_TYPES = ['string', 'number', 'boolean']; +function isExplicable(value) { + return EXPLICABLE_TYPES.some(function (elem) { return value.toLowerCase() === elem; }); +} +function isBoolean() { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; -function logError (err, vm, info) { - { - warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); - } - /* istanbul ignore else */ - if ((inBrowser || inWeex) && typeof console !== 'undefined') { - console.error(err); - } else { - throw err - } + return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }); } -/* */ +function handleError(err, vm, info) { + // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. + // See: https://github.com/vuejs/vuex/issues/1505 + pushTarget(); + try { + if (vm) { + var cur = vm; + while ((cur = cur.$parent)) { + var hooks = cur.$options.errorCaptured; + if (hooks) { + for (var i = 0; i < hooks.length; i++) { + try { + var capture = hooks[i].call(cur, err, vm, info) === false; + if (capture) + { return; } + } + catch (e) { + globalHandleError(e, cur, 'errorCaptured hook'); + } + } + } + } + } + globalHandleError(err, vm, info); + } + finally { + popTarget(); + } +} +function invokeWithErrorHandling(handler, context, args, vm, info) { + var res; + try { + res = args ? handler.apply(context, args) : handler.call(context); + if (res && !res._isVue && isPromise(res) && !res._handled) { + res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); + // issue #9511 + // avoid catch triggering multiple times when nested calls + res._handled = true; + } + } + catch (e) { + handleError(e, vm, info); + } + return res; +} +function globalHandleError(err, vm, info) { + if (config.errorHandler) { + try { + return config.errorHandler.call(null, err, vm, info); + } + catch (e) { + // if the user intentionally throws the original error in the handler, + // do not log it twice + if (e !== err) { + logError(e, null, 'config.errorHandler'); + } + } + } + logError(err, vm, info); +} +function logError(err, vm, info) { + { + warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); + } + /* istanbul ignore else */ + if ((inBrowser || inWeex) && typeof console !== 'undefined') { + console.error(err); + } + else { + throw err; + } +} +/* @flow */ var isUsingMicroTask = false; - var callbacks = []; var pending = false; - -function flushCallbacks () { - pending = false; - var copies = callbacks.slice(0); - callbacks.length = 0; - for (var i = 0; i < copies.length; i++) { - copies[i](); - } +function flushCallbacks() { + pending = false; + var copies = callbacks.slice(0); + callbacks.length = 0; + for (var i = 0; i < copies.length; i++) { + copies[i](); + } } - // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint @@ -1924,7 +1695,6 @@ function flushCallbacks () { // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; - // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in @@ -1933,3799 +1703,3315 @@ var timerFunc; // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { - var p = Promise.resolve(); - timerFunc = function () { - p.then(flushCallbacks); - // In problematic UIWebViews, Promise.then doesn't completely break, but - // it can get stuck in a weird state where callbacks are pushed into the - // microtask queue but the queue isn't being flushed, until the browser - // needs to do some other work, e.g. handle a timer. Therefore we can - // "force" the microtask queue to be flushed by adding an empty timer. - if (isIOS) { setTimeout(noop); } - }; - isUsingMicroTask = true; -} else if (!isIE && typeof MutationObserver !== 'undefined' && ( - isNative(MutationObserver) || - // PhantomJS and iOS 7.x - MutationObserver.toString() === '[object MutationObserverConstructor]' -)) { - // Use MutationObserver where native Promise is not available, - // e.g. PhantomJS, iOS7, Android 4.4 - // (#6466 MutationObserver is unreliable in IE11) - var counter = 1; - var observer = new MutationObserver(flushCallbacks); - var textNode = document.createTextNode(String(counter)); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function () { - counter = (counter + 1) % 2; - textNode.data = String(counter); - }; - isUsingMicroTask = true; -} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { - // Fallback to setImmediate. - // Technically it leverages the (macro) task queue, - // but it is still a better choice than setTimeout. - timerFunc = function () { - setImmediate(flushCallbacks); - }; -} else { - // Fallback to setTimeout. - timerFunc = function () { - setTimeout(flushCallbacks, 0); - }; -} - -function nextTick (cb, ctx) { - var _resolve; - callbacks.push(function () { - if (cb) { - try { - cb.call(ctx); - } catch (e) { - handleError(e, ctx, 'nextTick'); - } - } else if (_resolve) { - _resolve(ctx); - } - }); - if (!pending) { - pending = true; - timerFunc(); - } - // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve) { - _resolve = resolve; - }) - } -} - -/* */ + var p = Promise.resolve(); + timerFunc = function () { + p.then(flushCallbacks); + // In problematic UIWebViews, Promise.then doesn't completely break, but + // it can get stuck in a weird state where callbacks are pushed into the + // microtask queue but the queue isn't being flushed, until the browser + // needs to do some other work, e.g. handle a timer. Therefore we can + // "force" the microtask queue to be flushed by adding an empty timer. + if (isIOS) + { setTimeout(noop); } + }; + isUsingMicroTask = true; +} +else if (!isIE && + typeof MutationObserver !== 'undefined' && + (isNative(MutationObserver) || + // PhantomJS and iOS 7.x + MutationObserver.toString() === '[object MutationObserverConstructor]')) { + // Use MutationObserver where native Promise is not available, + // e.g. PhantomJS, iOS7, Android 4.4 + // (#6466 MutationObserver is unreliable in IE11) + var counter = 1; + var observer = new MutationObserver(flushCallbacks); + var textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true, + }); + timerFunc = function () { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + isUsingMicroTask = true; +} +else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { + // Fallback to setImmediate. + // Technically it leverages the (macro) task queue, + // but it is still a better choice than setTimeout. + timerFunc = function () { + setImmediate(flushCallbacks); + }; +} +else { + // Fallback to setTimeout. + timerFunc = function () { + setTimeout(flushCallbacks, 0); + }; +} +function nextTick(cb, ctx) { + var _resolve; + callbacks.push(function () { + if (cb) { + try { + cb.call(ctx); + } + catch (e) { + handleError(e, ctx, 'nextTick'); + } + } + else if (_resolve) { + _resolve(ctx); + } + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve) { + _resolve = resolve; + }); + } +} + +/* @flow */ var mark; var measure; - { - var perf = inBrowser && window.performance; - /* istanbul ignore if */ - if ( - perf && - perf.mark && - perf.measure && - perf.clearMarks && - perf.clearMeasures - ) { - mark = function (tag) { return perf.mark(tag); }; - measure = function (name, startTag, endTag) { - perf.measure(name, startTag, endTag); - perf.clearMarks(startTag); - perf.clearMarks(endTag); - // perf.clearMeasures(name) - }; - } + var perf = inBrowser && window.performance; + /* istanbul ignore if */ + if (perf && + perf.mark && + perf.measure && + perf.clearMarks && + perf.clearMeasures) { + mark = function (tag) { return perf.mark(tag); }; + measure = function (name, startTag, endTag) { + perf.measure(name, startTag, endTag); + perf.clearMarks(startTag); + perf.clearMarks(endTag); + // perf.clearMeasures(name) + }; + } } /* not type checking this file because flow doesn't play well with Proxy */ - var initProxy; - { - var allowedGlobals = makeMap( - 'Infinity,undefined,NaN,isFinite,isNaN,' + - 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + - 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + - 'require' // for Webpack/Browserify - ); - - var warnNonPresent = function (target, key) { - warn( - "Property or method \"" + key + "\" is not defined on the instance but " + - 'referenced during render. Make sure that this property is reactive, ' + - 'either in the data option, or for class-based components, by ' + - 'initializing the property. ' + - 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', - target + var allowedGlobals = makeMap('Infinity,undefined,NaN,isFinite,isNaN,' + + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' + + 'require' // for Webpack/Browserify ); - }; - - var warnReservedPrefix = function (target, key) { - warn( - "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + - 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + - 'prevent conflicts with Vue internals. ' + - 'See: https://vuejs.org/v2/api/#data', - target - ); - }; - - var hasProxy = - typeof Proxy !== 'undefined' && isNative(Proxy); - - if (hasProxy) { - var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); - config.keyCodes = new Proxy(config.keyCodes, { - set: function set (target, key, value) { - if (isBuiltInModifier(key)) { - warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); - return false - } else { - target[key] = value; - return true - } - } - }); - } - - var hasHandler = { - has: function has (target, key) { - var has = key in target; - var isAllowed = allowedGlobals(key) || - (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); - if (!has && !isAllowed) { - if (key in target.$data) { warnReservedPrefix(target, key); } - else { warnNonPresent(target, key); } - } - return has || !isAllowed - } - }; - - var getHandler = { - get: function get (target, key) { - if (typeof key === 'string' && !(key in target)) { - if (key in target.$data) { warnReservedPrefix(target, key); } - else { warnNonPresent(target, key); } - } - return target[key] - } - }; - - initProxy = function initProxy (vm) { + var warnNonPresent = function (target, key) { + warn("Property or method \"" + key + "\" is not defined on the instance but " + + 'referenced during render. Make sure that this property is reactive, ' + + 'either in the data option, or for class-based components, by ' + + 'initializing the property. ' + + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target); + }; + var warnReservedPrefix = function (target, key) { + warn("Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + + 'prevent conflicts with Vue internals. ' + + 'See: https://vuejs.org/v2/api/#data', target); + }; + var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { - // determine which proxy handler to use - var options = vm.$options; - var handlers = options.render && options.render._withStripped - ? getHandler - : hasHandler; - vm._renderProxy = new Proxy(vm, handlers); - } else { - vm._renderProxy = vm; + var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); + config.keyCodes = new Proxy(config.keyCodes, { + set: function set(target, key, value) { + if (isBuiltInModifier(key)) { + warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); + return false; + } + else { + target[key] = value; + return true; + } + }, + }); } - }; + var hasHandler = { + has: function has(target, key) { + var has = key in target; + var isAllowed = allowedGlobals(key) || + (typeof key === 'string' && + key.charAt(0) === '_' && + !(key in target.$data)); + if (!has && !isAllowed) { + if (key in target.$data) + { warnReservedPrefix(target, key); } + else + { warnNonPresent(target, key); } + } + return has || !isAllowed; + }, + }; + var getHandler = { + get: function get(target, key) { + if (typeof key === 'string' && !(key in target)) { + if (key in target.$data) + { warnReservedPrefix(target, key); } + else + { warnNonPresent(target, key); } + } + return target[key]; + }, + }; + initProxy = function initProxy(vm) { + if (hasProxy) { + // determine which proxy handler to use + var options = vm.$options; + var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; + vm._renderProxy = new Proxy(vm, handlers); + } + else { + vm._renderProxy = vm; + } + }; } -/* */ - +/* @flow */ var seenObjects = new _Set(); - /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ -function traverse (val) { - _traverse(val, seenObjects); - seenObjects.clear(); -} - -function _traverse (val, seen) { - var i, keys; - var isA = Array.isArray(val); - if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { - return - } - if (val.__ob__) { - var depId = val.__ob__.dep.id; - if (seen.has(depId)) { - return - } - seen.add(depId); - } - if (isA) { - i = val.length; - while (i--) { _traverse(val[i], seen); } - } else { - keys = Object.keys(val); - i = keys.length; - while (i--) { _traverse(val[keys[i]], seen); } - } -} - -/* */ +function traverse(val) { + _traverse(val, seenObjects); + seenObjects.clear(); +} +function _traverse(val, seen) { + var i, keys; + var isA = Array.isArray(val); + if ((!isA && !isObject(val)) || + Object.isFrozen(val) || + val instanceof VNode) { + return; + } + if (val.__ob__) { + var depId = val.__ob__.dep.id; + if (seen.has(depId)) { + return; + } + seen.add(depId); + } + if (isA) { + i = val.length; + while (i--) + { _traverse(val[i], seen); } + } + else { + keys = Object.keys(val); + i = keys.length; + while (i--) + { _traverse(val[keys[i]], seen); } + } +} var normalizeEvent = cached(function (name) { - var passive = name.charAt(0) === '&'; - name = passive ? name.slice(1) : name; - var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first - name = once$$1 ? name.slice(1) : name; - var capture = name.charAt(0) === '!'; - name = capture ? name.slice(1) : name; - return { - name: name, - once: once$$1, - capture: capture, - passive: passive - } + var passive = name.charAt(0) === '&'; + name = passive ? name.slice(1) : name; + var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first + name = once$$1 ? name.slice(1) : name; + var capture = name.charAt(0) === '!'; + name = capture ? name.slice(1) : name; + return { + name: name, + once: once$$1, + capture: capture, + passive: passive, + }; }); +function createFnInvoker(fns, vm) { + function invoker() { + var arguments$1 = arguments; + + var fns = invoker.fns; + if (Array.isArray(fns)) { + var cloned = fns.slice(); + for (var i = 0; i < cloned.length; i++) { + invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); + } + } + else { + // return handler return value for single handlers + return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler"); + } + } + invoker.fns = fns; + return invoker; +} +function updateListeners(on, oldOn, add, remove$$1, createOnceHandler, vm) { + var name, def$$1, cur, old, event; + for (name in on) { + def$$1 = cur = on[name]; + old = oldOn[name]; + event = normalizeEvent(name); + if (isUndef(cur)) { + warn("Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm); + } + else if (isUndef(old)) { + if (isUndef(cur.fns)) { + cur = on[name] = createFnInvoker(cur, vm); + } + if (isTrue(event.once)) { + cur = on[name] = createOnceHandler(event.name, cur, event.capture); + } + add(event.name, cur, event.capture, event.passive, event.params); + } + else if (cur !== old) { + old.fns = cur; + on[name] = old; + } + } + for (name in oldOn) { + if (isUndef(on[name])) { + event = normalizeEvent(name); + remove$$1(event.name, oldOn[name], event.capture); + } + } +} -function createFnInvoker (fns, vm) { - function invoker () { - var arguments$1 = arguments; - - var fns = invoker.fns; - if (Array.isArray(fns)) { - var cloned = fns.slice(); - for (var i = 0; i < cloned.length; i++) { - invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); - } - } else { - // return handler return value for single handlers - return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") - } - } - invoker.fns = fns; - return invoker -} - -function updateListeners ( - on, - oldOn, - add, - remove$$1, - createOnceHandler, - vm -) { - var name, def$$1, cur, old, event; - for (name in on) { - def$$1 = cur = on[name]; - old = oldOn[name]; - event = normalizeEvent(name); - if (isUndef(cur)) { - warn( - "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), - vm - ); - } else if (isUndef(old)) { - if (isUndef(cur.fns)) { - cur = on[name] = createFnInvoker(cur, vm); - } - if (isTrue(event.once)) { - cur = on[name] = createOnceHandler(event.name, cur, event.capture); - } - add(event.name, cur, event.capture, event.passive, event.params); - } else if (cur !== old) { - old.fns = cur; - on[name] = old; - } - } - for (name in oldOn) { - if (isUndef(on[name])) { - event = normalizeEvent(name); - remove$$1(event.name, oldOn[name], event.capture); - } - } -} - -/* */ - -function mergeVNodeHook (def, hookKey, hook) { - if (def instanceof VNode) { - def = def.data.hook || (def.data.hook = {}); - } - var invoker; - var oldHook = def[hookKey]; - - function wrappedHook () { - hook.apply(this, arguments); - // important: remove merged hook to ensure it's called only once - // and prevent memory leak - remove(invoker.fns, wrappedHook); - } - - if (isUndef(oldHook)) { - // no existing hook - invoker = createFnInvoker([wrappedHook]); - } else { - /* istanbul ignore if */ - if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { - // already a merged invoker - invoker = oldHook; - invoker.fns.push(wrappedHook); - } else { - // existing plain hook - invoker = createFnInvoker([oldHook, wrappedHook]); - } - } - - invoker.merged = true; - def[hookKey] = invoker; -} - -/* */ - -function extractPropsFromVNodeData ( - data, - Ctor, - tag -) { - // we are only extracting raw values here. - // validation and default values are handled in the child - // component itself. - var propOptions = Ctor.options.props; - if (isUndef(propOptions)) { - return - } - var res = {}; - var attrs = data.attrs; - var props = data.props; - if (isDef(attrs) || isDef(props)) { - for (var key in propOptions) { - var altKey = hyphenate(key); - { - var keyInLowerCase = key.toLowerCase(); - if ( - key !== keyInLowerCase && - attrs && hasOwn(attrs, keyInLowerCase) - ) { - tip( - "Prop \"" + keyInLowerCase + "\" is passed to component " + - (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + - " \"" + key + "\". " + - "Note that HTML attributes are case-insensitive and camelCased " + - "props need to use their kebab-case equivalents when using in-DOM " + - "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." - ); - } - } - checkProp(res, props, key, altKey, true) || - checkProp(res, attrs, key, altKey, false); - } - } - return res -} - -function checkProp ( - res, - hash, - key, - altKey, - preserve -) { - if (isDef(hash)) { - if (hasOwn(hash, key)) { - res[key] = hash[key]; - if (!preserve) { - delete hash[key]; - } - return true - } else if (hasOwn(hash, altKey)) { - res[key] = hash[altKey]; - if (!preserve) { - delete hash[altKey]; - } - return true - } - } - return false -} - -/* */ +/* @flow */ +function mergeVNodeHook(def, hookKey, hook) { + if (def instanceof VNode) { + def = def.data.hook || (def.data.hook = {}); + } + var invoker; + var oldHook = def[hookKey]; + function wrappedHook() { + hook.apply(this, arguments); + // important: remove merged hook to ensure it's called only once + // and prevent memory leak + remove(invoker.fns, wrappedHook); + } + if (isUndef(oldHook)) { + // no existing hook + invoker = createFnInvoker([wrappedHook]); + } + else { + /* istanbul ignore if */ + if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { + // already a merged invoker + invoker = oldHook; + invoker.fns.push(wrappedHook); + } + else { + // existing plain hook + invoker = createFnInvoker([oldHook, wrappedHook]); + } + } + invoker.merged = true; + def[hookKey] = invoker; +} + +/* @flow */ +function extractPropsFromVNodeData(data, Ctor, tag) { + // we are only extracting raw values here. + // validation and default values are handled in the child + // component itself. + var propOptions = Ctor.options.props; + if (isUndef(propOptions)) { + return; + } + var res = {}; + var attrs = data.attrs; + var props = data.props; + if (isDef(attrs) || isDef(props)) { + for (var key in propOptions) { + var altKey = hyphenate(key); + { + var keyInLowerCase = key.toLowerCase(); + if (key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase)) { + tip("Prop \"" + keyInLowerCase + "\" is passed to component " + + (formatComponentName( + // @ts-ignore + tag || Ctor)) + ", but the declared prop name is" + + " \"" + key + "\". " + + "Note that HTML attributes are case-insensitive and camelCased " + + "props need to use their kebab-case equivalents when using in-DOM " + + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."); + } + } + checkProp(res, props, key, altKey, true) || + checkProp(res, attrs, key, altKey, false); + } + } + return res; +} +function checkProp(res, hash, key, altKey, preserve) { + if (isDef(hash)) { + if (hasOwn(hash, key)) { + res[key] = hash[key]; + if (!preserve) { + delete hash[key]; + } + return true; + } + else if (hasOwn(hash, altKey)) { + res[key] = hash[altKey]; + if (!preserve) { + delete hash[altKey]; + } + return true; + } + } + return false; +} +/* @flow */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array. There are // two cases where extra normalization is needed: - // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. -function simpleNormalizeChildren (children) { - for (var i = 0; i < children.length; i++) { - if (Array.isArray(children[i])) { - return Array.prototype.concat.apply([], children) +function simpleNormalizeChildren(children) { + for (var i = 0; i < children.length; i++) { + if (Array.isArray(children[i])) { + return Array.prototype.concat.apply([], children); + } } - } - return children + return children; } - // 2. When the children contains constructs that always generated nested Arrays, // e.g.