UNPKG

@stripe/ui-extension-sdk

Version:

The suite of functionality available to UI extensions in Stripe apps

215 lines (212 loc) 10.3 kB
"use strict"; /* Copyright 2020-present, Shopify Inc. Copyright 2022-present, Stripe Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createTestRoot = createTestRoot; exports.mount = mount; const core_1 = require("@remote-ui/core"); const testing_1 = require("@remote-ui/testing"); const print_1 = require("./print"); const IS_NODE = Symbol.for('RemoteUiTesting.Node'); function createTestRoot() { // eslint-disable-next-line @typescript-eslint/no-empty-function return (0, core_1.createRemoteRoot)(() => { }); } function mount( // eslint-disable-next-line no-shadow run, root = createTestRoot()) { let acting = false; let mounted = true; let rootNode; // eslint-disable-next-line @typescript-eslint/no-use-before-define act(() => { run(root); }); const rootApi = new Proxy({ // eslint-disable-next-line @typescript-eslint/no-use-before-define act, // eslint-disable-next-line @typescript-eslint/no-use-before-define unmount, }, { get(target, key, receiver) { if (Reflect.ownKeys(target).includes(key)) { return Reflect.get(target, key, receiver); } // eslint-disable-next-line @typescript-eslint/no-use-before-define, no-shadow return withRootNode((rootNode) => Reflect.get(rootNode, key)); }, }); return rootApi; function createNode({ type, props, instance, children, }) { // eslint-disable-next-line @typescript-eslint/no-use-before-define const descendants = children.flatMap(getDescendants); function getDescendants(child) { return [ child, ...(typeof child === 'string' ? [] : child.children.flatMap(getDescendants)), ]; } // eslint-disable-next-line no-shadow const getTypeString = (type) => { var _a, _b; // Returns the wrappedComponentName for components wrapped with the withSdkProps HOC. if (typeof type === 'function' && type.name === 'WithSdkProps') { return type.wrappedComponentName; } // Components that have fragment props are put into a ComponentWrapper which makes their // `type` an object rather than a string. This function grabs the `displayName` string from // that object so that `find` works. if (typeof type === 'object' && ((_a = type === null || type === void 0 ? void 0 : type.type) === null || _a === void 0 ? void 0 : _a.name) === 'ComponentWrapper' && ((_b = type === null || type === void 0 ? void 0 : type.type) === null || _b === void 0 ? void 0 : _b.displayName)) { return type.type.displayName; } return type; }; // eslint-disable-next-line no-shadow const find = (type, props) => { var _a; return (_a = descendants.find((element) => (0, testing_1.isNode)(element) && element.type === getTypeString(type) && (props == null || // eslint-disable-next-line @typescript-eslint/no-use-before-define equalSubset(props, element.props)))) !== null && _a !== void 0 ? _a : null; }; const node = { [IS_NODE]: true, type, props, instance, get text() { return children.reduce((text, child) => `${text}${typeof child === 'string' ? child : child.text}`, ''); }, prop: (key) => props[key], // @ts-expect-error - TS2322 Signature '<Type extends RemoteComponentType<string, any, any>>(checkType: Type): boolean' must be a type predicate. // eslint-disable-next-line @stripe-internal/stripe/no-props-suppress-errors is: (checkType) => type === getTypeString(checkType), find, // eslint-disable-next-line no-shadow findAll: (type, props) => descendants.filter((element) => (0, testing_1.isNode)(element) && element.type === getTypeString(type) && (props == null || // eslint-disable-next-line @typescript-eslint/no-use-before-define equalSubset(props, element.props))), findWhere: (predicate) => { var _a; return (_a = descendants.find((element) => (0, testing_1.isNode)(element) && predicate(element))) !== null && _a !== void 0 ? _a : null; }, findAllWhere: (predicate) => descendants.filter((element) => (0, testing_1.isNode)(element) && predicate(element)), trigger: (prop, ...args) => // eslint-disable-next-line @typescript-eslint/no-use-before-define act(() => { const propValue = props[prop]; if (propValue == null) { throw new Error(`Attempted to call prop ${String(prop)} but it was not defined.`); } return propValue(...args); }, { eager: true }), triggerKeypath: (keypath, ...args) => // eslint-disable-next-line @typescript-eslint/no-use-before-define act(() => { const parts = keypath.split(/[.[\]]/g).filter(Boolean); let currentProp = props; const currentKeypath = []; // eslint-disable-next-line no-restricted-syntax for (const part of parts) { if (currentProp == null || typeof currentProp !== 'object') { throw new Error(`Attempted to access field keypath '${currentKeypath.join('.')}', but it was not an object.`); } currentProp = currentProp[part]; currentKeypath.push(part); } if (typeof currentProp !== 'function') { throw new Error(`Value at keypath '${keypath}' is not a function.`); } return currentProp(...args); }, { eager: true }), children, descendants, debug: (options) => (0, print_1.nodeChildToString)(node, options), toString: () => `<${(0, print_1.nodeName)(node)} />`, }; return node; } function unmount() { if (!mounted) { throw new Error('You attempted to unmount a node that was already unmounted'); } mounted = false; } // Currently, we run the actions directly, so act isn’t actually flushing // updates or anything like that. In the future, we could use the fact that // we force all actions to be nested in here to make other guarantees about // how the updates have been flushed to the passed `root` (right now, we // treat that root as a "noop"). function act(action, { update = true, eager = false } = {}) { // eslint-disable-next-line @typescript-eslint/no-use-before-define const performUpdate = update ? updateRootNode : noop; if (acting) { return action(); } acting = true; const afterResolve = () => { performUpdate(); acting = false; // eslint-disable-next-line @typescript-eslint/no-use-before-define return result; }; const result = action(); // eslint-disable-next-line @typescript-eslint/no-use-before-define if (isPromise(result)) { if (eager) { performUpdate(); // eslint-disable-next-line @typescript-eslint/no-empty-function return act(() => Promise.resolve(result).then(() => { })).then(afterResolve); } else { return Promise.resolve(result).then(afterResolve); } } return afterResolve(); } function createNodeFromRemoteChild(child) { return (0, core_1.isRemoteText)(child) ? child.text : createNode({ type: child.type, props: Object.assign({}, child.props), instance: child, children: child.children.map(createNodeFromRemoteChild), }); } function updateRootNode() { rootNode = createNode({ type: null, props: {}, children: root.children.map((child) => createNodeFromRemoteChild(child)), instance: root, }); } function withRootNode(perform) { if (!mounted) { throw new Error('Attempted to operate on a mounted tree, but it is not mounted. Did you forget to call .mount()? If not, have you already called .unmount()?'); } return perform(rootNode); } } function isPromise(promise) { return typeof (promise === null || promise === void 0 ? void 0 : promise.then) === 'function'; } function equalSubset(subset, full) { return Object.keys(subset).every((key) => key in full && full[key] === subset[key]); } // eslint-disable-next-line @typescript-eslint/no-empty-function function noop() { } //# sourceMappingURL=mount.js.map