From e2f9a806f841052588a67fd49b8e14cb09c31b78 Mon Sep 17 00:00:00 2001 From: Yacine Hmito <6893840+yacinehmito@users.noreply.github.com> Date: Fri, 21 Jun 2024 09:07:10 +0200 Subject: [PATCH] chore: Unignored tests fixed by #1264 --- ...acfc18989ae017216e4a994568787bdbd4cf266.ts | 227 ++++++ ...c08d57a4d300058c3c352fa4708e3c5adde3314.ts | 26 + ...329ccdbc1fb2c464c594c393d9af73aacfa70e7.ts | 173 ++++ ...2c7482bc02d703d0f4d3e4d28188d2f0e0deb40.ts | 106 +++ ...3ecbbdf07269ff9702167ca4318bcba6ac86026.ts | 121 +++ ...0263905cbabe47c396d361b5a5521d22dc387e3.ts | 60 ++ ...2a34b30a2f256e824d3e27cececccee8d1a4633.ts | 169 ++++ ...2dae7c239360846844d5e0f7829bf09eb7268d6.ts | 156 ++++ ...90c637324e5380b84e1d1c49511616be2e24f07.ts | 303 +++++++ ...afc345e783f9aec6732115ea1b911a7e6a904ae.ts | 107 +++ ...bd5df2debc51a446431df617d15587c9e2cd31f.ts | 218 +++++ ...30b71f59d2855c8c4c511faec68b548adf17233.ts | 64 ++ ...09944ba160d3dfa44bff012c86487577e7696b7.ts | 160 ++++ ...6237a3cb626635e98640eb6a45ec85a619ac35b.ts | 6 + ...926e3f982a035c5474ec05e82f5d808bd641fe8.ts | 117 +++ ...c76f03c5edf9c6600a0b3a2a7cbbb2f8a080de7.ts | 4 + ...138138b682d39794b0172e5be29f1343ba97e7d.ts | 95 +++ ...2b4c24b8c3274b0dec5338689a1a7635935ed0f.ts | 687 ++++++++++++++++ ...2f14796472d5741184a5202d6b99b054075b20d.ts | 137 ++++ ...6c930bf5ae99dd1abeba0cb78324a33564d6c8c.ts | 722 +++++++++++++++++ ...c2515b2dcd55e2b4e848ea766c7a314b34efcf3.ts | 87 ++ ...ee9cd5faaa0d5d7ccbe18e8bcd4b51e29f50478.ts | 69 ++ ...7eb9fb39d33a96067d7a52d4ee766934d85123f.ts | 232 ++++++ ...bab9ceea279895af4796a5aa3f3f1d4d7c161c0.ts | 133 +++ ...5b7bb4b30dd209ee2cde87d057efe566fd762e7.ts | 19 + ...9094cdae1a9139f84bfb7febaac3d9db8adde23.ts | 251 ++++++ ...fed52c6107144ebcd8a6dadcb175ab1ceec8675.ts | 78 ++ ...0bbe6eb2c50792684f187ea19c029edc81084f8.ts | 112 +++ ...b76e27ca7324b464ae5e2d840913b787c4431fe.ts | 145 ++++ ...1a3b6a7f1c20c36b5ab28dc9274729ce4b87815.ts | 19 + ...5be0026e5f127a68758f05cd2da89aff686dbe4.ts | 89 ++ ...a5f3c447c92c0b5ea5e4274691e6e8d21efc4e9.ts | 51 ++ ...ac3ab02f5261ef6c20c970b040790c7c4c71db9.ts | 390 +++++++++ ...e4158aa9c20a8a46ee0d83440bff47e8b6b9b61.ts | 218 +++++ ...47f5128949cef31d57df373ca28d39b4537ba1f.ts | 543 +++++++++++++ ...b44f2fda4625a6bc5d1f38f54a2c3a460982234.ts | 198 +++++ ...da9ab3a939045d8022ff9a0361109640d05579d.ts | 85 ++ ...fa7059c0a96fef309a902ecebe92dbfa8dca020.ts | 757 ++++++++++++++++++ ...8f1d17ce20eb1c3baec121508b120aab05a8ee9.ts | 242 ++++++ ...eeff4b61b8d756cab182585f34923fe63015859.ts | 123 +++ ...5e033443d6562214fafcf58cf5686b06dbe18cd.ts | 165 ++++ ...60b8f9bffc36c678481a1e1a166ed6a04105d37.ts | 129 +++ ...c78116fed8e72fa1ed3d969831ae9cfd1733ce6.ts | 204 +++++ ...730dbd8ba72e8a84422ed0fac15a64fa3fe06e3.ts | 94 +++ ...ea4c4785f1ce7babd902f2aa6132781e1fe3c6c.ts | 72 ++ ...eaf6dc3f9b0ce2cbfcf93d376cf373fcf943ccb.ts | 80 ++ crates/swc_bundler/tests/deno.rs | 150 ++-- .../tests/deno/deno-8530/input/entry.ts | 4 +- 48 files changed, 8294 insertions(+), 103 deletions(-) create mode 100644 crates/swc_bundler/tests/.cache/deno/5acfc18989ae017216e4a994568787bdbd4cf266.ts create mode 100644 crates/swc_bundler/tests/.cache/deno/ac08d57a4d300058c3c352fa4708e3c5adde3314.ts create mode 100644 crates/swc_bundler/tests/.cache/deno/f329ccdbc1fb2c464c594c393d9af73aacfa70e7.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/02c7482bc02d703d0f4d3e4d28188d2f0e0deb40.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/03ecbbdf07269ff9702167ca4318bcba6ac86026.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/10263905cbabe47c396d361b5a5521d22dc387e3.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/22a34b30a2f256e824d3e27cececccee8d1a4633.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/22dae7c239360846844d5e0f7829bf09eb7268d6.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/290c637324e5380b84e1d1c49511616be2e24f07.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/2afc345e783f9aec6732115ea1b911a7e6a904ae.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/2bd5df2debc51a446431df617d15587c9e2cd31f.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/330b71f59d2855c8c4c511faec68b548adf17233.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/409944ba160d3dfa44bff012c86487577e7696b7.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/46237a3cb626635e98640eb6a45ec85a619ac35b.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/4926e3f982a035c5474ec05e82f5d808bd641fe8.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/4c76f03c5edf9c6600a0b3a2a7cbbb2f8a080de7.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/5138138b682d39794b0172e5be29f1343ba97e7d.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/52b4c24b8c3274b0dec5338689a1a7635935ed0f.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/52f14796472d5741184a5202d6b99b054075b20d.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/56c930bf5ae99dd1abeba0cb78324a33564d6c8c.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/5c2515b2dcd55e2b4e848ea766c7a314b34efcf3.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/5ee9cd5faaa0d5d7ccbe18e8bcd4b51e29f50478.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/67eb9fb39d33a96067d7a52d4ee766934d85123f.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/6bab9ceea279895af4796a5aa3f3f1d4d7c161c0.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/75b7bb4b30dd209ee2cde87d057efe566fd762e7.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/79094cdae1a9139f84bfb7febaac3d9db8adde23.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/7fed52c6107144ebcd8a6dadcb175ab1ceec8675.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/80bbe6eb2c50792684f187ea19c029edc81084f8.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/8b76e27ca7324b464ae5e2d840913b787c4431fe.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/91a3b6a7f1c20c36b5ab28dc9274729ce4b87815.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/95be0026e5f127a68758f05cd2da89aff686dbe4.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/9a5f3c447c92c0b5ea5e4274691e6e8d21efc4e9.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/9ac3ab02f5261ef6c20c970b040790c7c4c71db9.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/9e4158aa9c20a8a46ee0d83440bff47e8b6b9b61.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/a47f5128949cef31d57df373ca28d39b4537ba1f.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/ab44f2fda4625a6bc5d1f38f54a2c3a460982234.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/ada9ab3a939045d8022ff9a0361109640d05579d.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/afa7059c0a96fef309a902ecebe92dbfa8dca020.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/b8f1d17ce20eb1c3baec121508b120aab05a8ee9.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/beeff4b61b8d756cab182585f34923fe63015859.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/c5e033443d6562214fafcf58cf5686b06dbe18cd.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/c60b8f9bffc36c678481a1e1a166ed6a04105d37.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/cc78116fed8e72fa1ed3d969831ae9cfd1733ce6.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/d730dbd8ba72e8a84422ed0fac15a64fa3fe06e3.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/dea4c4785f1ce7babd902f2aa6132781e1fe3c6c.ts create mode 100644 crates/swc_bundler/tests/.cache/untrusted/eeaf6dc3f9b0ce2cbfcf93d376cf373fcf943ccb.ts diff --git a/crates/swc_bundler/tests/.cache/deno/5acfc18989ae017216e4a994568787bdbd4cf266.ts b/crates/swc_bundler/tests/.cache/deno/5acfc18989ae017216e4a994568787bdbd4cf266.ts new file mode 100644 index 000000000000..d49f3b3cbe5c --- /dev/null +++ b/crates/swc_bundler/tests/.cache/deno/5acfc18989ae017216e4a994568787bdbd4cf266.ts @@ -0,0 +1,227 @@ +// Loaded from https://deno.land/x/aleph@v0.2.28/head.ts + + +import React, { Children, createElement, isValidElement, PropsWithChildren, ReactElement, ReactNode, useContext, useEffect } from 'https://esm.sh/react' +import { RendererContext } from './context.ts' +import util from './util.ts' + +export const serverStyles: Map = new Map() + +export default function Head(props: PropsWithChildren<{}>) { + const renderer = useContext(RendererContext) + + if (window.Deno) { + parse(props.children).forEach(({ type, props }, key) => renderer.cache.headElements.set(key, { type, props })) + } + + useEffect(() => { + const doc = (window as any).document + const nodes = parse(props.children) + const insertedEls: Array = [] + + if (nodes.size > 0) { + let charset = doc.querySelector('meta[charset]') + if (!charset) { + charset = doc.createElement('meta') + charset.setAttribute('charset', 'utf-8') + doc.head.prepend(charset) + } + + const anchor = doc.createElement('meta') + if (charset.nextElementSibling) { + doc.head.insertBefore(anchor, charset.nextElementSibling) + } else { + doc.head.appendChild(anchor) + } + + nodes.forEach(({ type, props }) => { + if (type === 'script') { + return + } + const el = doc.createElement(type) + Object.keys(props).forEach(key => { + const value = props[key] + if (key === 'children') { + if (util.isNEString(value)) { + el.innerText = value + } else if (util.isNEArray(value)) { + el.innerText = value.join('') + } + } else { + el.setAttribute(key, String(value || '')) + } + }) + doc.head.insertBefore(el, anchor) + insertedEls.push(el) + }) + doc.head.removeChild(anchor) + } + + return () => { + insertedEls.forEach(el => doc.head.removeChild(el)) + } + }, [props.children]) + + return null +} + +export function Scripts(props: PropsWithChildren<{}>) { + const renderer = useContext(RendererContext) + + if (window.Deno) { + parse(props.children).forEach(({ type, props }, key) => { + if (type === 'script') { + renderer.cache.scriptsElements.set(key, { type, props }) + } + }) + } + + // todo: insert page scripts in browser + + return null +} + +interface SEOProps { + title?: string + description?: string + keywords?: string | string[] + url?: string + image?: string + twitter?: { + card?: 'summary' | 'summary_large_image' | 'app' | 'player' + site?: string + creator?: string + } +} + +export function SEO(props: SEOProps) { + const { title, description, keywords, url, image, twitter } = props + return createElement( + Head, + undefined, + title && createElement('title', undefined, title), + description && createElement('meta', { name: 'description', content: description }), + keywords && createElement('meta', { name: 'keywords', content: util.isArray(keywords) ? keywords.join(',') : keywords }), + title && createElement('meta', { name: 'og:title', content: title }), + description && createElement('meta', { name: 'og:description', content: description }), + title && createElement('meta', { name: 'twitter:title', content: title }), + description && createElement('meta', { name: 'twitter:description', content: description }), + url && createElement('meta', { name: 'og:url', content: url }), + image && createElement('meta', { name: 'og:image', content: image }), + image && createElement('meta', { name: 'twitter:image', content: image }), + image && createElement('meta', { name: 'twitter:card', content: twitter?.card || 'summary_large_image' }), + twitter?.site && createElement('meta', { name: 'twitter:site', content: twitter.site }), + twitter?.creator && createElement('meta', { name: 'twitter:creator', content: twitter.creator }), + ) +} + +interface ViewportProps { + width?: number | 'device-width' + height?: number | 'device-height' + initialScale?: number + minimumScale?: number + maximumScale?: number + userScalable?: 'yes' | 'no' + targetDensitydpi?: number | 'device-dpi' | 'low-dpi' | 'medium-dpi' | 'high-dpi' +} + +export function Viewport(props: ViewportProps) { + const content = Object.entries(props) + .map(([key, value]) => { + key = key.replace(/[A-Z]/g, c => '-' + c.toLowerCase()) + return `${key}=${value}` + }) + .join(',') + return createElement( + Head, + undefined, + content && createElement('meta', { name: 'viewport', content }) + ) +} + +export function applyCSS(id: string, css: string, asLink: boolean = false) { + if (window.Deno) { + serverStyles.set(id, { css, asLink }) + } else { + const { document } = (window as any) + const styleEl = document.createElement(asLink ? 'link' : 'style') + const prevStyleEls = Array.from(document.head.children).filter((el: any) => el.getAttribute('data-module-id') === id) + if (asLink) { + styleEl.rel = 'stylesheet' + styleEl.href = css + } else { + styleEl.type = 'text/css' + styleEl.appendChild(document.createTextNode(css)) + } + styleEl.setAttribute('data-module-id', id) + document.head.appendChild(styleEl) + if (prevStyleEls.length > 0) { + if (asLink) { + styleEl.addEventListener('load', () => { + prevStyleEls.forEach(el => document.head.removeChild(el)) + }) + } else { + setTimeout(() => { + prevStyleEls.forEach(el => document.head.removeChild(el)) + }, 0) + } + } + } +} + +function parse(node: ReactNode, els: Map }> = new Map()) { + Children.forEach(node, child => { + if (!isValidElement(child)) { + return + } + + const { type, props } = child + switch (type) { + case React.Fragment: + parse(props.children, els) + break + case SEO: + case Viewport: + parse((type(props) as ReactElement).props.children, els) + break + case 'base': + case 'title': + case 'meta': + case 'link': + case 'style': + case 'script': + case 'no-script': + { + let key = type + if (type === 'meta') { + const propKeys = Object.keys(props).map(k => k.toLowerCase()) + if (propKeys.includes('charset')) { + return // ignore charset, always use utf-8 + } + if (propKeys.includes('name')) { + key += `[name=${JSON.stringify(props['name'])}]` + } else if (propKeys.includes('property')) { + key += `[property=${JSON.stringify(props['property'])}]` + } else if (propKeys.includes('http-equiv')) { + key += `[http-equiv=${JSON.stringify(props['http-equiv'])}]` + } else { + key += Object.keys(props).filter(k => !(/^content|children$/i.test(k))).map(k => `[${k.toLowerCase()}=${JSON.stringify(props[k])}]`).join('') + } + } else if (type !== 'title') { + key += '-' + (els.size + 1) + } + // remove the children prop of base/meta/link + if (['base', 'meta', 'link'].includes(type) && 'children' in props) { + const { children, ...rest } = props + els.set(key, { type, props: rest }) + } else { + els.set(key, { type, props }) + } + } + break + } + }) + + return els +} + diff --git a/crates/swc_bundler/tests/.cache/deno/ac08d57a4d300058c3c352fa4708e3c5adde3314.ts b/crates/swc_bundler/tests/.cache/deno/ac08d57a4d300058c3c352fa4708e3c5adde3314.ts new file mode 100644 index 000000000000..11fbb2b0ed35 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/deno/ac08d57a4d300058c3c352fa4708e3c5adde3314.ts @@ -0,0 +1,26 @@ +// Loaded from https://deno.land/x/aleph@v0.2.28/context.ts + + +import { createContext } from 'https://esm.sh/react' +import type { RouterURL } from './types.ts' + +export const RouterContext = createContext({ + locale: 'en', + pagePath: '/', + pathname: '/', + params: {}, + query: new URLSearchParams(), +}) +RouterContext.displayName = 'RouterContext' + +interface RendererCache { + headElements: Map }> + scriptsElements: Map }> +} + +export const RendererContext = createContext<{ cache: RendererCache }>({ + cache: { + headElements: new Map(), + scriptsElements: new Map() + } +}) diff --git a/crates/swc_bundler/tests/.cache/deno/f329ccdbc1fb2c464c594c393d9af73aacfa70e7.ts b/crates/swc_bundler/tests/.cache/deno/f329ccdbc1fb2c464c594c393d9af73aacfa70e7.ts new file mode 100644 index 000000000000..f7c6086ff295 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/deno/f329ccdbc1fb2c464c594c393d9af73aacfa70e7.ts @@ -0,0 +1,173 @@ +// Loaded from https://deno.land/x/aleph@v0.2.28/util.ts + + +const symbolFor = typeof Symbol === 'function' && Symbol.for +const REACT_FORWARD_REF_TYPE = symbolFor ? Symbol.for('react.forward_ref') : 0xead0 +const REACT_MEMO_TYPE = symbolFor ? Symbol.for('react.memo') : 0xead3 + +export const hashShort = 9 +export const reHttp = /^https?:\/\//i +export const reModuleExt = /\.(js|jsx|mjs|ts|tsx)$/i +export const reStyleModuleExt = /\.(css|less)$/i +export const reMDExt = /\.(md|markdown)$/i +export const reLocaleID = /^[a-z]{2}(-[a-zA-Z0-9]+)?$/ +export const reHashJs = new RegExp(`\\.[0-9a-fx]{${hashShort}}\\.js$`, 'i') + +export const KB = 1024 +export const MB = KB ** 2 +export const GB = KB ** 3 +export const TB = KB ** 4 +export const PB = KB ** 5 + +export default { + isNumber(a: any): a is number { + return typeof a === 'number' && !Number.isNaN(a) + }, + isUNumber(a: any): a is number { + return this.isNumber(a) && a >= 0 + }, + isInt(a: any): a is number { + return this.isNumber(a) && Number.isInteger(a) + }, + isUInt(a: any): a is number { + return this.isInt(a) && a >= 0 + }, + isString(a: any): a is string { + return typeof a === 'string' + }, + isNEString(a: any): a is string { + return typeof a === 'string' && a.length > 0 + }, + isArray(a: any): a is Array { + return Array.isArray(a) + }, + isNEArray(a: any): a is Array { + return Array.isArray(a) && a.length > 0 + }, + isPlainObject(a: any): a is Record { + return typeof a === 'object' && a !== null && !this.isArray(a) && Object.getPrototypeOf(a) == Object.prototype + }, + isFunction(a: any): a is Function { + return typeof a === 'function' + }, + isLikelyReactComponent(type: any): Boolean { + switch (typeof type) { + case 'function': + if (type.prototype != null) { + if (type.prototype.isReactComponent) { + return true + } + const ownNames = Object.getOwnPropertyNames(type.prototype); + if (ownNames.length > 1 || ownNames[0] !== 'constructor') { + return false + } + } + const name = type.name || type.displayName + return typeof name === 'string' && /^[A-Z]/.test(name) + case 'object': + if (type != null) { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + case REACT_MEMO_TYPE: + return true + default: + return false + } + } + return false + default: + return false + } + }, + isHttpUrl(url: string) { + try { + const { protocol } = new URL(url) + return protocol === 'https:' || protocol === 'http:' + } catch (error) { + return false + } + }, + trimPrefix(s: string, prefix: string): string { + if (prefix !== '' && s.startsWith(prefix)) { + return s.slice(prefix.length) + } + return s + }, + trimSuffix(s: string, suffix: string): string { + if (suffix !== '' && s.endsWith(suffix)) { + return s.slice(0, -suffix.length) + } + return s + }, + ensureExt(s: string, ext: string): string { + if (s.endsWith(ext)) { + return s + } + return s + ext + }, + splitBy(s: string, searchString: string): [string, string] { + const i = s.indexOf(searchString) + if (i >= 0) { + return [s.slice(0, i), s.slice(i + 1)] + } + return [s, ''] + }, + bytesString(bytes: number) { + if (bytes < KB) { + return bytes.toString() + 'B' + } + if (bytes < MB) { + return Math.ceil(bytes / KB) + 'KB' + } + if (bytes < GB) { + return (bytes / MB).toFixed(1).replace(/\.0$/, '') + 'MB' + } + if (bytes < TB) { + return (bytes / GB).toFixed(1).replace(/\.0$/, '') + 'GB' + } + if (bytes < PB) { + return (bytes / TB).toFixed(1).replace(/\.0$/, '') + 'TB' + } + return (bytes / PB).toFixed(1).replace(/\.0$/, '') + 'PB' + }, + splitPath(path: string): string[] { + return path + .split(/[\/\\]/g) + .map(p => p.trim()) + .filter(p => p !== '' && p !== '.') + .reduce((path, p) => { + if (p === '..') { + path.pop() + } else { + path.push(p) + } + return path + }, [] as Array) + }, + cleanPath(path: string): string { + return '/' + this.splitPath(path).join('/') + }, + debounce(callback: T, delay: number): T { + let timer: number | null = null + return ((...args: any[]) => { + if (timer != null) { + clearTimeout(timer) + } + timer = setTimeout(() => { + timer = null + callback(...args) + }, delay) + }) as any + }, + debounceX(id: string, callback: () => void, delay: number) { + const self = this as any + const timers: Map = self.__debounce_timers || (self.__debounce_timers = new Map()) + if (timers.has(id)) { + clearTimeout(timers.get(id)!) + } + timers.set(id, setTimeout(() => { + timers.delete(id) + callback() + }, delay)) + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/02c7482bc02d703d0f4d3e4d28188d2f0e0deb40.ts b/crates/swc_bundler/tests/.cache/untrusted/02c7482bc02d703d0f4d3e4d28188d2f0e0deb40.ts new file mode 100644 index 000000000000..eb8d1dba8ca9 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/02c7482bc02d703d0f4d3e4d28188d2f0e0deb40.ts @@ -0,0 +1,106 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/msg.ts + + +/* + * Copyright 2020 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Empty, Msg } from "./types.ts"; +import { MsgHdrs, MsgHdrsImpl } from "./headers.ts"; +import type { Publisher } from "./protocol.ts"; +import type { MsgArg } from "./parser.ts"; +import { TD } from "./encoders.ts"; +import { ErrorCode, NatsError } from "./error.ts"; + +export function isRequestError(msg: Msg): (NatsError | null) { + if (msg && msg.headers) { + const headers = msg.headers as MsgHdrsImpl; + if (headers.hasError) { + if (headers.status === "503") { + return NatsError.errorForCode(ErrorCode.NoResponders); + } else { + let desc = headers.get("description"); + if (desc === "") { + desc = ErrorCode.RequestError; + } + desc = desc.toLowerCase(); + return new NatsError(desc, headers.status); + } + } + } + return null; +} + +export class MsgImpl implements Msg { + _headers?: MsgHdrs; + _msg: MsgArg; + _rdata: Uint8Array; + _reply!: string; + _subject!: string; + publisher: Publisher; + + constructor(msg: MsgArg, data: Uint8Array, publisher: Publisher) { + this._msg = msg; + this._rdata = data; + this.publisher = publisher; + } + + get subject(): string { + if (this._subject) { + return this._subject; + } + this._subject = TD.decode(this._msg.subject); + return this._subject; + } + + get reply(): string { + if (this._reply) { + return this._reply; + } + this._reply = TD.decode(this._msg.reply); + return this._reply; + } + + get sid(): number { + return this._msg.sid; + } + + get headers(): (MsgHdrs | undefined) { + if (this._msg.hdr > -1 && !this._headers) { + const buf = this._rdata.subarray(0, this._msg.hdr); + this._headers = MsgHdrsImpl.decode(buf); + } + return this._headers; + } + + get data(): Uint8Array { + if (!this._rdata) { + return new Uint8Array(0); + } + return this._msg.hdr > -1 + ? this._rdata.subarray(this._msg.hdr) + : this._rdata; + } + + // eslint-ignore-next-line @typescript-eslint/no-explicit-any + respond( + data: Uint8Array = Empty, + opts?: { headers?: MsgHdrs; reply?: string }, + ): boolean { + if (this.reply) { + this.publisher.publish(this.reply, data, opts); + return true; + } + return false; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/03ecbbdf07269ff9702167ca4318bcba6ac86026.ts b/crates/swc_bundler/tests/.cache/untrusted/03ecbbdf07269ff9702167ca4318bcba6ac86026.ts new file mode 100644 index 000000000000..c6acfff5524c --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/03ecbbdf07269ff9702167ca4318bcba6ac86026.ts @@ -0,0 +1,121 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/databuffer.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { TD, TE } from "./encoders.ts"; + +export class DataBuffer { + buffers: Uint8Array[]; + byteLength: number; + + constructor() { + this.buffers = []; + this.byteLength = 0; + } + + static concat(...bufs: Uint8Array[]): Uint8Array { + let max = 0; + for (let i = 0; i < bufs.length; i++) { + max += bufs[i].length; + } + const out = new Uint8Array(max); + let index = 0; + for (let i = 0; i < bufs.length; i++) { + out.set(bufs[i], index); + index += bufs[i].length; + } + return out; + } + + static fromAscii(m: string): Uint8Array { + if (!m) { + m = ""; + } + return TE.encode(m); + } + + static toAscii(a: Uint8Array): string { + return TD.decode(a); + } + + reset(): void { + this.buffers.length = 0; + this.byteLength = 0; + } + + pack(): void { + if (this.buffers.length > 1) { + const v = new Uint8Array(this.byteLength); + let index = 0; + for (let i = 0; i < this.buffers.length; i++) { + v.set(this.buffers[i], index); + index += this.buffers[i].length; + } + this.buffers.length = 0; + this.buffers.push(v); + } + } + + drain(n?: number): Uint8Array { + if (this.buffers.length) { + this.pack(); + const v = this.buffers.pop(); + if (v) { + const max = this.byteLength; + if (n === undefined || n > max) { + n = max; + } + const d = v.subarray(0, n); + if (max > n) { + this.buffers.push(v.subarray(n)); + } + this.byteLength = max - n; + return d; + } + } + return new Uint8Array(0); + } + + fill(a: Uint8Array, ...bufs: Uint8Array[]): void { + if (a) { + this.buffers.push(a); + this.byteLength += a.length; + } + for (let i = 0; i < bufs.length; i++) { + if (bufs[i] && bufs[i].length) { + this.buffers.push(bufs[i]); + this.byteLength += bufs[i].length; + } + } + } + + peek(): Uint8Array { + if (this.buffers.length) { + this.pack(); + return this.buffers[0]; + } + return new Uint8Array(0); + } + + size(): number { + return this.byteLength; + } + + length(): number { + return this.buffers.length; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/10263905cbabe47c396d361b5a5521d22dc387e3.ts b/crates/swc_bundler/tests/.cache/untrusted/10263905cbabe47c396d361b5a5521d22dc387e3.ts new file mode 100644 index 000000000000..5a9fbb32411a --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/10263905cbabe47c396d361b5a5521d22dc387e3.ts @@ -0,0 +1,60 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/codec.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ErrorCode, NatsError } from "./error.ts"; +import { TD, TE } from "./encoders.ts"; + +export interface Codec { + encode(d: T): Uint8Array; + decode(a: Uint8Array): T; +} + +export function StringCodec(): Codec { + return { + encode(d: string): Uint8Array { + return TE.encode(d); + }, + decode(a: Uint8Array): string { + return TD.decode(a); + }, + }; +} + +export function JSONCodec(): Codec { + return { + encode(d: T): Uint8Array { + try { + if (d === undefined) { + // @ts-ignore: json will not handle undefined + d = null; + } + return TE.encode(JSON.stringify(d)); + } catch (err) { + throw NatsError.errorForCode(ErrorCode.BadJson, err); + } + }, + + decode(a: Uint8Array): T { + try { + return JSON.parse(TD.decode(a)); + } catch (err) { + throw NatsError.errorForCode(ErrorCode.BadJson, err); + } + }, + }; +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/22a34b30a2f256e824d3e27cececccee8d1a4633.ts b/crates/swc_bundler/tests/.cache/untrusted/22a34b30a2f256e824d3e27cececccee8d1a4633.ts new file mode 100644 index 000000000000..8f16fb50b0fa --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/22a34b30a2f256e824d3e27cececccee8d1a4633.ts @@ -0,0 +1,169 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsmsg.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + DeliveryInfo, + JsMsg, + Msg, + NextRequest, + RequestOptions, +} from "./types.ts"; +import { MsgHdrs } from "./headers.ts"; +import { DataBuffer } from "./databuffer.ts"; +import { JSONCodec } from "./codec.ts"; +import { MsgImpl } from "./msg.ts"; +import { ProtocolHandler } from "./protocol.ts"; +import { Request } from "./request.ts"; + +export const ACK = Uint8Array.of(43, 65, 67, 75); +const NAK = Uint8Array.of(45, 78, 65, 75); +const WPI = Uint8Array.of(43, 87, 80, 73); +const NXT = Uint8Array.of(43, 78, 88, 84); +const TERM = Uint8Array.of(43, 84, 69, 82, 77); +const SPACE = Uint8Array.of(32); + +export function toJsMsg(m: Msg): JsMsg { + return new JsMsgImpl(m); +} + +export function parseInfo(s: string): DeliveryInfo { + const tokens = s.split("."); + if (tokens.length !== 9 && tokens[0] !== "$JS" && tokens[1] !== "ACK") { + throw new Error(`not js message`); + } + // "$JS.ACK....." + const di = {} as DeliveryInfo; + di.stream = tokens[2]; + di.consumer = tokens[3]; + di.redeliveryCount = parseInt(tokens[4], 10); + di.streamSequence = parseInt(tokens[5], 10); + di.deliverySequence = parseInt(tokens[6], 10); + di.timestampNanos = parseInt(tokens[7], 10); + di.pending = parseInt(tokens[8], 10); + return di; +} + +class JsMsgImpl implements JsMsg { + msg: Msg; + di?: DeliveryInfo; + didAck: boolean; + + constructor(msg: Msg) { + this.msg = msg; + this.didAck = false; + } + + get subject(): string { + return this.msg.subject; + } + + get sid(): number { + return this.msg.sid; + } + + get data(): Uint8Array { + return this.msg.data; + } + + get headers(): MsgHdrs { + return this.msg.headers!; + } + + get info(): DeliveryInfo { + if (!this.di) { + this.di = parseInfo(this.reply); + } + return this.di; + } + + get redelivered(): boolean { + return this.info.redeliveryCount > 1; + } + + get reply(): string { + return this.msg.reply ?? ""; + } + + get seq(): number { + return this.info.streamSequence; + } + + doAck(payload: Uint8Array) { + if (!this.didAck) { + this.didAck = true; + this.msg.respond(payload); + } + } + + // this has to dig into the internals as the message has access + // to the protocol but not the high-level client. + async ackAck(): Promise { + if (!this.didAck) { + this.didAck = true; + if (this.msg.reply) { + const mi = this.msg as MsgImpl; + const proto = mi.publisher as unknown as ProtocolHandler; + const r = new Request(proto.muxSubscriptions); + proto.request(r); + try { + proto.publish( + this.msg.reply, + ACK, + { + reply: `${proto.muxSubscriptions.baseInbox}${r.token}`, + }, + ); + } catch (err) { + r.cancel(err); + } + try { + await Promise.race([r.timer, r.deferred]); + return true; + } catch (err) { + r.cancel(err); + } + } + } + return false; + } + + ack() { + this.doAck(ACK); + } + + nak() { + this.doAck(NAK); + } + + working() { + this.doAck(WPI); + } + + next(subj?: string, ro?: Partial) { + let payload = NXT; + if (ro) { + const data = JSONCodec().encode(ro); + payload = DataBuffer.concat(NXT, SPACE, data); + } + const opts = subj ? { reply: subj } as RequestOptions : undefined; + this.msg.respond(payload, opts); + } + + term() { + this.doAck(TERM); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/22dae7c239360846844d5e0f7829bf09eb7268d6.ts b/crates/swc_bundler/tests/.cache/untrusted/22dae7c239360846844d5e0f7829bf09eb7268d6.ts new file mode 100644 index 000000000000..f89b994044df --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/22dae7c239360846844d5e0f7829bf09eb7268d6.ts @@ -0,0 +1,156 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsstream_api.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Empty, + JetStreamOptions, + Lister, + MsgDeleteRequest, + MsgRequest, + NatsConnection, + PurgeResponse, + StoredMsg, + StreamAPI, + StreamConfig, + StreamInfo, + StreamListResponse, + StreamMsgResponse, + SuccessResponse, +} from "./types.ts"; +import { BaseApiClient } from "./jsbaseclient_api.ts"; +import { ListerFieldFilter, ListerImpl } from "./jslister.ts"; +import { validateStreamName } from "./jsutil.ts"; +import { headers, MsgHdrs, MsgHdrsImpl } from "./headers.ts"; + +export class StreamAPIImpl extends BaseApiClient implements StreamAPI { + constructor(nc: NatsConnection, opts?: JetStreamOptions) { + super(nc, opts); + } + + async add(cfg = {} as Partial): Promise { + validateStreamName(cfg.name); + const r = await this._request( + `${this.prefix}.STREAM.CREATE.${cfg.name}`, + cfg, + ); + return r as StreamInfo; + } + + async delete(stream: string): Promise { + validateStreamName(stream); + const r = await this._request(`${this.prefix}.STREAM.DELETE.${stream}`); + const cr = r as SuccessResponse; + return cr.success; + } + + async update(cfg = {} as StreamConfig): Promise { + validateStreamName(cfg.name); + const r = await this._request( + `${this.prefix}.STREAM.UPDATE.${cfg.name}`, + cfg, + ); + return r as StreamInfo; + } + + async info(name: string): Promise { + validateStreamName(name); + const r = await this._request(`${this.prefix}.STREAM.INFO.${name}`); + return r as StreamInfo; + } + + list(): Lister { + const filter: ListerFieldFilter = ( + v: unknown, + ): StreamInfo[] => { + const slr = v as StreamListResponse; + return slr.streams; + }; + const subj = `${this.prefix}.STREAM.LIST`; + return new ListerImpl(subj, filter, this); + } + + async purge(name: string): Promise { + validateStreamName(name); + const v = await this._request(`${this.prefix}.STREAM.PURGE.${name}`); + return v as PurgeResponse; + } + + async deleteMessage( + stream: string, + seq: number, + erase = true, + ): Promise { + validateStreamName(stream); + const dr = { seq } as MsgDeleteRequest; + if (!erase) { + dr.no_erase = true; + } + const r = await this._request( + `${this.prefix}.STREAM.MSG.DELETE.${stream}`, + dr, + ); + const cr = r as SuccessResponse; + return cr.success; + } + + async getMessage(stream: string, seq: number): Promise { + validateStreamName(stream); + const dr = { seq } as MsgRequest; + const r = await this._request( + `${this.prefix}.STREAM.MSG.GET.${stream}`, + dr, + ); + const sm = r as StreamMsgResponse; + return new StoredMsgImpl(sm); + } + + find(subject: string): Promise { + return this.findStream(subject); + } +} + +export class StoredMsgImpl implements StoredMsg { + subject: string; + seq: number; + data: Uint8Array; + time: Date; + header: MsgHdrs; + + constructor(smr: StreamMsgResponse) { + this.subject = smr.message.subject; + this.seq = smr.message.seq; + this.time = new Date(smr.message.time); + this.data = smr.message.data ? this._parse(smr.message.data) : Empty; + if (smr.message.hdrs) { + const hd = this._parse(smr.message.hdrs); + this.header = MsgHdrsImpl.decode(hd); + } else { + this.header = headers(); + } + } + + _parse(s: string): Uint8Array { + const bs = window.atob(s); + const len = bs.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = bs.charCodeAt(i); + } + return bytes; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/290c637324e5380b84e1d1c49511616be2e24f07.ts b/crates/swc_bundler/tests/.cache/untrusted/290c637324e5380b84e1d1c49511616be2e24f07.ts new file mode 100644 index 000000000000..afc12af176a1 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/290c637324e5380b84e1d1c49511616be2e24f07.ts @@ -0,0 +1,303 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/nats.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { deferred, isUint8Array } from "./util.ts"; +import { createInbox, ProtocolHandler } from "./protocol.ts"; +import { SubscriptionImpl } from "./subscription.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { + ConnectionOptions, + Empty, + JetStreamClient, + JetStreamManager, + JetStreamOptions, + Msg, + NatsConnection, + PublishOptions, + RequestOptions, + ServerInfo, + Stats, + Status, + Subscription, + SubscriptionOptions, +} from "./types.ts"; +import { parseOptions } from "./options.ts"; +import { QueuedIterator, QueuedIteratorImpl } from "./queued_iterator.ts"; +import { Request } from "./request.ts"; +import { isRequestError } from "./msg.ts"; +import { JetStreamManagerImpl } from "./jsm.ts"; +import { JetStreamClientImpl } from "./jsclient.ts"; + +export class NatsConnectionImpl implements NatsConnection { + options: ConnectionOptions; + protocol!: ProtocolHandler; + draining: boolean; + listeners: QueuedIterator[]; + + private constructor(opts: ConnectionOptions) { + this.draining = false; + this.options = parseOptions(opts); + this.listeners = []; + } + + public static connect(opts: ConnectionOptions = {}): Promise { + return new Promise((resolve, reject) => { + const nc = new NatsConnectionImpl(opts); + ProtocolHandler.connect(nc.options, nc) + .then((ph: ProtocolHandler) => { + nc.protocol = ph; + (async function () { + for await (const s of ph.status()) { + nc.listeners.forEach((l) => { + l.push(s); + }); + } + })(); + resolve(nc); + }) + .catch((err: Error) => { + reject(err); + }); + }); + } + + closed(): Promise { + return this.protocol.closed; + } + + async close() { + await this.protocol.close(); + } + + publish( + subject: string, + data: Uint8Array = Empty, + options?: PublishOptions, + ): void { + subject = subject || ""; + if (subject.length === 0) { + throw NatsError.errorForCode(ErrorCode.BadSubject); + } + // if argument is not undefined/null and not a Uint8Array, toss + if (data && !isUint8Array(data)) { + throw NatsError.errorForCode(ErrorCode.BadPayload); + } + this.protocol.publish(subject, data, options); + } + + subscribe( + subject: string, + opts: SubscriptionOptions = {}, + ): Subscription { + if (this.isClosed()) { + throw NatsError.errorForCode(ErrorCode.ConnectionClosed); + } + if (this.isDraining()) { + throw NatsError.errorForCode(ErrorCode.ConnectionDraining); + } + subject = subject || ""; + if (subject.length === 0) { + throw NatsError.errorForCode(ErrorCode.BadSubject); + } + + const sub = new SubscriptionImpl(this.protocol, subject, opts); + this.protocol.subscribe(sub); + return sub; + } + + request( + subject: string, + data: Uint8Array = Empty, + opts: RequestOptions = { timeout: 1000, noMux: false }, + ): Promise { + if (this.isClosed()) { + return Promise.reject( + NatsError.errorForCode(ErrorCode.ConnectionClosed), + ); + } + if (this.isDraining()) { + return Promise.reject( + NatsError.errorForCode(ErrorCode.ConnectionDraining), + ); + } + subject = subject || ""; + if (subject.length === 0) { + return Promise.reject(NatsError.errorForCode(ErrorCode.BadSubject)); + } + opts.timeout = opts.timeout || 1000; + if (opts.timeout < 1) { + return Promise.reject(new NatsError("timeout", ErrorCode.InvalidOption)); + } + if (!opts.noMux && opts.reply) { + return Promise.reject( + new NatsError( + "reply can only be used with noMux", + ErrorCode.InvalidOption, + ), + ); + } + + if (opts.noMux) { + const inbox = opts.reply + ? opts.reply + : createInbox(this.options.inboxPrefix); + const d = deferred(); + this.subscribe( + inbox, + { + max: 1, + timeout: opts.timeout, + callback: (err, msg) => { + if (err) { + d.reject(err); + } else { + err = isRequestError(msg); + if (err) { + d.reject(err); + } else { + d.resolve(msg); + } + } + }, + }, + ); + this.publish(subject, data, { reply: inbox }); + return d; + } else { + const r = new Request(this.protocol.muxSubscriptions, opts); + this.protocol.request(r); + + try { + this.publish( + subject, + data, + { + reply: `${this.protocol.muxSubscriptions.baseInbox}${r.token}`, + headers: opts.headers, + }, + ); + } catch (err) { + r.cancel(err); + } + + const p = Promise.race([r.timer, r.deferred]); + p.catch(() => { + r.cancel(); + }); + return p; + } + } + + /*** + * Flushes to the server. Promise resolves when round-trip completes. + * @returns {Promise} + */ + flush(): Promise { + return this.protocol.flush(); + } + + drain(): Promise { + if (this.isClosed()) { + return Promise.reject( + NatsError.errorForCode(ErrorCode.ConnectionClosed), + ); + } + if (this.isDraining()) { + return Promise.reject( + NatsError.errorForCode(ErrorCode.ConnectionDraining), + ); + } + this.draining = true; + return this.protocol.drain(); + } + + isClosed(): boolean { + return this.protocol.isClosed(); + } + + isDraining(): boolean { + return this.draining; + } + + getServer(): string { + const srv = this.protocol.getServer(); + return srv ? srv.listen : ""; + } + + status(): AsyncIterable { + const iter = new QueuedIteratorImpl(); + this.listeners.push(iter); + return iter; + } + + get info(): (ServerInfo | undefined) { + return this.protocol.isClosed() ? undefined : this.protocol.info; + } + + stats(): Stats { + return { + inBytes: this.protocol.inBytes, + outBytes: this.protocol.outBytes, + inMsgs: this.protocol.inMsgs, + outMsgs: this.protocol.outMsgs, + }; + } + + async jetstreamManager( + opts: JetStreamOptions = {}, + ): Promise { + jetstreamPreview(this); + const adm = new JetStreamManagerImpl(this, opts); + try { + await adm.getAccountInfo(); + } catch (err) { + const ne = err as NatsError; + if (ne.code === ErrorCode.NoResponders) { + throw NatsError.errorForCode(ErrorCode.JetStreamNotEnabled); + } + throw ne; + } + return adm; + } + + jetstream( + opts: JetStreamOptions = {}, + ): JetStreamClient { + jetstreamPreview(this); + return new JetStreamClientImpl(this, opts); + } +} + +const jetstreamPreview = (() => { + let once = false; + return (nci: NatsConnectionImpl) => { + if (!once) { + once = true; + const { lang } = nci?.protocol?.transport; + if (lang) { + console.log( + `\u001B[33m >> jetstream functionality in ${lang} is preview functionality \u001B[0m`, + ); + } else { + console.log( + `\u001B[33m >> jetstream functionality is preview functionality \u001B[0m`, + ); + } + } + }; +})(); diff --git a/crates/swc_bundler/tests/.cache/untrusted/2afc345e783f9aec6732115ea1b911a7e6a904ae.ts b/crates/swc_bundler/tests/.cache/untrusted/2afc345e783f9aec6732115ea1b911a7e6a904ae.ts new file mode 100644 index 000000000000..ddeb0d32819d --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/2afc345e783f9aec6732115ea1b911a7e6a904ae.ts @@ -0,0 +1,107 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsutil.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + AckPolicy, + ConsumerConfig, + DeliverPolicy, + Msg, + Nanos, + ReplayPolicy, +} from "./types.ts"; +import { ErrorCode, NatsError } from "./error.ts"; + +export function validateDurableName(name?: string) { + return validateName("durable", name); +} + +export function validateStreamName(name?: string) { + return validateName("stream", name); +} + +export function validateName(context: string, name = "") { + if (name === "") { + throw Error(`${context} name required`); + } + const bad = [".", "*", ">"]; + bad.forEach((v) => { + if (name.indexOf(v) !== -1) { + throw Error( + `invalid ${context} name - ${context} name cannot contain '${v}'`, + ); + } + }); +} + +export function defaultConsumer( + name: string, + opts: Partial = {}, +): ConsumerConfig { + return Object.assign({ + name: name, + deliver_policy: DeliverPolicy.All, + ack_policy: AckPolicy.Explicit, + ack_wait: nanos(30 * 1000), + replay_policy: ReplayPolicy.Instant, + }, opts); +} + +export function nanos(millis: number): Nanos { + return millis * 1000000; +} + +export function millis(ns: Nanos) { + return ns / 1000000; +} + +export function isFlowControlMsg(msg: Msg): boolean { + const h = msg.headers; + if (!h) { + return false; + } + return h.code >= 100 && h.code < 200; +} + +export function checkJsError(msg: Msg): NatsError | null { + const h = msg.headers; + if (!h) { + return null; + } + return checkJsErrorCode(h.code, h.status); +} + +export function checkJsErrorCode( + code: number, + description = "", +): NatsError | null { + if (code < 300) { + return null; + } + description = description.toLowerCase(); + switch (code) { + case 503: + return NatsError.errorForCode( + ErrorCode.JetStreamNotEnabled, + new Error(description), + ); + default: + if (description === "") { + description = ErrorCode.Unknown; + } + return new NatsError(description, `${code}`); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/2bd5df2debc51a446431df617d15587c9e2cd31f.ts b/crates/swc_bundler/tests/.cache/untrusted/2bd5df2debc51a446431df617d15587c9e2cd31f.ts new file mode 100644 index 000000000000..fc501717be20 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/2bd5df2debc51a446431df617d15587c9e2cd31f.ts @@ -0,0 +1,218 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/servers.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +import { + DEFAULT_HOST, + DEFAULT_PORT, + Server, + ServerInfo, + ServersChanged, + URLParseFn, +} from "./types.ts"; +import { defaultPort, getUrlParseFn } from "./transport.ts"; +import { shuffle } from "./util.ts"; +import { isIP } from "./ipparser.ts"; + +/** + * @hidden + */ +export class ServerImpl implements Server { + src: string; + listen: string; + hostname: string; + port: number; + didConnect: boolean; + reconnects: number; + lastConnect: number; + gossiped: boolean; + tlsName: string; + + constructor(u: string, gossiped = false) { + this.src = u; + this.tlsName = ""; + // remove any protocol that may have been provided + if (u.match(/^(.*:\/\/)(.*)/m)) { + u = u.replace(/^(.*:\/\/)(.*)/gm, "$2"); + } + // in web environments, URL may not be a living standard + // that means that protocols other than HTTP/S are not + // parsable correctly. + const url = new URL(`http://${u}`); + if (!url.port) { + url.port = `${DEFAULT_PORT}`; + } + this.listen = url.host; + this.hostname = url.hostname; + this.port = parseInt(url.port, 10); + + this.didConnect = false; + this.reconnects = 0; + this.lastConnect = 0; + this.gossiped = gossiped; + } + + toString(): string { + return this.listen; + } +} + +export interface ServersOptions { + urlParseFn?: URLParseFn; +} + +/** + * @hidden + */ +export class Servers { + private firstSelect: boolean; + private readonly servers: ServerImpl[]; + private currentServer: ServerImpl; + private tlsName: string; + + constructor( + randomize: boolean, + listens: string[] = [], + opts: ServersOptions = {}, + ) { + this.firstSelect = true; + this.servers = [] as ServerImpl[]; + this.tlsName = ""; + + const urlParseFn = getUrlParseFn(); + if (listens) { + listens.forEach((hp) => { + hp = urlParseFn ? urlParseFn(hp) : hp; + this.servers.push(new ServerImpl(hp)); + }); + if (randomize) { + this.servers = shuffle(this.servers); + } + } + if (this.servers.length === 0) { + this.addServer(`${DEFAULT_HOST}:${defaultPort()}`, false); + } + this.currentServer = this.servers[0]; + } + + updateTLSName(): void { + const cs = this.getCurrentServer(); + if (!isIP(cs.hostname)) { + this.tlsName = cs.hostname; + this.servers.forEach((s) => { + if (s.gossiped) { + s.tlsName = this.tlsName; + } + }); + } + } + + getCurrentServer(): ServerImpl { + return this.currentServer; + } + + addServer(u: string, implicit = false): void { + const urlParseFn = getUrlParseFn(); + u = urlParseFn ? urlParseFn(u) : u; + const s = new ServerImpl(u, implicit); + if (isIP(s.hostname)) { + s.tlsName = this.tlsName; + } + this.servers.push(s); + } + + selectServer(): ServerImpl | undefined { + // allow using select without breaking the order of the servers + if (this.firstSelect) { + this.firstSelect = false; + return this.currentServer; + } + const t = this.servers.shift(); + if (t) { + this.servers.push(t); + this.currentServer = t; + } + return t; + } + + removeCurrentServer(): void { + this.removeServer(this.currentServer); + } + + removeServer(server: ServerImpl | undefined): void { + if (server) { + const index = this.servers.indexOf(server); + this.servers.splice(index, 1); + } + } + + length(): number { + return this.servers.length; + } + + next(): ServerImpl | undefined { + return this.servers.length ? this.servers[0] : undefined; + } + + getServers(): ServerImpl[] { + return this.servers; + } + + update(info: ServerInfo): ServersChanged { + const added: string[] = []; + let deleted: string[] = []; + + const urlParseFn = getUrlParseFn(); + const discovered = new Map(); + if (info.connect_urls && info.connect_urls.length > 0) { + info.connect_urls.forEach((hp) => { + hp = urlParseFn ? urlParseFn(hp) : hp; + const s = new ServerImpl(hp, true); + discovered.set(hp, s); + }); + } + // remove gossiped servers that are no longer reported + const toDelete: number[] = []; + this.servers.forEach((s, index) => { + const u = s.listen; + if ( + s.gossiped && this.currentServer.listen !== u && + discovered.get(u) === undefined + ) { + // server was removed + toDelete.push(index); + } + // remove this entry from reported + discovered.delete(u); + }); + + // perform the deletion + toDelete.reverse(); + toDelete.forEach((index) => { + const removed = this.servers.splice(index, 1); + deleted = deleted.concat(removed[0].listen); + }); + + // remaining servers are new + discovered.forEach((v, k, m) => { + this.servers.push(v); + added.push(k); + }); + + return { added, deleted }; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/330b71f59d2855c8c4c511faec68b548adf17233.ts b/crates/swc_bundler/tests/.cache/untrusted/330b71f59d2855c8c4c511faec68b548adf17233.ts new file mode 100644 index 000000000000..fda27f5c6d75 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/330b71f59d2855c8c4c511faec68b548adf17233.ts @@ -0,0 +1,64 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/request.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Deferred, deferred, extend, Timeout, timeout } from "./util.ts"; +import type { Msg, RequestOptions } from "./types.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import type { MuxSubscription } from "./muxsubscription.ts"; +import { nuid } from "./nuid.ts"; + +export class Request { + token: string; + received: number; + deferred: Deferred; + timer: Timeout; + private mux: MuxSubscription; + + constructor( + mux: MuxSubscription, + opts: RequestOptions = { timeout: 1000 }, + ) { + this.mux = mux; + this.received = 0; + this.deferred = deferred(); + this.token = nuid.next(); + extend(this, opts); + this.timer = timeout(opts.timeout); + } + + resolver(err: Error | null, msg: Msg): void { + if (this.timer) { + this.timer.cancel(); + } + if (err) { + this.deferred.reject(err); + } else { + this.deferred.resolve(msg); + } + this.cancel(); + } + + cancel(err?: NatsError): void { + if (this.timer) { + this.timer.cancel(); + } + this.mux.cancel(this); + this.deferred.reject( + err ? err : NatsError.errorForCode(ErrorCode.Cancelled), + ); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/409944ba160d3dfa44bff012c86487577e7696b7.ts b/crates/swc_bundler/tests/.cache/untrusted/409944ba160d3dfa44bff012c86487577e7696b7.ts new file mode 100644 index 000000000000..e01396280058 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/409944ba160d3dfa44bff012c86487577e7696b7.ts @@ -0,0 +1,160 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsconsumeropts.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AckPolicy, + ConsumerConfig, + ConsumerOpts, + DeliverPolicy, + JsMsgCallback, + Nanos, +} from "./types.ts"; +import { defaultConsumer, validateDurableName } from "./jsutil.ts"; + +export interface ConsumerOptsBuilder { + deliverTo(subject: string): void; + manualAck(): void; + durable(name: string): void; + deliverAll(): void; + deliverLast(): void; + deliverNew(): void; + startSequence(seq: number): void; + startTime(time: Date | Nanos): void; + ackNone(): void; + ackAll(): void; + ackExplicit(): void; + maxDeliver(max: number): void; + maxAckPending(max: number): void; + maxWaiting(max: number): void; + maxMessages(max: number): void; + callback(fn: JsMsgCallback): void; + + // FIXME: 503: + // maxRetries() + // retryBackoff() + + // ackWait(time) + // replayOriginal() + // rateLimit(bytesPerSec) +} + +export function consumerOpts(): ConsumerOptsBuilder { + return new ConsumerOptsBuilderImpl(); +} + +export class ConsumerOptsBuilderImpl implements ConsumerOptsBuilder { + config: Partial; + mack: boolean; + stream: string; + callbackFn?: JsMsgCallback; + max?: number; + + constructor() { + this.stream = ""; + this.mack = false; + this.config = defaultConsumer(""); + // not set + this.config.ack_policy = AckPolicy.All; + } + + getOpts(): ConsumerOpts { + const o = {} as ConsumerOpts; + o.config = this.config; + o.mack = this.mack; + o.stream = this.stream; + o.callbackFn = this.callbackFn; + o.max = this.max; + return o; + } + + deliverTo(subject: string) { + this.config.deliver_subject = subject; + } + + manualAck() { + this.mack = true; + } + + durable(name: string) { + validateDurableName(name); + this.config.durable_name = name; + } + + deliverAll() { + this.config.deliver_policy = DeliverPolicy.All; + } + + deliverLast() { + this.config.deliver_policy = DeliverPolicy.Last; + } + + deliverNew() { + this.config.deliver_policy = DeliverPolicy.New; + } + + startSequence(seq: number) { + if (seq <= 0) { + throw new Error("sequence must be greater than 0"); + } + this.config.deliver_policy = DeliverPolicy.StartSequence; + this.config.opt_start_seq = seq; + } + + startTime(time: Date) { + this.config.deliver_policy = DeliverPolicy.StartTime; + this.config.opt_start_time = time.toISOString(); + } + + ackNone() { + this.config.ack_policy = AckPolicy.None; + } + + ackAll() { + this.config.ack_policy = AckPolicy.All; + } + + ackExplicit() { + this.config.ack_policy = AckPolicy.Explicit; + } + + maxDeliver(max: number) { + this.config.max_deliver = max; + } + + maxAckPending(max: number) { + this.config.max_ack_pending = max; + } + + maxWaiting(max: number) { + this.config.max_waiting = max; + } + + maxMessages(max: number) { + this.max = max; + } + + callback(fn: JsMsgCallback) { + this.callbackFn = fn; + } +} + +export function isConsumerOptsBuilder( + o: ConsumerOptsBuilder | Partial, +): o is ConsumerOptsBuilderImpl { + return typeof (o as ConsumerOptsBuilderImpl).getOpts === "function"; +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/46237a3cb626635e98640eb6a45ec85a619ac35b.ts b/crates/swc_bundler/tests/.cache/untrusted/46237a3cb626635e98640eb6a45ec85a619ac35b.ts new file mode 100644 index 000000000000..645114411e3e --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/46237a3cb626635e98640eb6a45ec85a619ac35b.ts @@ -0,0 +1,6 @@ +// Loaded from https://esm.sh/react + + +/* esm.sh - react@18.3.1 */ +export * from "/stable/react@18.3.1/esnext/react.mjs"; +export { default } from "/stable/react@18.3.1/esnext/react.mjs"; diff --git a/crates/swc_bundler/tests/.cache/untrusted/4926e3f982a035c5474ec05e82f5d808bd641fe8.ts b/crates/swc_bundler/tests/.cache/untrusted/4926e3f982a035c5474ec05e82f5d808bd641fe8.ts new file mode 100644 index 000000000000..79b2ce34fb86 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/4926e3f982a035c5474ec05e82f5d808bd641fe8.ts @@ -0,0 +1,117 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/internal_mod.ts + + +export { NatsConnectionImpl } from "./nats.ts"; +export { Nuid, nuid } from "./nuid.ts"; +export { ErrorCode, NatsError } from "./error.ts"; +export type { + Msg, + NatsConnection, + PublishOptions, + RequestOptions, + Server, + ServerInfo, + ServersChanged, + Status, + Sub, + SubOpts, + Subscription, + SubscriptionOptions, +} from "./types.ts"; + +export type { + AccountLimits, + ClusterInfo, + ConnectionOptions, + Consumer, + ConsumerConfig, + ConsumerOpts, + DeliveryInfo, + JetStreamAccountStats, + JetStreamApiStats, + JetStreamClient, + JetStreamManager, + JetStreamOptions, + JetStreamPublishOptions, + JetStreamPullSubscription, + JetStreamSubscription, + JetStreamSubscriptionOptions, + JsMsg, + JsMsgCallback, + Lister, + LostStreamData, + MsgDeleteRequest, + MsgRequest, + Nanos, + PeerInfo, + Placement, + PullOptions, + SequencePair, + StoredMsg, + StreamConfig, + StreamInfo, + StreamNames, + StreamSource, + StreamSourceInfo, + StreamState, +} from "./types.ts"; + +export { + AckPolicy, + AdvisoryKind, + DeliverPolicy, + DiscardPolicy, + ReplayPolicy, + RetentionPolicy, + StorageType, +} from "./types.ts"; + +export { consumerOpts } from "./jsconsumeropts.ts"; +export type { ConsumerOptsBuilder } from "./jsconsumeropts.ts"; +export { toJsMsg } from "./jsmsg.ts"; + +export { DebugEvents, Empty, Events } from "./types.ts"; +export { MsgImpl } from "./msg.ts"; +export { SubscriptionImpl } from "./subscription.ts"; +export { Subscriptions } from "./subscriptions.ts"; +export { setTransportFactory } from "./transport.ts"; +export type { Transport, TransportFactory } from "./transport.ts"; +export { Connect, createInbox, INFO, ProtocolHandler } from "./protocol.ts"; +export type { Deferred, Timeout } from "./util.ts"; +export { + deferred, + delay, + extend, + extractProtocolMessage, + render, + timeout, +} from "./util.ts"; +export type { MsgHdrs } from "./headers.ts"; +export { headers, MsgHdrsImpl } from "./headers.ts"; +export { Heartbeat } from "./heartbeats.ts"; +export type { PH } from "./heartbeats.ts"; +export { MuxSubscription } from "./muxsubscription.ts"; +export { DataBuffer } from "./databuffer.ts"; +export { checkOptions, checkUnsupportedOption } from "./options.ts"; +export { Request } from "./request.ts"; +export type { Authenticator } from "./authenticator.ts"; +export { + credsAuthenticator, + jwtAuthenticator, + nkeyAuthenticator, +} from "./authenticator.ts"; +export type { Codec } from "./codec.ts"; +export { JSONCodec, StringCodec } from "./codec.ts"; +export * from "./nkeys.ts"; +export type { DispatchedFn, Dispatcher } from "./queued_iterator.ts"; +export type { QueuedIterator } from "./queued_iterator.ts"; +export type { ParserEvent } from "./parser.ts"; +export { Kind, Parser, State } from "./parser.ts"; +export { DenoBuffer, MAX_SIZE, readAll, writeAll } from "./denobuffer.ts"; +export { Bench, Metric } from "./bench.ts"; +export type { BenchOpts } from "./bench.ts"; +export { TD, TE } from "./encoders.ts"; +export { isIP, parseIP } from "./ipparser.ts"; +export { TypedSubscription } from "./typedsub.ts"; +export type { TypedSubscriptionOptions } from "./typedsub.ts"; +export { millis, nanos } from "./jsutil.ts"; diff --git a/crates/swc_bundler/tests/.cache/untrusted/4c76f03c5edf9c6600a0b3a2a7cbbb2f8a080de7.ts b/crates/swc_bundler/tests/.cache/untrusted/4c76f03c5edf9c6600a0b3a2a7cbbb2f8a080de7.ts new file mode 100644 index 000000000000..d892dac3dfaf --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/4c76f03c5edf9c6600a0b3a2a7cbbb2f8a080de7.ts @@ -0,0 +1,4 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/nkeys.ts + + +export * as nkeys from "https://raw.githubusercontent.com/nats-io/nkeys.js/v1.0.0-9/modules/esm/mod.ts"; diff --git a/crates/swc_bundler/tests/.cache/untrusted/5138138b682d39794b0172e5be29f1343ba97e7d.ts b/crates/swc_bundler/tests/.cache/untrusted/5138138b682d39794b0172e5be29f1343ba97e7d.ts new file mode 100644 index 000000000000..be57962c5747 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/5138138b682d39794b0172e5be29f1343ba97e7d.ts @@ -0,0 +1,95 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/subscriptions.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { SubscriptionImpl } from "./subscription.ts"; +import type { NatsError } from "./error.ts"; +import type { Msg } from "./types.ts"; + +export class Subscriptions { + mux!: SubscriptionImpl; + subs: Map; + sidCounter: number; + + constructor() { + this.sidCounter = 0; + this.subs = new Map(); + } + + size(): number { + return this.subs.size; + } + + add(s: SubscriptionImpl): SubscriptionImpl { + this.sidCounter++; + s.sid = this.sidCounter; + this.subs.set(s.sid, s as SubscriptionImpl); + return s; + } + + setMux(s: SubscriptionImpl): SubscriptionImpl { + this.mux = s; + return s; + } + + getMux(): SubscriptionImpl | null { + return this.mux; + } + + get(sid: number): (SubscriptionImpl | undefined) { + return this.subs.get(sid); + } + + all(): (SubscriptionImpl)[] { + const buf = []; + for (const s of this.subs.values()) { + buf.push(s); + } + return buf; + } + + cancel(s: SubscriptionImpl): void { + if (s) { + s.close(); + this.subs.delete(s.sid); + } + } + + handleError(err?: NatsError): boolean { + let handled = false; + if (err) { + const re = /^'Permissions Violation for Subscription to "(\S+)"'/i; + const ma = re.exec(err.message); + if (ma) { + const subj = ma[1]; + this.subs.forEach((sub) => { + if (subj == sub.subject) { + sub.callback(err, {} as Msg); + sub.close(); + handled = sub !== this.mux; + } + }); + } + } + return handled; + } + + close() { + this.subs.forEach((sub) => { + sub.close(); + }); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/52b4c24b8c3274b0dec5338689a1a7635935ed0f.ts b/crates/swc_bundler/tests/.cache/untrusted/52b4c24b8c3274b0dec5338689a1a7635935ed0f.ts new file mode 100644 index 000000000000..699bc41ff1ee --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/52b4c24b8c3274b0dec5338689a1a7635935ed0f.ts @@ -0,0 +1,687 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/types.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { NatsError } from "./error.ts"; +import type { MsgHdrs } from "./headers.ts"; +import type { Authenticator } from "./authenticator.ts"; +import { TypedSubscriptionOptions } from "./typedsub.ts"; +import { QueuedIterator } from "./queued_iterator.ts"; + +export const Empty = new Uint8Array(0); + +export enum Events { + Disconnect = "disconnect", + Reconnect = "reconnect", + Update = "update", + LDM = "ldm", + Error = "error", +} + +export interface Status { + type: Events | DebugEvents; + data: string | ServersChanged | number; +} + +export enum DebugEvents { + Reconnecting = "reconnecting", + PingTimer = "pingTimer", + StaleConnection = "staleConnection", +} + +export const DEFAULT_PORT = 4222; +export const DEFAULT_HOST = "127.0.0.1"; + +// DISCONNECT Parameters, 2 sec wait, 10 tries +export const DEFAULT_RECONNECT_TIME_WAIT = 2 * 1000; +export const DEFAULT_MAX_RECONNECT_ATTEMPTS = 10; +export const DEFAULT_JITTER = 100; +export const DEFAULT_JITTER_TLS = 1000; + +// Ping interval +export const DEFAULT_PING_INTERVAL = 2 * 60 * 1000; // 2 minutes +export const DEFAULT_MAX_PING_OUT = 2; + +export interface ConnectFn { + (opts: ConnectionOptions): Promise; +} + +export interface NatsConnection { + info?: ServerInfo; + closed(): Promise; + close(): Promise; + publish(subject: string, data?: Uint8Array, options?: PublishOptions): void; + subscribe(subject: string, opts?: SubscriptionOptions): Subscription; + request( + subject: string, + data?: Uint8Array, + opts?: RequestOptions, + ): Promise; + flush(): Promise; + drain(): Promise; + isClosed(): boolean; + isDraining(): boolean; + getServer(): string; + status(): AsyncIterable; + stats(): Stats; + + jetstreamManager(opts?: JetStreamOptions): Promise; + jetstream(opts?: JetStreamOptions): JetStreamClient; +} + +export interface ConnectionOptions { + authenticator?: Authenticator; + debug?: boolean; + maxPingOut?: number; + maxReconnectAttempts?: number; + name?: string; + noEcho?: boolean; + noRandomize?: boolean; + pass?: string; + pedantic?: boolean; + pingInterval?: number; + port?: number; + reconnect?: boolean; + reconnectDelayHandler?: () => number; + reconnectJitter?: number; + reconnectJitterTLS?: number; + reconnectTimeWait?: number; + servers?: Array | string; + timeout?: number; + tls?: TlsOptions; + token?: string; + user?: string; + verbose?: boolean; + waitOnFirstConnect?: boolean; + ignoreClusterUpdates?: boolean; + inboxPrefix?: string; +} + +// these may not be supported on all environments +export interface TlsOptions { + certFile?: string; + cert?: string; + caFile?: string; + ca?: string; + keyFile?: string; + key?: string; +} + +export interface Msg { + subject: string; + sid: number; + reply?: string; + data: Uint8Array; + headers?: MsgHdrs; + + respond(data?: Uint8Array, opts?: PublishOptions): boolean; +} + +export interface SubOpts { + queue?: string; + max?: number; + timeout?: number; + callback?: (err: NatsError | null, msg: T) => void; +} + +export type SubscriptionOptions = SubOpts; + +export interface Base { + subject: string; + callback: (error: NatsError | null, msg: Msg) => void; + received: number; + timeout?: number | null; + max?: number | undefined; + draining: boolean; +} + +export interface ServerInfo { + "auth_required"?: boolean; + "client_id": number; + "client_ip"?: string; + "connect_urls"?: string[]; + "git_commit"?: string; + go: string; + headers?: boolean; + host: string; + jetstream?: boolean; + ldm?: boolean; + "max_payload": number; + nonce?: string; + port: number; + proto: number; + "server_id": string; + "server_name": string; + "tls_available"?: boolean; + "tls_required"?: boolean; + "tls_verify"?: boolean; + version: string; +} + +export interface Server { + hostname: string; + port: number; + listen: string; + src: string; + tlsName: string; +} + +export interface ServersChanged { + readonly added: string[]; + readonly deleted: string[]; +} + +export interface Sub extends AsyncIterable { + unsubscribe(max?: number): void; + drain(): Promise; + isDraining(): boolean; + isClosed(): boolean; + callback(err: NatsError | null, msg: Msg): void; + getSubject(): string; + getReceived(): number; + getProcessed(): number; + getPending(): number; + getID(): number; + getMax(): number | undefined; +} + +export type Subscription = Sub; + +export interface RequestOptions { + timeout: number; + headers?: MsgHdrs; + noMux?: boolean; + reply?: string; +} + +export interface PublishOptions { + reply?: string; + headers?: MsgHdrs; +} + +export interface Stats { + inBytes: number; + outBytes: number; + inMsgs: number; + outMsgs: number; +} + +export interface URLParseFn { + (u: string): string; +} + +// JetStream +export interface JetStreamOptions { + apiPrefix?: string; + timeout?: number; +} + +export interface JetStreamManager { + consumers: ConsumerAPI; + streams: StreamAPI; + getAccountInfo(): Promise; + advisories(): AsyncIterable; +} + +export interface PullOptions { + batch: number; + "no_wait": boolean; + expires: number; +} + +export interface PubAck { + stream: string; + seq: number; + duplicate: boolean; + + ack(): void; +} + +export interface JetStreamPublishOptions { + msgID: string; + timeout: number; + ackWait: Nanos; + expect: Partial<{ + lastMsgID: string; + streamName: string; + lastSequence: number; + }>; +} + +export interface ConsumerInfoable { + consumerInfo(): Promise; +} + +export interface Closed { + closed: Promise; +} + +export type JetStreamSubscription = + & Sub + & Destroyable + & Closed + & ConsumerInfoable; + +export type JetStreamSubscriptionOptions = TypedSubscriptionOptions; + +export interface Pullable { + pull(opts?: Partial): void; +} + +export interface Destroyable { + destroy(): Promise; +} + +export type JetStreamPullSubscription = JetStreamSubscription & Pullable; + +export type JsMsgCallback = (err: NatsError | null, msg: JsMsg | null) => void; + +// FIXME: pulls must limit to maxAcksInFlight +export interface JetStreamClient { + publish( + subj: string, + data?: Uint8Array, + options?: Partial, + ): Promise; + pull(stream: string, durable: string): Promise; + fetch( + stream: string, + durable: string, + opts?: Partial, + ): QueuedIterator; + pullSubscribe( + subject: string, + opts: ConsumerOptsBuilder | Partial, + ): Promise; + subscribe( + subject: string, + opts: ConsumerOptsBuilder | Partial, + ): Promise; +} + +export interface ConsumerOpts { + config: Partial; + mack: boolean; + subQueue: string; + stream: string; + callbackFn?: JsMsgCallback; + name?: string; + + // standard + max?: number; + debug?: boolean; +} + +export interface ConsumerOptsBuilder { + deliverTo(subject: string): void; + manualAck(): void; + durable(name: string): void; + deliverAll(): void; + deliverLast(): void; + deliverNew(): void; + startSequence(seq: number): void; + startTime(time: Date | Nanos): void; + ackNone(): void; + ackAll(): void; + ackExplicit(): void; + maxDeliver(max: number): void; + maxAckPending(max: number): void; + // FIXME: pullMaxWaiting + maxWaiting(max: number): void; + maxMessages(max: number): void; + callback(fn: JsMsgCallback): void; +} + +export interface Lister { + next(): Promise; +} + +export interface ConsumerAPI { + info(stream: string, consumer: string): Promise; + add(stream: string, cfg: Partial): Promise; + delete(stream: string, consumer: string): Promise; + list(stream: string): Lister; +} + +export interface StreamAPI { + info(stream: string): Promise; + add(cfg: Partial): Promise; + update(cfg: StreamConfig): Promise; + purge(stream: string): Promise; + delete(stream: string): Promise; + list(): Lister; + deleteMessage(stream: string, seq: number): Promise; + getMessage(stream: string, seq: number): Promise; + find(subject: string): Promise; +} + +export interface JsMsg { + redelivered: boolean; + info: DeliveryInfo; + seq: number; + headers: MsgHdrs | undefined; + data: Uint8Array; + subject: string; + sid: number; + + ack(): void; + nak(): void; + working(): void; + // next(subj?: string): void; + term(): void; + ackAck(): Promise; +} + +export interface DeliveryInfo { + stream: string; + consumer: string; + redeliveryCount: number; + streamSequence: number; + deliverySequence: number; + timestampNanos: number; + pending: number; + redelivered: boolean; +} + +export interface StoredMsg { + subject: string; + seq: number; + header: MsgHdrs; + data: Uint8Array; + time: Date; +} + +export interface Advisory { + kind: AdvisoryKind; + data: unknown; +} + +export enum AdvisoryKind { + API = "api_audit", + StreamAction = "stream_action", + ConsumerAction = "consumer_action", + SnapshotCreate = "snapshot_create", + SnapshotComplete = "snapshot_complete", + RestoreCreate = "restore_create", + RestoreComplete = "restore_complete", + MaxDeliver = "max_deliver", + Terminated = "terminated", + Ack = "consumer_ack", + StreamLeaderElected = "stream_leader_elected", + StreamQuorumLost = "stream_quorum_lost", + ConsumerLeaderElected = "consumer_leader_elected", + ConsumerQuorumLost = "consumer_quorum_lost", +} + +// JetStream Server Types + +export type Nanos = number; + +export interface ApiError { + code: number; + description: string; +} + +export interface ApiResponse { + type: string; + error?: ApiError; +} + +export interface ApiPaged { + total: number; + offset: number; + limit: number; +} + +export interface ApiPagedRequest { + offset: number; +} + +export interface StreamInfo { + config: StreamConfig; + created: number; // in ns + state: StreamState; + cluster?: ClusterInfo; + mirror?: StreamSourceInfo; + sources?: StreamSourceInfo[]; +} + +export interface StreamConfig { + name: string; + subjects?: string[]; + retention: RetentionPolicy; + "max_consumers": number; + "max_msgs": number; + "max_bytes": number; + discard?: DiscardPolicy; + "max_age": number; + "max_msg_size"?: number; + storage: StorageType; + "num_replicas": number; + "no_ack"?: boolean; + "template_owner"?: string; + "duplicate_window"?: number; // duration + placement?: Placement; + mirror?: StreamSource; // same as a source + sources?: StreamSource[]; +} + +export interface StreamSource { + name: string; + "opt_start_seq": number; + "opt_start_time": string; + "filter_subject": string; +} + +export interface Placement { + cluster: string; + tags: string[]; +} + +export enum RetentionPolicy { + Limits = "limits", + Interest = "interest", + Workqueue = "workqueue", +} + +export enum DiscardPolicy { + Old = "old", + New = "new", +} + +export enum StorageType { + File = "file", + Memory = "memory", +} + +export enum DeliverPolicy { + All = "all", + Last = "last", + New = "new", + StartSequence = "by_start_sequence", + StartTime = "by_start_time", +} + +export enum AckPolicy { + None = "none", + All = "all", + Explicit = "explicit", + NotSet = "", +} + +export enum ReplayPolicy { + Instant = "instant", + Original = "original", +} + +export interface StreamState { + messages: number; + bytes: number; + "first_seq": number; + "first_ts": number; + "last_seq": number; + "last_ts": string; + deleted: number[]; + lost: LostStreamData; + "consumer_count": number; +} + +export interface LostStreamData { + msgs: number; + bytes: number; +} + +export interface ClusterInfo { + name?: string; + leader?: string; + replicas?: PeerInfo[]; +} + +export interface PeerInfo { + name: string; + current: boolean; + offline: boolean; + active: Nanos; + lag: number; +} + +export interface StreamSourceInfo { + name: string; + lag: number; + active: Nanos; + error?: ApiError; +} + +export interface PurgeResponse extends Success { + purged: number; +} + +export interface CreateConsumerRequest { + "stream_name": string; + config: Partial; +} + +export interface StreamMsgResponse extends ApiResponse { + message: { + subject: string; + seq: number; + data: string; + hdrs: string; + time: string; + }; +} + +export interface SequencePair { + "consumer_seq": number; + "stream_seq": number; +} + +export interface ConsumerInfo { + "stream_name": string; + name: string; + created: number; + config: ConsumerConfig; + delivered: SequencePair; + "ack_floor": SequencePair; + "num_ack_pending": number; + "num_redelivered": number; + "num_waiting": number; + "num_pending": number; + cluster?: ClusterInfo; +} + +export interface ConsumerListResponse extends ApiResponse, ApiPaged { + consumers: ConsumerInfo[]; +} + +export interface StreamListResponse extends ApiResponse, ApiPaged { + streams: StreamInfo[]; +} + +export interface Success { + success: boolean; +} + +export type SuccessResponse = ApiResponse & Success; + +export interface MsgRequest { + seq: number; +} + +export interface MsgDeleteRequest extends MsgRequest { + "no_erase"?: boolean; +} + +export interface JetStreamAccountStats { + memory: number; + storage: number; + streams: number; + consumers: number; + api: JetStreamApiStats; + limits: AccountLimits; +} + +export interface JetStreamApiStats { + total: number; + errors: number; +} + +export interface AccountInfoResponse + extends ApiResponse, JetStreamAccountStats {} + +export interface AccountLimits { + "max_memory": number; + "max_storage": number; + "max_streams": number; + "max_consumers": number; +} + +export interface ConsumerConfig { + name: string; + "durable_name"?: string; + "deliver_subject"?: string; + "deliver_policy": DeliverPolicy; + "opt_start_seq"?: number; + "opt_start_time"?: string; + "ack_policy": AckPolicy; + "ack_wait"?: number; + "max_deliver"?: number; + "filter_subject"?: string; + "replay_policy": ReplayPolicy; + "rate_limit_bps"?: number; + "sample_freq"?: string; + "max_waiting"?: number; + "max_ack_pending"?: number; +} + +export interface Consumer { + "stream_name": string; + config: ConsumerConfig; +} + +export interface StreamNames { + streams: string[]; +} + +export interface StreamNameBySubject { + subject: string; +} + +export interface NextRequest { + expires: number; + batch: number; + "no_wait": boolean; +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/52f14796472d5741184a5202d6b99b054075b20d.ts b/crates/swc_bundler/tests/.cache/untrusted/52f14796472d5741184a5202d6b99b054075b20d.ts new file mode 100644 index 000000000000..ea51dec8dde7 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/52f14796472d5741184a5202d6b99b054075b20d.ts @@ -0,0 +1,137 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/nuid.ts + + +/* +* Copyright 2016-2021 The NATS Authors +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +"use strict"; + +const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +const base = 36; +const preLen = 12; +const seqLen = 10; +const maxSeq = 3656158440062976; // base^seqLen == 36^10 +const minInc = 33; +const maxInc = 333; +const totalLen = preLen + seqLen; + +const cryptoObj = initCrypto(); + +function initCrypto() { + let cryptoObj = null; + if (typeof globalThis !== "undefined") { + if ("crypto" in globalThis && globalThis.crypto.getRandomValues) { + cryptoObj = globalThis.crypto; + } + } + if (!cryptoObj) { + // shim it + cryptoObj = { + getRandomValues: function (array: Uint8Array) { + for (let i = 0; i < array.length; i++) { + array[i] = Math.floor(Math.random() * 255); + } + }, + }; + } + return cryptoObj; +} + +/** + * Create and initialize a nuid. + * + * @api private + */ +export class Nuid { + buf: Uint8Array; + seq!: number; + inc!: number; + + constructor() { + this.buf = new Uint8Array(totalLen); + this.init(); + } + + /** + * Initializes a nuid with a crypto random prefix, + * and pseudo-random sequence and increment. + * + * @api private + */ + private init() { + this.setPre(); + this.initSeqAndInc(); + this.fillSeq(); + } + + /** + * Initializes the pseudo randmon sequence number and the increment range. + * + * @api private + */ + private initSeqAndInc() { + this.seq = Math.floor(Math.random() * maxSeq); + this.inc = Math.floor(Math.random() * (maxInc - minInc) + minInc); + } + + /** + * Sets the prefix from crypto random bytes. Converts to base36. + * + * @api private + */ + private setPre() { + const cbuf = new Uint8Array(preLen); + cryptoObj.getRandomValues(cbuf); + for (let i = 0; i < preLen; i++) { + const di = cbuf[i] % base; + this.buf[i] = digits.charCodeAt(di); + } + } + + /** + * Fills the sequence part of the nuid as base36 from this.seq. + * + * @api private + */ + private fillSeq() { + let n = this.seq; + for (let i = totalLen - 1; i >= preLen; i--) { + this.buf[i] = digits.charCodeAt(n % base); + n = Math.floor(n / base); + } + } + + /** + * Returns the next nuid. + * + * @api private + */ + next(): string { + this.seq += this.inc; + if (this.seq > maxSeq) { + this.setPre(); + this.initSeqAndInc(); + } + this.fillSeq(); + // @ts-ignore - Uint8Arrays can be an argument + return String.fromCharCode.apply(String, this.buf); + } + + reset() { + this.init(); + } +} + +export const nuid = new Nuid(); diff --git a/crates/swc_bundler/tests/.cache/untrusted/56c930bf5ae99dd1abeba0cb78324a33564d6c8c.ts b/crates/swc_bundler/tests/.cache/untrusted/56c930bf5ae99dd1abeba0cb78324a33564d6c8c.ts new file mode 100644 index 000000000000..efccd03bdd53 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/56c930bf5ae99dd1abeba0cb78324a33564d6c8c.ts @@ -0,0 +1,722 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/protocol.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + ConnectionOptions, + DebugEvents, + DEFAULT_MAX_PING_OUT, + DEFAULT_PING_INTERVAL, + DEFAULT_RECONNECT_TIME_WAIT, + Empty, + Events, + PublishOptions, + ServerInfo, + Status, + Subscription, +} from "./types.ts"; +import { newTransport, Transport } from "./transport.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { + CR_LF, + CRLF, + Deferred, + deferred, + delay, + extend, + timeout, +} from "./util.ts"; +import { nuid } from "./nuid.ts"; +import { DataBuffer } from "./databuffer.ts"; +import { ServerImpl, Servers } from "./servers.ts"; +import { + Dispatcher, + QueuedIterator, + QueuedIteratorImpl, +} from "./queued_iterator.ts"; +import type { MsgHdrs, MsgHdrsImpl } from "./headers.ts"; +import { SubscriptionImpl } from "./subscription.ts"; +import { Subscriptions } from "./subscriptions.ts"; +import { MuxSubscription } from "./muxsubscription.ts"; +import type { Request } from "./request.ts"; +import { Heartbeat, PH } from "./heartbeats.ts"; +import { Kind, MsgArg, Parser, ParserEvent } from "./parser.ts"; +import { MsgImpl } from "./msg.ts"; +import { fastDecoder, fastEncoder } from "./encoders.ts"; + +const FLUSH_THRESHOLD = 1024 * 32; + +export const INFO = /^INFO\s+([^\r\n]+)\r\n/i; + +export function createInbox(prefix = ""): string { + prefix = prefix || "_INBOX"; + if (typeof prefix !== "string") { + throw (new Error("prefix must be a string")); + } + return `${prefix}.${nuid.next()}`; +} + +const PONG_CMD = fastEncoder("PONG\r\n"); +const PING_CMD = fastEncoder("PING\r\n"); + +export class Connect { + echo?: boolean; + no_responders?: boolean; + protocol: number; + verbose?: boolean; + pedantic?: boolean; + jwt?: string; + nkey?: string; + sig?: string; + user?: string; + pass?: string; + auth_token?: string; + tls_required?: boolean; + name?: string; + lang: string; + version: string; + headers?: boolean; + + constructor( + transport: { version: string; lang: string }, + opts: ConnectionOptions, + nonce?: string, + ) { + this.protocol = 1; + this.version = transport.version; + this.lang = transport.lang; + this.echo = opts.noEcho ? false : undefined; + this.verbose = opts.verbose; + this.pedantic = opts.pedantic; + this.tls_required = opts.tls ? true : undefined; + this.name = opts.name; + + const creds = + (opts && opts.authenticator ? opts.authenticator(nonce) : {}) || {}; + extend(this, creds); + } +} + +export interface Publisher { + publish( + subject: string, + data: Uint8Array, + options?: { reply?: string; headers?: MsgHdrs }, + ): void; +} + +export class ProtocolHandler implements Dispatcher { + connected: boolean; + connectedOnce: boolean; + infoReceived: boolean; + info?: ServerInfo; + muxSubscriptions: MuxSubscription; + options: ConnectionOptions; + outbound: DataBuffer; + pongs: Array>; + subscriptions: Subscriptions; + transport!: Transport; + noMorePublishing: boolean; + connectError?: (err?: Error) => void; + publisher: Publisher; + _closed: boolean; + closed: Deferred; + listeners: QueuedIterator[]; + heartbeats: Heartbeat; + parser: Parser; + outMsgs: number; + inMsgs: number; + outBytes: number; + inBytes: number; + pendingLimit: number; + lastError?: NatsError; + abortReconnect: boolean; + + servers: Servers; + server!: ServerImpl; + + constructor(options: ConnectionOptions, publisher: Publisher) { + this._closed = false; + this.connected = false; + this.connectedOnce = false; + this.infoReceived = false; + this.noMorePublishing = false; + this.abortReconnect = false; + this.listeners = []; + this.pendingLimit = FLUSH_THRESHOLD; + this.outMsgs = 0; + this.inMsgs = 0; + this.outBytes = 0; + this.inBytes = 0; + this.options = options; + this.publisher = publisher; + this.subscriptions = new Subscriptions(); + this.muxSubscriptions = new MuxSubscription(); + this.outbound = new DataBuffer(); + this.pongs = []; + //@ts-ignore: options.pendingLimit is hidden + this.pendingLimit = options.pendingLimit || this.pendingLimit; + this.servers = new Servers( + !options.noRandomize, + //@ts-ignore: servers should be a list + options.servers, + ); + this.closed = deferred(); + this.parser = new Parser(this); + + this.heartbeats = new Heartbeat( + this as PH, + this.options.pingInterval || DEFAULT_PING_INTERVAL, + this.options.maxPingOut || DEFAULT_MAX_PING_OUT, + ); + } + + resetOutbound(): void { + this.outbound.reset(); + const pongs = this.pongs; + this.pongs = []; + // reject the pongs + pongs.forEach((p) => { + p.reject(NatsError.errorForCode(ErrorCode.Disconnect)); + }); + this.parser = new Parser(this); + this.infoReceived = false; + } + + dispatchStatus(status: Status): void { + this.listeners.forEach((q) => { + q.push(status); + }); + } + + status(): AsyncIterable { + const iter = new QueuedIteratorImpl(); + this.listeners.push(iter); + return iter; + } + + private prepare(): Deferred { + this.info = undefined; + this.resetOutbound(); + + const pong = deferred(); + this.pongs.unshift(pong); + + this.connectError = (err?: Error) => { + pong.reject(err); + }; + + this.transport = newTransport(); + this.transport.closed() + .then(async (err?) => { + this.connected = false; + if (!this.isClosed()) { + await this.disconnected(this.transport.closeError); + return; + } + }); + + return pong; + } + + public disconnect(): void { + this.dispatchStatus({ type: DebugEvents.StaleConnection, data: "" }); + this.transport.disconnect(); + } + + async disconnected(err?: Error): Promise { + this.dispatchStatus( + { + type: Events.Disconnect, + data: this.servers.getCurrentServer().toString(), + }, + ); + if (this.options.reconnect) { + await this.dialLoop() + .then(() => { + this.dispatchStatus( + { + type: Events.Reconnect, + data: this.servers.getCurrentServer().toString(), + }, + ); + }) + .catch((err) => { + this._close(err); + }); + } else { + await this._close(); + } + } + + async dial(srv: ServerImpl): Promise { + const pong = this.prepare(); + let timer; + try { + timer = timeout(this.options.timeout || 20000); + const cp = this.transport.connect(srv, this.options); + await Promise.race([cp, timer]); + (async () => { + try { + for await (const b of this.transport) { + this.parser.parse(b); + } + } catch (err) { + console.log("reader closed", err); + } + })().then(); + } catch (err) { + pong.reject(err); + } + + try { + await Promise.race([timer, pong]); + if (timer) { + timer.cancel(); + } + this.connected = true; + this.connectError = undefined; + this.sendSubscriptions(); + this.connectedOnce = true; + this.server.didConnect = true; + this.server.reconnects = 0; + this.flushPending(); + this.heartbeats.start(); + } catch (err) { + if (timer) { + timer.cancel(); + } + await this.transport.close(err); + throw err; + } + } + + async dialLoop(): Promise { + let lastError: Error | undefined; + while (true) { + const wait = this.options.reconnectDelayHandler + ? this.options.reconnectDelayHandler() + : DEFAULT_RECONNECT_TIME_WAIT; + let maxWait = wait; + const srv = this.selectServer(); + if (!srv || this.abortReconnect) { + throw lastError || NatsError.errorForCode(ErrorCode.ConnectionRefused); + } + const now = Date.now(); + if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) { + srv.lastConnect = Date.now(); + try { + this.dispatchStatus( + { type: DebugEvents.Reconnecting, data: srv.toString() }, + ); + await this.dial(srv); + break; + } catch (err) { + lastError = err; + if (!this.connectedOnce) { + if (this.options.waitOnFirstConnect) { + continue; + } + this.servers.removeCurrentServer(); + } + srv.reconnects++; + const mra = this.options.maxReconnectAttempts || 0; + if (mra !== -1 && srv.reconnects >= mra) { + this.servers.removeCurrentServer(); + } + } + } else { + maxWait = Math.min(maxWait, srv.lastConnect + wait - now); + await delay(maxWait); + } + } + } + + public static async connect( + options: ConnectionOptions, + publisher: Publisher, + ): Promise { + const h = new ProtocolHandler(options, publisher); + await h.dialLoop(); + return h; + } + + static toError(s: string) { + const t = s ? s.toLowerCase() : ""; + if (t.indexOf("permissions violation") !== -1) { + return new NatsError(s, ErrorCode.PermissionsViolation); + } else if (t.indexOf("authorization violation") !== -1) { + return new NatsError(s, ErrorCode.AuthorizationViolation); + } else if (t.indexOf("user authentication expired") !== -1) { + return new NatsError(s, ErrorCode.AuthenticationExpired); + } else { + return new NatsError(s, ErrorCode.ProtocolError); + } + } + + processMsg(msg: MsgArg, data: Uint8Array) { + this.inMsgs++; + this.inBytes += data.length; + if (!this.subscriptions.sidCounter) { + return; + } + + const sub = this.subscriptions.get(msg.sid) as SubscriptionImpl; + if (!sub) { + return; + } + sub.received += 1; + + if (sub.callback) { + sub.callback(null, new MsgImpl(msg, data, this)); + } + + if (sub.max !== undefined && sub.received >= sub.max) { + sub.unsubscribe(); + } + } + + async processError(m: Uint8Array) { + const s = fastDecoder(m); + const err = ProtocolHandler.toError(s); + const handled = this.subscriptions.handleError(err); + if (!handled) { + this.dispatchStatus({ type: Events.Error, data: err.code }); + } + await this.handleError(err); + } + + async handleError(err: NatsError) { + if (err.isAuthError()) { + this.handleAuthError(err); + } + if (err.isPermissionError() || err.isProtocolError()) { + await this._close(err); + } + this.lastError = err; + } + + handleAuthError(err: NatsError) { + if (this.lastError && err.code === this.lastError.code) { + this.abortReconnect = true; + } + if (this.connectError) { + this.connectError(err); + } else { + this.disconnect(); + } + } + + processPing() { + this.transport.send(PONG_CMD); + } + + processPong() { + const cb = this.pongs.shift(); + if (cb) { + cb.resolve(); + } + } + + processInfo(m: Uint8Array) { + const info = JSON.parse(fastDecoder(m)); + this.info = info; + const updates = this.options && this.options.ignoreClusterUpdates + ? undefined + : this.servers.update(info); + if (!this.infoReceived) { + this.infoReceived = true; + if (this.transport.isEncrypted()) { + this.servers.updateTLSName(); + } + // send connect + const { version, lang } = this.transport; + try { + const c = new Connect( + { version, lang }, + this.options, + info.nonce, + ); + + if (info.headers) { + c.headers = true; + c.no_responders = true; + } + const cs = JSON.stringify(c); + this.transport.send( + fastEncoder(`CONNECT ${cs}${CR_LF}`), + ); + this.transport.send(PING_CMD); + } catch (err) { + this._close( + NatsError.errorForCode(ErrorCode.BadAuthentication, err), + ); + } + } + if (updates) { + this.dispatchStatus({ type: Events.Update, data: updates }); + } + const ldm = info.ldm !== undefined ? info.ldm : false; + if (ldm) { + this.dispatchStatus( + { + type: Events.LDM, + data: this.servers.getCurrentServer().toString(), + }, + ); + } + } + + push(e: ParserEvent): void { + switch (e.kind) { + case Kind.MSG: { + const { msg, data } = e; + this.processMsg(msg!, data!); + break; + } + case Kind.OK: + break; + case Kind.ERR: + this.processError(e.data!); + break; + case Kind.PING: + this.processPing(); + break; + case Kind.PONG: + this.processPong(); + break; + case Kind.INFO: + this.processInfo(e.data!); + break; + } + } + + sendCommand(cmd: (string | Uint8Array), ...payloads: Uint8Array[]) { + const len = this.outbound.length(); + let buf: Uint8Array; + if (typeof cmd === "string") { + buf = fastEncoder(cmd); + } else { + buf = cmd as Uint8Array; + } + this.outbound.fill(buf, ...payloads); + + if (len === 0) { + setTimeout(() => { + this.flushPending(); + }); + } else if (this.outbound.size() >= this.pendingLimit) { + this.flushPending(); + } + } + + publish( + subject: string, + data: Uint8Array, + options?: PublishOptions, + ) { + if (this.isClosed()) { + throw NatsError.errorForCode(ErrorCode.ConnectionClosed); + } + if (this.noMorePublishing) { + throw NatsError.errorForCode(ErrorCode.ConnectionDraining); + } + + let len = data.length; + options = options || {}; + options.reply = options.reply || ""; + + let headers = Empty; + let hlen = 0; + if (options.headers) { + if (this.info && !this.info.headers) { + throw new NatsError("headers", ErrorCode.ServerOptionNotAvailable); + } + const hdrs = options.headers as MsgHdrsImpl; + headers = hdrs.encode(); + hlen = headers.length; + len = data.length + hlen; + } + + if (this.info && len > this.info.max_payload) { + throw NatsError.errorForCode((ErrorCode.MaxPayloadExceeded)); + } + this.outBytes += len; + this.outMsgs++; + + let proto: string; + if (options.headers) { + if (options.reply) { + proto = `HPUB ${subject} ${options.reply} ${hlen} ${len}${CR_LF}`; + } else { + proto = `HPUB ${subject} ${hlen} ${len}\r\n`; + } + this.sendCommand(proto, headers, data, CRLF); + } else { + if (options.reply) { + proto = `PUB ${subject} ${options.reply} ${len}\r\n`; + } else { + proto = `PUB ${subject} ${len}\r\n`; + } + this.sendCommand(proto, data, CRLF); + } + } + + request(r: Request): Request { + this.initMux(); + this.muxSubscriptions.add(r); + return r; + } + + subscribe(s: SubscriptionImpl): Subscription { + this.subscriptions.add(s); + if (s.queue) { + this.sendCommand(`SUB ${s.subject} ${s.queue} ${s.sid}\r\n`); + } else { + this.sendCommand(`SUB ${s.subject} ${s.sid}\r\n`); + } + if (s.max) { + this.unsubscribe(s, s.max); + } + return s; + } + + unsubscribe(s: SubscriptionImpl, max?: number) { + this.unsub(s, max); + if (s.max === undefined || s.received >= s.max) { + this.subscriptions.cancel(s); + } + } + + unsub(s: SubscriptionImpl, max?: number) { + if (!s || this.isClosed()) { + return; + } + if (max) { + this.sendCommand(`UNSUB ${s.sid} ${max}${CR_LF}`); + } else { + this.sendCommand(`UNSUB ${s.sid}${CR_LF}`); + } + s.max = max; + } + + flush(p?: Deferred): Promise { + if (!p) { + p = deferred(); + } + this.pongs.push(p); + this.sendCommand(PING_CMD); + return p; + } + + sendSubscriptions() { + const cmds: string[] = []; + this.subscriptions.all().forEach((s) => { + const sub = s as SubscriptionImpl; + if (sub.queue) { + cmds.push(`SUB ${sub.subject} ${sub.queue} ${sub.sid}${CR_LF}`); + } else { + cmds.push(`SUB ${sub.subject} ${sub.sid}${CR_LF}`); + } + }); + if (cmds.length) { + this.transport.send(fastEncoder(cmds.join(""))); + } + } + + private async _close(err?: Error): Promise { + if (this._closed) { + return; + } + this.heartbeats.cancel(); + if (this.connectError) { + this.connectError(err); + this.connectError = undefined; + } + this.muxSubscriptions.close(); + this.subscriptions.close(); + this.listeners.forEach((l) => { + l.stop(); + }); + this._closed = true; + await this.transport.close(err); + await this.closed.resolve(err); + } + + close(): Promise { + return this._close(); + } + + isClosed(): boolean { + return this._closed; + } + + drain(): Promise { + const subs = this.subscriptions.all(); + const promises: Promise[] = []; + subs.forEach((sub: Subscription) => { + promises.push(sub.drain()); + }); + return Promise.all(promises) + .then(async () => { + this.noMorePublishing = true; + await this.flush(); + return this.close(); + }) + .catch(() => { + // cannot happen + }); + } + + private flushPending() { + if (!this.infoReceived || !this.connected) { + return; + } + + if (this.outbound.size()) { + const d = this.outbound.drain(); + this.transport.send(d); + } + } + + private initMux(): void { + const mux = this.subscriptions.getMux(); + if (!mux) { + const inbox = this.muxSubscriptions.init( + this.options.inboxPrefix, + ); + // dot is already part of mux + const sub = new SubscriptionImpl(this, `${inbox}*`); + sub.callback = this.muxSubscriptions.dispatcher(); + this.subscriptions.setMux(sub); + this.subscribe(sub); + } + } + + private selectServer(): ServerImpl | undefined { + const server = this.servers.selectServer(); + if (server === undefined) { + return undefined; + } + // Place in client context. + this.server = server; + return this.server; + } + + getServer(): ServerImpl | undefined { + return this.server; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/5c2515b2dcd55e2b4e848ea766c7a314b34efcf3.ts b/crates/swc_bundler/tests/.cache/untrusted/5c2515b2dcd55e2b4e848ea766c7a314b34efcf3.ts new file mode 100644 index 000000000000..4b7071945292 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/5c2515b2dcd55e2b4e848ea766c7a314b34efcf3.ts @@ -0,0 +1,87 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/mod.ts + + +export { + Bench, + createInbox, + credsAuthenticator, + DebugEvents, + Empty, + ErrorCode, + Events, + headers, + JSONCodec, + jwtAuthenticator, + NatsError, + nkeyAuthenticator, + Nuid, + StringCodec, +} from "./internal_mod.ts"; + +export type { + Authenticator, + Codec, + ConnectionOptions, + Msg, + MsgHdrs, + NatsConnection, + PublishOptions, + RequestOptions, + ServersChanged, + Status, + Sub, + SubOpts, + Subscription, + SubscriptionOptions, +} from "./internal_mod.ts"; + +export { + AckPolicy, + AdvisoryKind, + consumerOpts, + DeliverPolicy, + DiscardPolicy, + millis, + nanos, + ReplayPolicy, + RetentionPolicy, + StorageType, + toJsMsg, +} from "./internal_mod.ts"; + +export type { + AccountLimits, + ClusterInfo, + Consumer, + ConsumerConfig, + ConsumerOpts, + ConsumerOptsBuilder, + DeliveryInfo, + JetStreamAccountStats, + JetStreamApiStats, + JetStreamClient, + JetStreamManager, + JetStreamOptions, + JetStreamPublishOptions, + JetStreamPullSubscription, + JetStreamSubscription, + JetStreamSubscriptionOptions, + JsMsg, + JsMsgCallback, + Lister, + LostStreamData, + MsgDeleteRequest, + MsgRequest, + Nanos, + PeerInfo, + Placement, + PullOptions, + SequencePair, + StoredMsg, + StreamConfig, + StreamInfo, + StreamNames, + StreamSource, + StreamSourceInfo, + StreamState, +} from "./internal_mod.ts"; diff --git a/crates/swc_bundler/tests/.cache/untrusted/5ee9cd5faaa0d5d7ccbe18e8bcd4b51e29f50478.ts b/crates/swc_bundler/tests/.cache/untrusted/5ee9cd5faaa0d5d7ccbe18e8bcd4b51e29f50478.ts new file mode 100644 index 000000000000..29c3180e2d9f --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/5ee9cd5faaa0d5d7ccbe18e8bcd4b51e29f50478.ts @@ -0,0 +1,69 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsm.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AccountInfoResponse, + Advisory, + AdvisoryKind, + ApiResponse, + ConsumerAPI, + JetStreamAccountStats, + JetStreamManager, + JetStreamOptions, + NatsConnection, + StreamAPI, +} from "./types.ts"; + +import { BaseApiClient } from "./jsbaseclient_api.ts"; +import { StreamAPIImpl } from "./jsstream_api.ts"; +import { ConsumerAPIImpl } from "./jsconsumer_api.ts"; +import { QueuedIteratorImpl } from "./queued_iterator.ts"; + +export class JetStreamManagerImpl extends BaseApiClient + implements JetStreamManager { + streams: StreamAPI; + consumers: ConsumerAPI; + constructor(nc: NatsConnection, opts?: JetStreamOptions) { + super(nc, opts); + this.streams = new StreamAPIImpl(nc, opts); + this.consumers = new ConsumerAPIImpl(nc, opts); + } + + async getAccountInfo(): Promise { + const r = await this._request(`${this.prefix}.INFO`); + return r as AccountInfoResponse; + } + + advisories(): AsyncIterable { + const iter = new QueuedIteratorImpl(); + this.nc.subscribe(`$JS.EVENT.ADVISORY.>`, { + callback: (err, msg) => { + try { + const d = this.parseJsResponse(msg) as ApiResponse; + const chunks = d.type.split("."); + const kind = chunks[chunks.length - 1]; + iter.push({ kind: kind as AdvisoryKind, data: d }); + } catch (err) { + iter.stop(err); + } + }, + }); + + return iter; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/67eb9fb39d33a96067d7a52d4ee766934d85123f.ts b/crates/swc_bundler/tests/.cache/untrusted/67eb9fb39d33a96067d7a52d4ee766934d85123f.ts new file mode 100644 index 000000000000..a68cec509b71 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/67eb9fb39d33a96067d7a52d4ee766934d85123f.ts @@ -0,0 +1,232 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/headers.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Heavily inspired by Golang's https://golang.org/src/net/http/header.go + +import { ErrorCode, NatsError } from "./error.ts"; +import { TD, TE } from "./encoders.ts"; + +export interface MsgHdrs extends Iterable<[string, string[]]> { + hasError: boolean; + status: string; + code: number; + get(k: string): string; + set(k: string, v: string): void; + append(k: string, v: string): void; + has(k: string): boolean; + values(k: string): string[]; + delete(k: string): void; +} + +export function headers(): MsgHdrs { + return new MsgHdrsImpl(); +} + +const HEADER = "NATS/1.0"; + +export class MsgHdrsImpl implements MsgHdrs { + code: number; + headers: Map; + description: string; + + constructor() { + this.code = 0; + this.headers = new Map(); + this.description = ""; + } + + [Symbol.iterator]() { + return this.headers.entries(); + } + + size(): number { + let count = 0; + for (const [_, v] of this.headers.entries()) { + count += v.length; + } + return count; + } + + equals(mh: MsgHdrsImpl) { + if ( + mh && this.headers.size === mh.headers.size && + this.code === mh.code + ) { + for (const [k, v] of this.headers) { + const a = mh.values(k); + if (v.length !== a.length) { + return false; + } + const vv = [...v].sort(); + const aa = [...a].sort(); + for (let i = 0; i < vv.length; i++) { + if (vv[i] !== aa[i]) { + return false; + } + } + return true; + } + } + return false; + } + + static decode(a: Uint8Array): MsgHdrsImpl { + const mh = new MsgHdrsImpl(); + const s = TD.decode(a); + const lines = s.split("\r\n"); + const h = lines[0]; + if (h !== HEADER) { + let str = h.replace(HEADER, ""); + mh.code = parseInt(str, 10); + const scode = mh.code.toString(); + mh.set("Status", scode); + str = str.replace(scode, ""); + mh.description = str.trim(); + if (mh.description) { + mh.set("Description", mh.description); + } + } else { + lines.slice(1).map((s) => { + if (s) { + const idx = s.indexOf(": "); + const k = s.slice(0, idx); + const v = s.slice(idx + 2); + mh.append(k, v); + } + }); + } + return mh; + } + + toString(): string { + if (this.headers.size === 0) { + return ""; + } + let s = HEADER; + for (const [k, v] of this.headers) { + for (let i = 0; i < v.length; i++) { + s = `${s}\r\n${k}: ${v[i]}`; + } + } + return `${s}\r\n\r\n`; + } + + encode(): Uint8Array { + return TE.encode(this.toString()); + } + + // https://www.ietf.org/rfc/rfc822.txt + // 3.1.2. STRUCTURE OF HEADER FIELDS + // + // Once a field has been unfolded, it may be viewed as being com- + // posed of a field-name followed by a colon (":"), followed by a + // field-body, and terminated by a carriage-return/line-feed. + // The field-name must be composed of printable ASCII characters + // (i.e., characters that have values between 33. and 126., + // decimal, except colon). The field-body may be composed of any + // ASCII characters, except CR or LF. (While CR and/or LF may be + // present in the actual text, they are removed by the action of + // unfolding the field.) + static canonicalMIMEHeaderKey(k: string): string { + const a = 97; + const A = 65; + const Z = 90; + const z = 122; + const dash = 45; + const colon = 58; + const start = 33; + const end = 126; + const toLower = a - A; + + let upper = true; + const buf: number[] = new Array(k.length); + for (let i = 0; i < k.length; i++) { + let c = k.charCodeAt(i); + if (c === colon || c < start || c > end) { + throw new NatsError( + `'${k[i]}' is not a valid character for a header key`, + ErrorCode.BadHeader, + ); + } + if (upper && a <= c && c <= z) { + c -= toLower; + } else if (!upper && A <= c && c <= Z) { + c += toLower; + } + buf[i] = c; + upper = c == dash; + } + return String.fromCharCode(...buf); + } + + static validHeaderValue(k: string): string { + const inv = /[\r\n]/; + if (inv.test(k)) { + throw new NatsError( + "invalid header value - \\r and \\n are not allowed.", + ErrorCode.BadHeader, + ); + } + return k.trim(); + } + + get(k: string): string { + const key = MsgHdrsImpl.canonicalMIMEHeaderKey(k); + const a = this.headers.get(key); + return a ? a[0] : ""; + } + + has(k: string): boolean { + return this.get(k) !== ""; + } + + set(k: string, v: string): void { + const key = MsgHdrsImpl.canonicalMIMEHeaderKey(k); + const value = MsgHdrsImpl.validHeaderValue(v); + this.headers.set(key, [value]); + } + + append(k: string, v: string): void { + const key = MsgHdrsImpl.canonicalMIMEHeaderKey(k); + const value = MsgHdrsImpl.validHeaderValue(v); + let a = this.headers.get(key); + if (!a) { + a = []; + this.headers.set(key, a); + } + a.push(value); + } + + values(k: string): string[] { + const key = MsgHdrsImpl.canonicalMIMEHeaderKey(k); + return this.headers.get(key) || []; + } + + delete(k: string): void { + const key = MsgHdrsImpl.canonicalMIMEHeaderKey(k); + this.headers.delete(key); + } + + get hasError() { + return this.code >= 300; + } + + get status(): string { + return `${this.code} ${this.description}`.trim(); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/6bab9ceea279895af4796a5aa3f3f1d4d7c161c0.ts b/crates/swc_bundler/tests/.cache/untrusted/6bab9ceea279895af4796a5aa3f3f1d4d7c161c0.ts new file mode 100644 index 000000000000..e83f98954d82 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/6bab9ceea279895af4796a5aa3f3f1d4d7c161c0.ts @@ -0,0 +1,133 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/error.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum ErrorCode { + // emitted by the client + ApiError = "BAD API", + BadAuthentication = "BAD_AUTHENTICATION", + BadCreds = "BAD_CREDS", + BadHeader = "BAD_HEADER", + BadJson = "BAD_JSON", + BadPayload = "BAD_PAYLOAD", + BadSubject = "BAD_SUBJECT", + Cancelled = "CANCELLED", + ConnectionClosed = "CONNECTION_CLOSED", + ConnectionDraining = "CONNECTION_DRAINING", + ConnectionRefused = "CONNECTION_REFUSED", + ConnectionTimeout = "CONNECTION_TIMEOUT", + Disconnect = "DISCONNECT", + InvalidOption = "INVALID_OPTION", + InvalidPayload = "INVALID_PAYLOAD", + MaxPayloadExceeded = "MAX_PAYLOAD_EXCEEDED", + NoResponders = "503", + NotFunction = "NOT_FUNC", + RequestError = "REQUEST_ERROR", + ServerOptionNotAvailable = "SERVER_OPT_NA", + SubClosed = "SUB_CLOSED", + SubDraining = "SUB_DRAINING", + Timeout = "TIMEOUT", + Tls = "TLS", + Unknown = "UNKNOWN_ERROR", + WssRequired = "WSS_REQUIRED", + + // jetstream + JetStreamInvalidAck = "JESTREAM_INVALID_ACK", + JetStream404NoMessages = "404", + JetStream408RequestTimeout = "408", + JetStream409MaxAckPendingExceeded = "409", + JetStreamNotEnabled = "503", + + // emitted by the server + AuthorizationViolation = "AUTHORIZATION_VIOLATION", + AuthenticationExpired = "AUTHENTICATION_EXPIRED", + ProtocolError = "NATS_PROTOCOL_ERR", + PermissionsViolation = "PERMISSIONS_VIOLATION", +} + +export class Messages { + messages: Map; + + constructor() { + this.messages = new Map(); + this.messages.set( + ErrorCode.InvalidPayload, + "Invalid payload type - payloads can be 'binary', 'string', or 'json'", + ); + this.messages.set(ErrorCode.BadJson, "Bad JSON"); + this.messages.set( + ErrorCode.WssRequired, + "TLS is required, therefore a secure websocket connection is also required", + ); + } + + static getMessage(s: string): string { + return messages.getMessage(s); + } + + getMessage(s: string): string { + return this.messages.get(s) || s; + } +} + +// safari doesn't support static class members +const messages: Messages = new Messages(); + +export function isNatsError(err: NatsError | Error): err is NatsError { + return typeof (err as NatsError).code === "string"; +} + +export class NatsError extends Error { + name: string; + message: string; + code: string; + chainedError?: Error; + + /** + * @param {String} message + * @param {String} code + * @param {Error} [chainedError] + * @constructor + * + * @api private + */ + constructor(message: string, code: string, chainedError?: Error) { + super(message); + this.name = "NatsError"; + this.message = message; + this.code = code; + this.chainedError = chainedError; + } + + static errorForCode(code: string, chainedError?: Error): NatsError { + const m = Messages.getMessage(code); + return new NatsError(m, code, chainedError); + } + + isAuthError(): boolean { + return this.code === ErrorCode.AuthenticationExpired || + this.code === ErrorCode.AuthorizationViolation; + } + + isPermissionError(): boolean { + return this.code === ErrorCode.PermissionsViolation; + } + + isProtocolError(): boolean { + return this.code === ErrorCode.ProtocolError; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/75b7bb4b30dd209ee2cde87d057efe566fd762e7.ts b/crates/swc_bundler/tests/.cache/untrusted/75b7bb4b30dd209ee2cde87d057efe566fd762e7.ts new file mode 100644 index 000000000000..a7ba42ff1fc5 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/75b7bb4b30dd209ee2cde87d057efe566fd762e7.ts @@ -0,0 +1,19 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.ws/v1.0.1/src/mod.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/internal_mod.ts"; +export { connect } from "./connect.ts"; diff --git a/crates/swc_bundler/tests/.cache/untrusted/79094cdae1a9139f84bfb7febaac3d9db8adde23.ts b/crates/swc_bundler/tests/.cache/untrusted/79094cdae1a9139f84bfb7febaac3d9db8adde23.ts new file mode 100644 index 000000000000..ba00af50a27b --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/79094cdae1a9139f84bfb7febaac3d9db8adde23.ts @@ -0,0 +1,251 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/denobuffer.ts + + +// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. + +// This code has been ported almost directly from Go's src/bytes/buffer.go +// Copyright 2009 The Go Authors. All rights reserved. BSD license. +// https://github.com/golang/go/blob/master/LICENSE + +// This code removes all Deno specific functionality to enable its use +// in a browser environment + +//@internal +import { TE } from "./encoders.ts"; + +export class AssertionError extends Error { + constructor(msg?: string) { + super(msg); + this.name = "AssertionError"; + } +} + +export interface Reader { + read(p: Uint8Array): number | null; +} + +export interface Writer { + write(p: Uint8Array): number; +} + +// @internal +export function assert(cond: unknown, msg = "Assertion failed."): asserts cond { + if (!cond) { + throw new AssertionError(msg); + } +} + +// MIN_READ is the minimum ArrayBuffer size passed to a read call by +// buffer.ReadFrom. As long as the Buffer has at least MIN_READ bytes beyond +// what is required to hold the contents of r, readFrom() will not grow the +// underlying buffer. +const MIN_READ = 32 * 1024; + +export const MAX_SIZE = 2 ** 32 - 2; + +// `off` is the offset into `dst` where it will at which to begin writing values +// from `src`. +// Returns the number of bytes copied. +function copy(src: Uint8Array, dst: Uint8Array, off = 0): number { + const r = dst.byteLength - off; + if (src.byteLength > r) { + src = src.subarray(0, r); + } + dst.set(src, off); + return src.byteLength; +} + +export function concat(origin?: Uint8Array, b?: Uint8Array): Uint8Array { + if (origin === undefined && b === undefined) { + return new Uint8Array(0); + } + if (origin === undefined) { + return b!; + } + if (b === undefined) { + return origin; + } + const output = new Uint8Array(origin.length + b.length); + output.set(origin, 0); + output.set(b, origin.length); + return output; +} + +export function append(origin: Uint8Array, b: number): Uint8Array { + return concat(origin, Uint8Array.of(b)); +} + +export class DenoBuffer implements Reader, Writer { + _buf: Uint8Array; // contents are the bytes _buf[off : len(_buf)] + _off: number; // read at _buf[off], write at _buf[_buf.byteLength] + + constructor(ab?: ArrayBuffer) { + this._off = 0; + if (ab == null) { + this._buf = new Uint8Array(0); + return; + } + + this._buf = new Uint8Array(ab); + } + + bytes(options: { copy?: boolean } = { copy: true }): Uint8Array { + if (options.copy === false) return this._buf.subarray(this._off); + return this._buf.slice(this._off); + } + + empty(): boolean { + return this._buf.byteLength <= this._off; + } + + get length(): number { + return this._buf.byteLength - this._off; + } + + get capacity(): number { + return this._buf.buffer.byteLength; + } + + truncate(n: number): void { + if (n === 0) { + this.reset(); + return; + } + if (n < 0 || n > this.length) { + throw Error("bytes.Buffer: truncation out of range"); + } + this._reslice(this._off + n); + } + + reset(): void { + this._reslice(0); + this._off = 0; + } + + _tryGrowByReslice(n: number): number { + const l = this._buf.byteLength; + if (n <= this.capacity - l) { + this._reslice(l + n); + return l; + } + return -1; + } + + _reslice(len: number): void { + assert(len <= this._buf.buffer.byteLength); + this._buf = new Uint8Array(this._buf.buffer, 0, len); + } + + readByte(): number | null { + const a = new Uint8Array(1); + if (this.read(a)) { + return a[0]; + } + return null; + } + + read(p: Uint8Array): number | null { + if (this.empty()) { + // Buffer is empty, reset to recover space. + this.reset(); + if (p.byteLength === 0) { + // this edge case is tested in 'bufferReadEmptyAtEOF' test + return 0; + } + return null; + } + const nread = copy(this._buf.subarray(this._off), p); + this._off += nread; + return nread; + } + + writeByte(n: number): number { + return this.write(Uint8Array.of(n)); + } + + writeString(s: string): number { + return this.write(TE.encode(s)); + } + + write(p: Uint8Array): number { + const m = this._grow(p.byteLength); + return copy(p, this._buf, m); + } + + _grow(n: number): number { + const m = this.length; + // If buffer is empty, reset to recover space. + if (m === 0 && this._off !== 0) { + this.reset(); + } + // Fast: Try to _grow by means of a _reslice. + const i = this._tryGrowByReslice(n); + if (i >= 0) { + return i; + } + const c = this.capacity; + if (n <= Math.floor(c / 2) - m) { + // We can slide things down instead of allocating a new + // ArrayBuffer. We only need m+n <= c to slide, but + // we instead let capacity get twice as large so we + // don't spend all our time copying. + copy(this._buf.subarray(this._off), this._buf); + } else if (c + n > MAX_SIZE) { + throw new Error("The buffer cannot be grown beyond the maximum size."); + } else { + // Not enough space anywhere, we need to allocate. + const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE)); + copy(this._buf.subarray(this._off), buf); + this._buf = buf; + } + // Restore this.off and len(this._buf). + this._off = 0; + this._reslice(Math.min(m + n, MAX_SIZE)); + return m; + } + + grow(n: number): void { + if (n < 0) { + throw Error("Buffer._grow: negative count"); + } + const m = this._grow(n); + this._reslice(m); + } + + readFrom(r: Reader): number { + let n = 0; + const tmp = new Uint8Array(MIN_READ); + while (true) { + const shouldGrow = this.capacity - this.length < MIN_READ; + // read into tmp buffer if there's not enough room + // otherwise read directly into the internal buffer + const buf = shouldGrow + ? tmp + : new Uint8Array(this._buf.buffer, this.length); + + const nread = r.read(buf); + if (nread === null) { + return n; + } + + // write will grow if needed + if (shouldGrow) this.write(buf.subarray(0, nread)); + else this._reslice(this.length + nread); + + n += nread; + } + } +} + +export function readAll(r: Reader): Uint8Array { + const buf = new DenoBuffer(); + buf.readFrom(r); + return buf.bytes(); +} + +export function writeAll(w: Writer, arr: Uint8Array): void { + let nwritten = 0; + while (nwritten < arr.length) { + nwritten += w.write(arr.subarray(nwritten)); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/7fed52c6107144ebcd8a6dadcb175ab1ceec8675.ts b/crates/swc_bundler/tests/.cache/untrusted/7fed52c6107144ebcd8a6dadcb175ab1ceec8675.ts new file mode 100644 index 000000000000..ce5ac06e6edf --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/7fed52c6107144ebcd8a6dadcb175ab1ceec8675.ts @@ -0,0 +1,78 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/transport.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + ConnectionOptions, + DEFAULT_PORT, + Server, + URLParseFn, +} from "./types.ts"; + +let transportConfig: TransportFactory; +export function setTransportFactory(config: TransportFactory): void { + transportConfig = config; +} + +export function defaultPort(): number { + return transportConfig !== undefined && + transportConfig.defaultPort !== undefined + ? transportConfig.defaultPort + : DEFAULT_PORT; +} + +export function getUrlParseFn(): URLParseFn | undefined { + return transportConfig !== undefined && transportConfig.urlParseFn + ? transportConfig.urlParseFn + : undefined; +} + +export function newTransport(): Transport { + if (!transportConfig || typeof transportConfig.factory !== "function") { + throw new Error("transport fn is not set"); + } + return transportConfig.factory(); +} + +export interface TransportFactory { + factory?: () => Transport; + defaultPort?: number; + urlParseFn?: URLParseFn; +} + +export interface Transport extends AsyncIterable { + readonly isClosed: boolean; + readonly lang: string; + readonly version: string; + readonly closeError?: Error; + + connect( + server: Server, + opts: ConnectionOptions, + ): Promise; + + [Symbol.asyncIterator](): AsyncIterableIterator; + + isEncrypted(): boolean; + + send(frame: Uint8Array): Promise; + + close(err?: Error): Promise; + + disconnect(): void; + + closed(): Promise; +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/80bbe6eb2c50792684f187ea19c029edc81084f8.ts b/crates/swc_bundler/tests/.cache/untrusted/80bbe6eb2c50792684f187ea19c029edc81084f8.ts new file mode 100644 index 000000000000..1761c226dbe3 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/80bbe6eb2c50792684f187ea19c029edc81084f8.ts @@ -0,0 +1,112 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsbaseclient_api.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ApiResponse, + Empty, + JetStreamOptions, + Msg, + NatsConnection, + RequestOptions, + StreamNameBySubject, + StreamNames, +} from "./types.ts"; +import { Codec, JSONCodec } from "./codec.ts"; +import { extend } from "./util.ts"; +import { NatsConnectionImpl } from "./nats.ts"; +import { checkJsErrorCode } from "./jsutil.ts"; + +const defaultPrefix = "$JS.API"; +const defaultTimeout = 5000; + +export function defaultJsOptions(opts?: JetStreamOptions): JetStreamOptions { + opts = opts ?? {} as JetStreamOptions; + return extend({ apiPrefix: defaultPrefix, timeout: defaultTimeout }, opts); +} + +export class BaseApiClient { + nc: NatsConnectionImpl; + opts: JetStreamOptions; + prefix: string; + timeout: number; + jc: Codec; + + constructor(nc: NatsConnection, opts?: JetStreamOptions) { + this.nc = nc as NatsConnectionImpl; + this.opts = defaultJsOptions(opts); + this._parseOpts(); + this.prefix = this.opts.apiPrefix!; + this.timeout = this.opts.timeout!; + this.jc = JSONCodec(); + } + + _parseOpts() { + let prefix = this.opts.apiPrefix; + if (!prefix || prefix.length === 0) { + throw new Error("invalid empty prefix"); + } + const c = prefix[prefix.length - 1]; + if (c === ".") { + prefix = prefix.substr(0, prefix.length - 1); + } + this.opts.apiPrefix = prefix; + } + + async _request( + subj: string, + data: unknown = null, + opts?: RequestOptions, + ): Promise { + opts = opts || {} as RequestOptions; + opts.timeout = this.timeout; + + let a: Uint8Array = Empty; + if (data) { + a = this.jc.encode(data); + } + + const m = await this.nc.request( + subj, + a, + opts, + ); + return this.parseJsResponse(m); + } + + async findStream(subject: string): Promise { + const q = { subject } as StreamNameBySubject; + const r = await this._request(`${this.prefix}.STREAM.NAMES`, q); + const names = r as StreamNames; + if (!names.streams || names.streams.length !== 1) { + throw new Error("no stream matches subject"); + } + return names.streams[0]; + } + + parseJsResponse(m: Msg): unknown { + const v = this.jc.decode(m.data); + const r = v as ApiResponse; + if (r.error) { + const err = checkJsErrorCode(r.error.code, r.error.description); + if (err !== null) { + throw err; + } + } + return v; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/8b76e27ca7324b464ae5e2d840913b787c4431fe.ts b/crates/swc_bundler/tests/.cache/untrusted/8b76e27ca7324b464ae5e2d840913b787c4431fe.ts new file mode 100644 index 000000000000..4cedfc7c5aca --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/8b76e27ca7324b464ae5e2d840913b787c4431fe.ts @@ -0,0 +1,145 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/subscription.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DispatchedFn, QueuedIteratorImpl } from "./queued_iterator.ts"; +import type { Base, Msg, Subscription, SubscriptionOptions } from "./types.ts"; +import { Deferred, deferred, extend, Timeout, timeout } from "./util.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import type { ProtocolHandler } from "./protocol.ts"; + +export class SubscriptionImpl extends QueuedIteratorImpl + implements Base, Subscription { + sid!: number; + queue?: string; + draining: boolean; + max?: number; + subject: string; + drained?: Promise; + protocol: ProtocolHandler; + timer?: Timeout; + info?: unknown; + cleanupFn?: (sub: Subscription, info?: unknown) => void; + closed: Deferred; + + constructor( + protocol: ProtocolHandler, + subject: string, + opts: SubscriptionOptions = {}, + ) { + super(); + extend(this, opts); + this.protocol = protocol; + this.subject = subject; + this.draining = false; + this.noIterator = typeof opts.callback === "function"; + this.closed = deferred(); + + if (opts.timeout) { + this.timer = timeout(opts.timeout); + this.timer + .then(() => { + // timer was cancelled + this.timer = undefined; + }) + .catch((err) => { + // timer fired + this.stop(err); + }); + } + } + + setDispatchedFn(cb: DispatchedFn) { + // user specified callback + if (this.noIterator) { + const uc = this.callback; + this.callback = (err: NatsError | null, msg: Msg) => { + uc(err, msg); + cb(msg); + }; + } else { + this.dispatchedFn = cb; + } + } + + callback(err: NatsError | null, msg: Msg) { + this.cancelTimeout(); + err ? this.stop(err) : this.push(msg); + } + + close(): void { + if (!this.isClosed()) { + this.cancelTimeout(); + this.stop(); + if (this.cleanupFn) { + try { + this.cleanupFn(this, this.info); + } catch (err) { + // ignoring + } + } + this.closed.resolve(); + } + } + + unsubscribe(max?: number): void { + this.protocol.unsubscribe(this, max); + } + + cancelTimeout(): void { + if (this.timer) { + this.timer.cancel(); + this.timer = undefined; + } + } + + drain(): Promise { + if (this.protocol.isClosed()) { + throw NatsError.errorForCode(ErrorCode.ConnectionClosed); + } + if (this.isClosed()) { + throw NatsError.errorForCode(ErrorCode.SubClosed); + } + if (!this.drained) { + this.protocol.unsub(this); + this.drained = this.protocol.flush(deferred()); + this.drained.then(() => { + this.protocol.subscriptions.cancel(this); + }); + } + return this.drained; + } + + isDraining(): boolean { + return this.draining; + } + + isClosed(): boolean { + return this.done; + } + + getSubject(): string { + return this.subject; + } + + getMax(): number | undefined { + return this.max; + } + + getID(): number { + return this.sid; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/91a3b6a7f1c20c36b5ab28dc9274729ce4b87815.ts b/crates/swc_bundler/tests/.cache/untrusted/91a3b6a7f1c20c36b5ab28dc9274729ce4b87815.ts new file mode 100644 index 000000000000..f1955619a746 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/91a3b6a7f1c20c36b5ab28dc9274729ce4b87815.ts @@ -0,0 +1,19 @@ +// Loaded from https://esm.sh/stable/react@18.3.1/esnext/react.mjs + + +/* esm.sh - esbuild bundle(react@18.3.1) esnext production */ +var B=Object.create;var E=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var x=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),J=(e,t)=>{for(var r in t)E(e,r,{get:t[r],enumerable:!0})},S=(e,t,r,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of W(t))!G.call(e,o)&&o!==r&&E(e,o,{get:()=>t[o],enumerable:!(u=H(t,o))||u.enumerable});return e},y=(e,t,r)=>(S(e,t,"default"),r&&S(r,t,"default")),O=(e,t,r)=>(r=e!=null?B(Y(e)):{},S(t||!e||!e.__esModule?E(r,"default",{value:e,enumerable:!0}):r,e));var q=x(n=>{"use strict";var _=Symbol.for("react.element"),K=Symbol.for("react.portal"),Q=Symbol.for("react.fragment"),X=Symbol.for("react.strict_mode"),Z=Symbol.for("react.profiler"),ee=Symbol.for("react.provider"),te=Symbol.for("react.context"),re=Symbol.for("react.forward_ref"),ne=Symbol.for("react.suspense"),oe=Symbol.for("react.memo"),ue=Symbol.for("react.lazy"),j=Symbol.iterator;function se(e){return e===null||typeof e!="object"?null:(e=j&&e[j]||e["@@iterator"],typeof e=="function"?e:null)}var P={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T=Object.assign,D={};function d(e,t,r){this.props=e,this.context=t,this.refs=D,this.updater=r||P}d.prototype.isReactComponent={};d.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};d.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function V(){}V.prototype=d.prototype;function C(e,t,r){this.props=e,this.context=t,this.refs=D,this.updater=r||P}var k=C.prototype=new V;k.constructor=C;T(k,d.prototype);k.isPureReactComponent=!0;var I=Array.isArray,L=Object.prototype.hasOwnProperty,w={current:null},N={key:!0,ref:!0,__self:!0,__source:!0};function F(e,t,r){var u,o={},c=null,f=null;if(t!=null)for(u in t.ref!==void 0&&(f=t.ref),t.key!==void 0&&(c=""+t.key),t)L.call(t,u)&&!N.hasOwnProperty(u)&&(o[u]=t[u]);var i=arguments.length-2;if(i===1)o.children=r;else if(1{"use strict";A.exports=q()});var p={};J(p,{Children:()=>ae,Component:()=>pe,Fragment:()=>ye,Profiler:()=>de,PureComponent:()=>_e,StrictMode:()=>me,Suspense:()=>he,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>ve,act:()=>Se,cloneElement:()=>Ee,createContext:()=>Re,createElement:()=>Ce,createFactory:()=>ke,createRef:()=>we,default:()=>Ge,forwardRef:()=>be,isValidElement:()=>$e,lazy:()=>xe,memo:()=>Oe,startTransition:()=>je,unstable_act:()=>Ie,useCallback:()=>ge,useContext:()=>Pe,useDebugValue:()=>Te,useDeferredValue:()=>De,useEffect:()=>Ve,useId:()=>Le,useImperativeHandle:()=>Ne,useInsertionEffect:()=>Fe,useLayoutEffect:()=>Ue,useMemo:()=>qe,useReducer:()=>Ae,useRef:()=>Me,useState:()=>ze,useSyncExternalStore:()=>Be,useTransition:()=>He,version:()=>We});var z=O($());y(p,O($()));var{Children:ae,Component:pe,Fragment:ye,Profiler:de,PureComponent:_e,StrictMode:me,Suspense:he,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ve,act:Se,cloneElement:Ee,createContext:Re,createElement:Ce,createFactory:ke,createRef:we,forwardRef:be,isValidElement:$e,lazy:xe,memo:Oe,startTransition:je,unstable_act:Ie,useCallback:ge,useContext:Pe,useDebugValue:Te,useDeferredValue:De,useEffect:Ve,useId:Le,useImperativeHandle:Ne,useInsertionEffect:Fe,useLayoutEffect:Ue,useMemo:qe,useReducer:Ae,useRef:Me,useState:ze,useSyncExternalStore:Be,useTransition:He,version:We}=z,{default:M,...Ye}=z,Ge=M!==void 0?M:Ye;export{ae as Children,pe as Component,ye as Fragment,de as Profiler,_e as PureComponent,me as StrictMode,he as Suspense,ve as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Se as act,Ee as cloneElement,Re as createContext,Ce as createElement,ke as createFactory,we as createRef,Ge as default,be as forwardRef,$e as isValidElement,xe as lazy,Oe as memo,je as startTransition,Ie as unstable_act,ge as useCallback,Pe as useContext,Te as useDebugValue,De as useDeferredValue,Ve as useEffect,Le as useId,Ne as useImperativeHandle,Fe as useInsertionEffect,Ue as useLayoutEffect,qe as useMemo,Ae as useReducer,Me as useRef,ze as useState,Be as useSyncExternalStore,He as useTransition,We as version}; +/*! Bundled license information: + +react/cjs/react.production.min.js: + (** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) +*/ +//# sourceMappingURL=react.mjs.map \ No newline at end of file diff --git a/crates/swc_bundler/tests/.cache/untrusted/95be0026e5f127a68758f05cd2da89aff686dbe4.ts b/crates/swc_bundler/tests/.cache/untrusted/95be0026e5f127a68758f05cd2da89aff686dbe4.ts new file mode 100644 index 000000000000..2c21b270a2a7 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/95be0026e5f127a68758f05cd2da89aff686dbe4.ts @@ -0,0 +1,89 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsconsumer_api.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + ConsumerAPI, + ConsumerConfig, + ConsumerInfo, + ConsumerListResponse, + CreateConsumerRequest, + JetStreamOptions, + Lister, + NatsConnection, + SuccessResponse, +} from "./types.ts"; +import { BaseApiClient } from "./jsbaseclient_api.ts"; +import { ListerFieldFilter, ListerImpl } from "./jslister.ts"; +import { validateDurableName, validateStreamName } from "./jsutil.ts"; + +export class ConsumerAPIImpl extends BaseApiClient implements ConsumerAPI { + constructor(nc: NatsConnection, opts?: JetStreamOptions) { + super(nc, opts); + } + + async add( + stream: string, + cfg: ConsumerConfig, + ): Promise { + validateStreamName(stream); + + const cr = {} as CreateConsumerRequest; + cr.config = cfg; + cr.stream_name = stream; + + if (cr.config.durable_name) { + validateDurableName(cr.config.durable_name); + } + + const subj = cfg.durable_name + ? `${this.prefix}.CONSUMER.DURABLE.CREATE.${stream}.${cfg.durable_name}` + : `${this.prefix}.CONSUMER.CREATE.${stream}`; + const r = await this._request(subj, cr); + return r as ConsumerInfo; + } + + async info(stream: string, name: string): Promise { + validateStreamName(stream); + validateDurableName(name); + const r = await this._request( + `${this.prefix}.CONSUMER.INFO.${stream}.${name}`, + ); + return r as ConsumerInfo; + } + + async delete(stream: string, name: string): Promise { + validateStreamName(stream); + validateDurableName(name); + const r = await this._request( + `${this.prefix}.CONSUMER.DELETE.${stream}.${name}`, + ); + const cr = r as SuccessResponse; + return cr.success; + } + + list(stream: string): Lister { + validateStreamName(stream); + const filter: ListerFieldFilter = ( + v: unknown, + ): ConsumerInfo[] => { + const clr = v as ConsumerListResponse; + return clr.consumers; + }; + const subj = `${this.prefix}.CONSUMER.LIST.${stream}`; + return new ListerImpl(subj, filter, this); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/9a5f3c447c92c0b5ea5e4274691e6e8d21efc4e9.ts b/crates/swc_bundler/tests/.cache/untrusted/9a5f3c447c92c0b5ea5e4274691e6e8d21efc4e9.ts new file mode 100644 index 000000000000..4d3890175c62 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/9a5f3c447c92c0b5ea5e4274691e6e8d21efc4e9.ts @@ -0,0 +1,51 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/encoders.ts + + +/* + * Copyright 2020 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Empty } from "./types.ts"; + +export const TE = new TextEncoder(); +export const TD = new TextDecoder(); + +export function fastEncoder(...a: string[]): Uint8Array { + let len = 0; + for (let i = 0; i < a.length; i++) { + len += a[i] ? a[i].length : 0; + } + if (len === 0) { + return Empty; + } + const buf = new Uint8Array(len); + let c = 0; + for (let i = 0; i < a.length; i++) { + const s = a[i]; + if (s) { + for (let j = 0; j < s.length; j++) { + buf[c] = s.charCodeAt(j); + c++; + } + } + } + return buf; +} + +export function fastDecoder(a: Uint8Array): string { + if (!a || a.length === 0) { + return ""; + } + return String.fromCharCode(...a); +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/9ac3ab02f5261ef6c20c970b040790c7c4c71db9.ts b/crates/swc_bundler/tests/.cache/untrusted/9ac3ab02f5261ef6c20c970b040790c7c4c71db9.ts new file mode 100644 index 000000000000..813e43895eb9 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/9ac3ab02f5261ef6c20c970b040790c7c4c71db9.ts @@ -0,0 +1,390 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/bench.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Empty, NatsConnection } from "./types.ts"; +import { nuid } from "./nuid.ts"; +import { deferred, Perf } from "./util.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import type { NatsConnectionImpl } from "./nats.ts"; + +export class Metric { + name: string; + duration: number; + date: number; + payload: number; + msgs: number; + lang!: string; + version!: string; + bytes: number; + asyncRequests?: boolean; + min?: number; + max?: number; + + constructor(name: string, duration: number) { + this.name = name; + this.duration = duration; + this.date = Date.now(); + this.payload = 0; + this.msgs = 0; + this.bytes = 0; + } + + toString(): string { + const sec = (this.duration) / 1000; + const mps = Math.round(this.msgs / sec); + const label = this.asyncRequests ? "asyncRequests" : ""; + let minmax = ""; + if (this.max) { + minmax = `${this.min}/${this.max}`; + } + + return `${this.name}${label ? " [asyncRequests]" : ""} ${ + humanizeNumber(mps) + } msgs/sec - [${sec.toFixed(2)} secs] ~ ${ + throughput(this.bytes, sec) + } ${minmax}`; + } + + toCsv(): string { + return `"${this.name}",${ + new Date(this.date).toISOString() + },${this.lang},${this.version},${this.msgs},${this.payload},${this.bytes},${this.duration},${ + this.asyncRequests ? this.asyncRequests : false + }\n`; + } + + static header(): string { + return `Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async\n`; + } +} + +export interface BenchOpts { + callbacks?: boolean; + msgs?: number; + size?: number; + subject?: string; + asyncRequests?: boolean; + pub?: boolean; + sub?: boolean; + rep?: boolean; + req?: boolean; +} + +export class Bench { + nc: NatsConnection; + callbacks: boolean; + msgs: number; + size: number; + subject: string; + asyncRequests?: boolean; + pub?: boolean; + sub?: boolean; + req?: boolean; + rep?: boolean; + perf: Perf; + payload: Uint8Array; + + constructor( + nc: NatsConnection, + opts: BenchOpts = { + msgs: 100000, + size: 128, + subject: "", + asyncRequests: false, + pub: false, + sub: false, + req: false, + rep: false, + }, + ) { + this.nc = nc; + this.callbacks = opts.callbacks || false; + this.msgs = opts.msgs || 0; + this.size = opts.size || 0; + this.subject = opts.subject || nuid.next(); + this.asyncRequests = opts.asyncRequests || false; + this.pub = opts.pub || false; + this.sub = opts.sub || false; + this.req = opts.req || false; + this.rep = opts.rep || false; + this.perf = new Perf(); + this.payload = this.size ? new Uint8Array(this.size) : Empty; + + if (!this.pub && !this.sub && !this.req && !this.rep) { + throw new Error("no bench option selected"); + } + } + + async run(): Promise { + this.nc.closed() + .then((err) => { + if (err) { + throw new NatsError( + `bench closed with an error: ${err.message}`, + ErrorCode.Unknown, + err, + ); + } + }); + + if (this.callbacks) { + await this.runCallbacks(); + } else { + await this.runAsync(); + } + return this.processMetrics(); + } + + processMetrics(): Metric[] { + const nc = this.nc as NatsConnectionImpl; + const { lang, version } = nc.protocol.transport; + + if (this.pub && this.sub) { + this.perf.measure("pubsub", "pubStart", "subStop"); + } + + const measures = this.perf.getEntries(); + const pubsub = measures.find((m) => m.name === "pubsub"); + const req = measures.find((m) => m.name === "req"); + const pub = measures.find((m) => m.name === "pub"); + const sub = measures.find((m) => m.name === "sub"); + + const stats = this.nc.stats(); + + const metrics: Metric[] = []; + if (pubsub) { + const { name, duration } = pubsub; + const m = new Metric(name, duration); + m.msgs = this.msgs * 2; + m.bytes = stats.inBytes + stats.outBytes; + m.lang = lang; + m.version = version; + m.payload = this.payload.length; + metrics.push(m); + } + + if (pub) { + const { name, duration } = pub; + const m = new Metric(name, duration); + m.msgs = this.msgs; + m.bytes = stats.outBytes; + m.lang = lang; + m.version = version; + m.payload = this.payload.length; + metrics.push(m); + } + + if (sub) { + const { name, duration } = sub; + const m = new Metric(name, duration); + m.msgs = this.msgs; + m.bytes = stats.inBytes; + m.lang = lang; + m.version = version; + m.payload = this.payload.length; + metrics.push(m); + } + + if (req) { + const { name, duration } = req; + const m = new Metric(name, duration); + m.msgs = this.msgs * 2; + m.bytes = stats.inBytes + stats.outBytes; + m.lang = lang; + m.version = version; + m.payload = this.payload.length; + metrics.push(m); + } + + return metrics; + } + + async runCallbacks(): Promise { + const jobs: Promise[] = []; + + if (this.req) { + const d = deferred(); + jobs.push(d); + const sub = this.nc.subscribe( + this.subject, + { + max: this.msgs, + callback: (_, m) => { + m.respond(this.payload); + if (sub.getProcessed() === this.msgs) { + d.resolve(); + } + }, + }, + ); + } + + if (this.sub) { + const d = deferred(); + jobs.push(d); + let i = 0; + const sub = this.nc.subscribe(this.subject, { + max: this.msgs, + callback: (_, msg) => { + i++; + if (i === 1) { + this.perf.mark("subStart"); + } + if (i === this.msgs) { + this.perf.mark("subStop"); + this.perf.measure("sub", "subStart", "subStop"); + d.resolve(); + } + }, + }); + } + + if (this.pub) { + const job = (async () => { + this.perf.mark("pubStart"); + for (let i = 0; i < this.msgs; i++) { + this.nc.publish(this.subject, this.payload); + } + await this.nc.flush(); + this.perf.mark("pubStop"); + this.perf.measure("pub", "pubStart", "pubStop"); + })(); + jobs.push(job); + } + + if (this.req) { + const job = (async () => { + if (this.asyncRequests) { + this.perf.mark("reqStart"); + const a = []; + for (let i = 0; i < this.msgs; i++) { + a.push( + this.nc.request(this.subject, this.payload, { timeout: 20000 }), + ); + } + await Promise.all(a); + this.perf.mark("reqStop"); + this.perf.measure("req", "reqStart", "reqStop"); + } else { + this.perf.mark("reqStart"); + for (let i = 0; i < this.msgs; i++) { + await this.nc.request(this.subject); + } + this.perf.mark("reqStop"); + this.perf.measure("req", "reqStart", "reqStop"); + } + })(); + jobs.push(job); + } + + await Promise.all(jobs); + } + + async runAsync(): Promise { + const jobs: Promise[] = []; + + if (this.req) { + const sub = this.nc.subscribe(this.subject, { max: this.msgs }); + const job = (async () => { + for await (const m of sub) { + m.respond(this.payload); + } + })(); + jobs.push(job); + } + + if (this.sub) { + let first = false; + const sub = this.nc.subscribe(this.subject, { max: this.msgs }); + const job = (async () => { + for await (const m of sub) { + if (!first) { + this.perf.mark("subStart"); + first = true; + } + } + this.perf.mark("subStop"); + this.perf.measure("sub", "subStart", "subStop"); + })(); + jobs.push(job); + } + + if (this.pub) { + const job = (async () => { + this.perf.mark("pubStart"); + for (let i = 0; i < this.msgs; i++) { + this.nc.publish(this.subject, this.payload); + } + await this.nc.flush(); + this.perf.mark("pubStop"); + this.perf.measure("pub", "pubStart", "pubStop"); + })(); + jobs.push(job); + } + + if (this.req) { + const job = (async () => { + if (this.asyncRequests) { + this.perf.mark("reqStart"); + const a = []; + for (let i = 0; i < this.msgs; i++) { + a.push( + this.nc.request(this.subject, this.payload, { timeout: 20000 }), + ); + } + await Promise.all(a); + this.perf.mark("reqStop"); + this.perf.measure("req", "reqStart", "reqStop"); + } else { + this.perf.mark("reqStart"); + for (let i = 0; i < this.msgs; i++) { + await this.nc.request(this.subject); + } + this.perf.mark("reqStop"); + this.perf.measure("req", "reqStart", "reqStop"); + } + })(); + jobs.push(job); + } + + await Promise.all(jobs); + } +} + +function throughput(bytes: number, seconds: number): string { + return humanizeBytes(bytes / seconds); +} + +function humanizeBytes(bytes: number, si = false): string { + const base = si ? 1000 : 1024; + const pre = si + ? ["k", "M", "G", "T", "P", "E"] + : ["K", "M", "G", "T", "P", "E"]; + const post = si ? "iB" : "B"; + + if (bytes < base) { + return `${bytes.toFixed(2)} ${post}/sec`; + } + const exp = parseInt(Math.log(bytes) / Math.log(base) + ""); + const index = parseInt((exp - 1) + ""); + return `${(bytes / Math.pow(base, exp)).toFixed(2)} ${pre[index]}${post}/sec`; +} + +function humanizeNumber(n: number) { + return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/9e4158aa9c20a8a46ee0d83440bff47e8b6b9b61.ts b/crates/swc_bundler/tests/.cache/untrusted/9e4158aa9c20a8a46ee0d83440bff47e8b6b9b61.ts new file mode 100644 index 000000000000..16e9b2da3022 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/9e4158aa9c20a8a46ee0d83440bff47e8b6b9b61.ts @@ -0,0 +1,218 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/ipparser.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// JavaScript port of go net/ip/ParseIP +// https://github.com/golang/go/blob/master/src/net/ip.go +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +const IPv4LEN = 4; +const IPv6LEN = 16; +const ASCII0 = 48; +const ASCII9 = 57; +const ASCIIA = 65; +const ASCIIF = 70; +const ASCIIa = 97; +const ASCIIf = 102; +const big = 0xFFFFFF; + +export function ipV4(a: number, b: number, c: number, d: number): Uint8Array { + const ip = new Uint8Array(IPv6LEN); + const prefix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]; + prefix.forEach((v, idx) => { + ip[idx] = v; + }); + ip[12] = a; + ip[13] = b; + ip[14] = c; + ip[15] = d; + + return ip; +} + +export function isIP(h: string) { + return parseIP(h) !== undefined; +} + +export function parseIP(h: string): (Uint8Array | undefined) { + for (let i = 0; i < h.length; i++) { + switch (h[i]) { + case ".": + return parseIPv4(h); + case ":": + return parseIPv6(h); + } + } + return; +} + +function parseIPv4(s: string): (Uint8Array | undefined) { + const ip = new Uint8Array(IPv4LEN); + for (let i = 0; i < IPv4LEN; i++) { + if (s.length === 0) { + return undefined; + } + if (i > 0) { + if (s[0] !== ".") { + return undefined; + } + s = s.substring(1); + } + const { n, c, ok } = dtoi(s); + if (!ok || n > 0xFF) { + return undefined; + } + s = s.substring(c); + ip[i] = n; + } + return ipV4(ip[0], ip[1], ip[2], ip[3]); +} + +function parseIPv6(s: string): (Uint8Array | undefined) { + const ip = new Uint8Array(IPv6LEN); + let ellipsis = -1; + + if (s.length >= 2 && s[0] === ":" && s[1] === ":") { + ellipsis = 0; + s = s.substring(2); + if (s.length === 0) { + return ip; + } + } + + let i = 0; + while (i < IPv6LEN) { + const { n, c, ok } = xtoi(s); + if (!ok || n > 0xFFFF) { + return undefined; + } + + if (c < s.length && s[c] === ".") { + if (ellipsis < 0 && i != IPv6LEN - IPv4LEN) { + return undefined; + } + if (i + IPv4LEN > IPv6LEN) { + return undefined; + } + const ip4 = parseIPv4(s); + if (ip4 === undefined) { + return undefined; + } + ip[i] = ip4[12]; + ip[i + 1] = ip4[13]; + ip[i + 2] = ip4[14]; + ip[i + 3] = ip4[15]; + s = ""; + i += IPv4LEN; + break; + } + + ip[i] = n >> 8; + ip[i + 1] = n; + i += 2; + + s = s.substring(c); + if (s.length === 0) { + break; + } + + if (s[0] !== ":" || s.length == 1) { + return undefined; + } + + s = s.substring(1); + + if (s[0] === ":") { + if (ellipsis >= 0) { + return undefined; + } + ellipsis = i; + s = s.substring(1); + if (s.length === 0) { + break; + } + } + } + + if (s.length !== 0) { + return undefined; + } + + if (i < IPv6LEN) { + if (ellipsis < 0) { + return undefined; + } + + const n = IPv6LEN - i; + for (let j = i - 1; j >= ellipsis; j--) { + ip[j + n] = ip[j]; + } + for (let j = ellipsis + n - 1; j >= ellipsis; j--) { + ip[j] = 0; + } + } else if (ellipsis >= 0) { + return undefined; + } + return ip; +} + +function dtoi(s: string): { n: number; c: number; ok: boolean } { + let i = 0; + let n = 0; + for ( + i = 0; + i < s.length && ASCII0 <= s.charCodeAt(i) && s.charCodeAt(i) <= ASCII9; + i++ + ) { + n = n * 10 + (s.charCodeAt(i) - ASCII0); + if (n >= big) { + return { n: big, c: i, ok: false }; + } + } + if (i === 0) { + return { n: 0, c: 0, ok: false }; + } + return { n: n, c: i, ok: true }; +} + +function xtoi(s: string): { n: number; c: number; ok: boolean } { + let n = 0; + let i = 0; + for (i = 0; i < s.length; i++) { + if (ASCII0 <= s.charCodeAt(i) && s.charCodeAt(i) <= ASCII9) { + n *= 16; + n += (s.charCodeAt(i) - ASCII0); + } else if (ASCIIa <= s.charCodeAt(i) && s.charCodeAt(i) <= ASCIIf) { + n *= 16; + n += (s.charCodeAt(i) - ASCIIa) + 10; + } else if (ASCIIA <= s.charCodeAt(i) && s.charCodeAt(i) <= ASCIIF) { + n *= 16; + n += (s.charCodeAt(i) - ASCIIA) + 10; + } else { + break; + } + if (n >= big) { + return { n: 0, c: i, ok: false }; + } + } + if (i === 0) { + return { n: 0, c: i, ok: false }; + } + return { n: n, c: i, ok: true }; +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/a47f5128949cef31d57df373ca28d39b4537ba1f.ts b/crates/swc_bundler/tests/.cache/untrusted/a47f5128949cef31d57df373ca28d39b4537ba1f.ts new file mode 100644 index 000000000000..3c4ad53fd16f --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/a47f5128949cef31d57df373ca28d39b4537ba1f.ts @@ -0,0 +1,543 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jsclient.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AckPolicy, + ConsumerAPI, + ConsumerConfig, + ConsumerInfo, + ConsumerInfoable, + ConsumerOpts, + DeliverPolicy, + Destroyable, + Empty, + JetStreamClient, + JetStreamOptions, + JetStreamPublishOptions, + JetStreamPullSubscription, + JetStreamSubscription, + JetStreamSubscriptionOptions, + JsMsg, + Msg, + NatsConnection, + PubAck, + Pullable, + PullOptions, + ReplayPolicy, + RequestOptions, +} from "./types.ts"; +import { BaseApiClient } from "./jsbaseclient_api.ts"; +import { + checkJsError, + isFlowControlMsg, + nanos, + validateDurableName, + validateStreamName, +} from "./jsutil.ts"; +import { ConsumerAPIImpl } from "./jsconsumer_api.ts"; +import { toJsMsg } from "./jsmsg.ts"; +import { + MsgAdapter, + TypedSubscription, + TypedSubscriptionOptions, +} from "./typedsub.ts"; +import { ErrorCode, isNatsError, NatsError } from "./error.ts"; +import { SubscriptionImpl } from "./subscription.ts"; +import { QueuedIterator, QueuedIteratorImpl } from "./queued_iterator.ts"; +import { Timeout, timeout } from "./util.ts"; +import { createInbox } from "./protocol.ts"; +import { headers } from "./headers.ts"; +import type { ConsumerOptsBuilder } from "./jsconsumeropts.ts"; +import { consumerOpts, isConsumerOptsBuilder } from "./jsconsumeropts.ts"; + +export interface JetStreamSubscriptionInfoable { + info: JetStreamSubscriptionInfo | null; +} + +enum PubHeaders { + MsgIdHdr = "Nats-Msg-Id", + ExpectedStreamHdr = "Nats-Expected-Stream", + ExpectedLastSeqHdr = "Nats-Expected-Last-Sequence", + ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id", +} + +export class JetStreamClientImpl extends BaseApiClient + implements JetStreamClient { + api: ConsumerAPI; + constructor(nc: NatsConnection, opts?: JetStreamOptions) { + super(nc, opts); + this.api = new ConsumerAPIImpl(nc, opts); + } + + async publish( + subj: string, + data: Uint8Array = Empty, + opts?: Partial, + ): Promise { + opts = opts ?? {}; + opts.expect = opts.expect ?? {}; + const mh = headers(); + if (opts) { + if (opts.msgID) { + mh.set(PubHeaders.MsgIdHdr, opts.msgID); + } + if (opts.expect.lastMsgID) { + mh.set(PubHeaders.ExpectedLastMsgIdHdr, opts.expect.lastMsgID); + } + if (opts.expect.streamName) { + mh.set(PubHeaders.ExpectedStreamHdr, opts.expect.streamName); + } + if (opts.expect.lastSequence) { + mh.set(PubHeaders.ExpectedLastSeqHdr, `${opts.expect.lastSequence}`); + } + } + + const to = opts.timeout ?? this.timeout; + const ro = {} as RequestOptions; + if (to) { + ro.timeout = to; + } + if (opts) { + ro.headers = mh; + } + + const r = await this.nc.request(subj, data, ro); + + const pa = this.parseJsResponse(r) as PubAck; + if (pa.stream === "") { + throw NatsError.errorForCode(ErrorCode.JetStreamInvalidAck); + } + pa.duplicate = pa.duplicate ? pa.duplicate : false; + return pa; + } + + async pull(stream: string, durable: string): Promise { + validateStreamName(stream); + validateDurableName(durable); + const msg = await this.nc.request( + // FIXME: specify expires + `${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`, + this.jc.encode({ no_wait: true, batch: 1, expires: nanos(this.timeout) }), + { noMux: true, timeout: this.timeout }, + ); + const err = checkJsError(msg); + if (err) { + throw (err); + } + return toJsMsg(msg); + } + + /* + * Returns available messages upto specified batch count. + * If expires is set the iterator will wait for the specified + * amount of millis before closing the subscription. + * If no_wait is specified, the iterator will return no messages. + * @param stream + * @param durable + * @param opts + */ + fetch( + stream: string, + durable: string, + opts: Partial = {}, + ): QueuedIterator { + validateStreamName(stream); + validateDurableName(durable); + + let timer: Timeout | null = null; + + const args: Partial = {}; + args.batch = opts.batch ?? 1; + args.no_wait = opts.no_wait ?? false; + const expires = opts.expires ?? 0; + if (expires) { + args.expires = nanos(expires); + } + if (expires === 0 && args.no_wait === false) { + throw new Error("expires or no_wait is required"); + } + + const qi = new QueuedIteratorImpl(); + const wants = args.batch; + let received = 0; + qi.dispatchedFn = (m: JsMsg | null) => { + if (m) { + received++; + if (timer && m.info.pending === 0) { + // the expiration will close it + return; + } + // if we have one pending and we got the expected + // or there are no more stop the iterator + if ( + qi.getPending() === 1 && m.info.pending === 0 || wants === received + ) { + qi.stop(); + } + } + }; + + const inbox = createInbox(this.nc.options.inboxPrefix); + const sub = this.nc.subscribe(inbox, { + max: opts.batch, + callback: (err: Error | null, msg) => { + if (err === null) { + err = checkJsError(msg); + } + if (err !== null) { + if (timer) { + timer.cancel(); + timer = null; + } + if ( + isNatsError(err) && err.code === ErrorCode.JetStream404NoMessages + ) { + qi.stop(); + } else { + qi.stop(err); + } + } else { + qi.received++; + qi.push(toJsMsg(msg)); + } + }, + }); + + // timer on the client the issue is that the request + // is started on the client, which means that it will expire + // on the client first + if (expires) { + timer = timeout(expires); + timer.catch(() => { + if (!sub.isClosed()) { + sub.drain(); + timer = null; + } + }); + } + + (async () => { + // close the iterator if the connection or subscription closes unexpectedly + await (sub as SubscriptionImpl).closed; + if (timer !== null) { + timer.cancel(); + timer = null; + } + qi.stop(); + })().catch(); + + this.nc.publish( + `${this.prefix}.CONSUMER.MSG.NEXT.${stream}.${durable}`, + this.jc.encode(args), + { reply: inbox }, + ); + return qi; + } + + async pullSubscribe( + subject: string, + opts: ConsumerOptsBuilder | Partial = consumerOpts(), + ): Promise { + const cso = await this._processOptions(subject, opts); + if (!cso.attached) { + cso.config.filter_subject = subject; + } + if (cso.config.deliver_subject) { + throw new Error( + "consumer info specifies deliver_subject - pull consumers cannot have deliver_subject set", + ); + } + + const ackPolicy = cso.config.ack_policy; + if (ackPolicy === AckPolicy.None || ackPolicy === AckPolicy.All) { + throw new Error("ack policy for pull consumers must be explicit"); + } + + const so = this._buildTypedSubscriptionOpts(cso); + const sub = new JetStreamPullSubscriptionImpl( + this, + cso.deliver, + so, + ); + + try { + await this._maybeCreateConsumer(cso); + } catch (err) { + sub.unsubscribe(); + throw err; + } + sub.info = cso; + return sub as JetStreamPullSubscription; + } + + async subscribe( + subject: string, + opts: ConsumerOptsBuilder | Partial = consumerOpts(), + ): Promise { + const cso = await this._processOptions(subject, opts); + // this effectively requires deliver subject to be specified + // as an option otherwise we have a pull consumer + if (!cso.config.deliver_subject) { + throw new Error( + "consumer info specifies a pull consumer - deliver_subject is required", + ); + } + + const so = this._buildTypedSubscriptionOpts(cso); + const sub = new JetStreamSubscriptionImpl( + this, + cso.deliver, + so, + ); + try { + await this._maybeCreateConsumer(cso); + } catch (err) { + sub.unsubscribe(); + throw err; + } + sub.info = cso; + return sub; + } + + async _processOptions( + subject: string, + opts: ConsumerOptsBuilder | Partial = consumerOpts(), + ): Promise { + const jsi = + (isConsumerOptsBuilder(opts) + ? opts.getOpts() + : opts) as JetStreamSubscriptionInfo; + + jsi.api = this; + jsi.config = jsi.config ?? {} as ConsumerConfig; + jsi.stream = jsi.stream ? jsi.stream : await this.findStream(subject); + + jsi.attached = false; + if (jsi.config.durable_name) { + try { + const info = await this.api.info(jsi.stream, jsi.config.durable_name); + if (info) { + if ( + info.config.filter_subject && info.config.filter_subject !== subject + ) { + throw new Error("subject does not match consumer"); + } + jsi.config = info.config; + jsi.attached = true; + } + } catch (err) { + //consumer doesn't exist + if (err.code !== "404") { + throw err; + } + } + } + + if (!jsi.attached) { + jsi.config.filter_subject = subject; + // jsi.config.deliver_subject = jsi.config.deliver_subject ?? + // createInbox(this.nc.options.inboxPrefix); + } + + jsi.deliver = jsi.config.deliver_subject ?? + createInbox(this.nc.options.inboxPrefix); + + return jsi; + } + + _buildTypedSubscriptionOpts( + jsi: JetStreamSubscriptionInfo, + ): TypedSubscriptionOptions { + const so = {} as TypedSubscriptionOptions; + so.adapter = msgAdapter(jsi.callbackFn === undefined); + if (jsi.callbackFn) { + so.callback = jsi.callbackFn; + } + if (!jsi.mack) { + so.dispatchedFn = autoAckJsMsg; + } + so.max = jsi.max ?? 0; + return so; + } + + async _maybeCreateConsumer(jsi: JetStreamSubscriptionInfo): Promise { + if (jsi.attached) { + return; + } + jsi.config = Object.assign({ + deliver_policy: DeliverPolicy.All, + ack_policy: AckPolicy.Explicit, + ack_wait: nanos(30 * 1000), + replay_policy: ReplayPolicy.Instant, + }, jsi.config); + + const ci = await this.api.add(jsi.stream, jsi.config); + jsi.name = ci.name; + jsi.config = ci.config; + } +} + +class JetStreamSubscriptionImpl extends TypedSubscription + implements JetStreamSubscriptionInfoable, Destroyable, ConsumerInfoable { + constructor( + js: BaseApiClient, + subject: string, + opts: JetStreamSubscriptionOptions, + ) { + super(js.nc, subject, opts); + } + + set info(info: JetStreamSubscriptionInfo | null) { + (this.sub as SubscriptionImpl).info = info; + } + + get info(): JetStreamSubscriptionInfo | null { + return this.sub.info as JetStreamSubscriptionInfo; + } + + async destroy(): Promise { + if (!this.isClosed()) { + await this.drain(); + } + const jinfo = this.sub.info as JetStreamSubscriptionInfo; + const name = jinfo.config.durable_name ?? jinfo.name; + const subj = `${jinfo.api.prefix}.CONSUMER.DELETE.${jinfo.stream}.${name}`; + await jinfo.api._request(subj); + } + + async consumerInfo(): Promise { + const jinfo = this.sub.info as JetStreamSubscriptionInfo; + const name = jinfo.config.durable_name ?? jinfo.name; + const subj = `${jinfo.api.prefix}.CONSUMER.INFO.${jinfo.stream}.${name}`; + return await jinfo.api._request(subj) as ConsumerInfo; + } +} + +class JetStreamPullSubscriptionImpl extends JetStreamSubscriptionImpl + implements Pullable { + constructor( + js: BaseApiClient, + subject: string, + opts: TypedSubscriptionOptions, + ) { + super(js, subject, opts); + } + pull(opts: Partial = { batch: 1 }): void { + const { stream, config } = this.sub.info as JetStreamSubscriptionInfo; + const consumer = config.durable_name; + const args: Partial = {}; + args.batch = opts.batch ?? 1; + args.no_wait = opts.no_wait ?? false; + // FIXME: this is nanos + if (opts.expires && opts.expires > 0) { + args.expires = opts.expires; + } + + if (this.info) { + const api = (this.info.api as BaseApiClient); + const subj = `${api.prefix}.CONSUMER.MSG.NEXT.${stream}.${consumer}`; + const reply = this.sub.subject; + + api.nc.publish( + subj, + api.jc.encode(args), + { reply: reply }, + ); + } + } +} + +interface JetStreamSubscriptionInfo extends ConsumerOpts { + api: BaseApiClient; + attached: boolean; + deliver: string; +} + +function msgAdapter(iterator: boolean): MsgAdapter { + if (iterator) { + return iterMsgAdapter; + } else { + return cbMsgAdapter; + } +} + +function cbMsgAdapter( + err: NatsError | null, + msg: Msg, +): [NatsError | null, JsMsg | null] { + if (err) { + return [err, null]; + } + err = checkJsError(msg); + if (err) { + return [err, null]; + } + if (isFlowControlMsg(msg)) { + msg.respond(); + return [null, null]; + } + const jm = toJsMsg(msg); + try { + // this will throw if not a JsMsg + jm.info; + return [null, jm]; + } catch (err) { + return [err, null]; + } +} + +function iterMsgAdapter( + err: NatsError | null, + msg: Msg, +): [NatsError | null, JsMsg | null] { + if (err) { + return [err, null]; + } + + // iterator will close if we have an error + // check for errors that shouldn't close it + const ne = checkJsError(msg); + if (ne !== null) { + switch (ne.code) { + case ErrorCode.JetStream404NoMessages: + case ErrorCode.JetStream408RequestTimeout: + case ErrorCode.JetStream409MaxAckPendingExceeded: + return [null, null]; + default: + return [ne, null]; + } + } + if (isFlowControlMsg(msg)) { + msg.respond(); + return [null, null]; + } + const jm = toJsMsg(msg); + try { + // this will throw if not a JsMsg + jm.info; + return [null, jm]; + } catch (err) { + return [err, null]; + } +} + +function autoAckJsMsg(data: JsMsg | null) { + if (data) { + data.ack(); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/ab44f2fda4625a6bc5d1f38f54a2c3a460982234.ts b/crates/swc_bundler/tests/.cache/untrusted/ab44f2fda4625a6bc5d1f38f54a2c3a460982234.ts new file mode 100644 index 000000000000..5033a2021099 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/ab44f2fda4625a6bc5d1f38f54a2c3a460982234.ts @@ -0,0 +1,198 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/typedsub.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Deferred, deferred } from "./util.ts"; +import type { DispatchedFn } from "./queued_iterator.ts"; +import type { + Msg, + NatsConnection, + Sub, + SubOpts, + Subscription, + SubscriptionOptions, +} from "./types.ts"; +import { QueuedIteratorImpl } from "./queued_iterator.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { SubscriptionImpl } from "./subscription.ts"; + +/** + * Converts a NATS message into some other type. Implementers are expected to: + * return [err, null] if the message callback is invoked with an error. + * return [err, null] if converting the message yielded an error, note that + * iterators will stop on the error, but callbacks will be presented with + * the error. + * return [null, T] if the conversion worked correctly + */ +export type MsgAdapter = ( + err: NatsError | null, + msg: Msg, +) => [NatsError | null, T | null]; + +/** + * Callback presented to the user with the converted type + */ +export type TypedCallback = (err: NatsError | null, msg: T | null) => void; + +export interface TypedSubscriptionOptions extends SubOpts { + adapter: MsgAdapter; + callback?: TypedCallback; + dispatchedFn?: DispatchedFn; + cleanupFn?: (sub: Subscription, info?: unknown) => void; +} + +export function checkFn(fn: unknown, name: string, required = false) { + if (required === true && !fn) { + throw NatsError.errorForCode( + ErrorCode.ApiError, + new Error(`${name} is not a function`), + ); + } + if (fn && typeof fn !== "function") { + throw NatsError.errorForCode( + ErrorCode.ApiError, + new Error(`${name} is not a function`), + ); + } +} + +/** + * TypedSubscription wraps a subscription to provide payload specific + * subscription semantics. That is messages are a transport + * for user data, and the data is presented as application specific + * data to the client. + */ +export class TypedSubscription extends QueuedIteratorImpl + implements Sub { + sub: SubscriptionImpl; + adapter: MsgAdapter; + subIterDone: Deferred; + + constructor( + nc: NatsConnection, + subject: string, + opts: TypedSubscriptionOptions, + ) { + super(); + + checkFn(opts.adapter, "adapter", true); + this.adapter = opts.adapter; + + if (opts.callback) { + checkFn(opts.callback, "callback"); + } + this.noIterator = typeof opts.callback === "function"; + + if (opts.dispatchedFn) { + checkFn(opts.dispatchedFn, "dispatchedFn"); + this.dispatchedFn = opts.dispatchedFn; + } + if (opts.cleanupFn) { + checkFn(opts.cleanupFn, "cleanupFn"); + } + + let callback = (err: NatsError | null, msg: Msg) => { + this.callback(err, msg); + }; + if (opts.callback) { + const uh = opts.callback; + callback = (err: NatsError | null, msg: Msg) => { + const [jer, tm] = this.adapter(err, msg); + uh(jer, tm); + if (this.dispatchedFn && tm) { + this.dispatchedFn(tm); + } + }; + } + const { max, queue, timeout } = opts; + const sopts = { queue, timeout, callback } as SubscriptionOptions; + if (max && max > 0) { + sopts.max = max; + } + this.sub = nc.subscribe(subject, sopts) as SubscriptionImpl; + if (opts.cleanupFn) { + this.sub.cleanupFn = opts.cleanupFn; + } + + this.subIterDone = deferred(); + Promise.all([this.sub.closed, this.iterClosed]) + .then(() => { + this.subIterDone.resolve(); + }) + .catch(() => { + this.subIterDone.resolve(); + }); + (async (s) => { + await s.closed; + this.stop(); + })(this.sub).then().catch(); + } + + unsubscribe(max?: number): void { + this.sub.unsubscribe(max); + } + + drain(): Promise { + return this.sub.drain(); + } + + isDraining(): boolean { + return this.sub.isDraining(); + } + + isClosed(): boolean { + return this.sub.isClosed(); + } + + callback(e: NatsError | null, msg: Msg): void { + const [err, tm] = this.adapter(e, msg); + if (err) { + this.stop(err); + } + if (tm) { + this.push(tm); + } + } + + getSubject(): string { + return this.sub.getSubject(); + } + + getReceived(): number { + return this.sub.getReceived(); + } + + getProcessed(): number { + return this.sub.getProcessed(); + } + + getPending(): number { + return this.sub.getPending(); + } + + getID(): number { + return this.sub.getID(); + } + + getMax(): number | undefined { + return this.sub.getMax(); + } + + get closed(): Promise { + return this.sub.closed; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/ada9ab3a939045d8022ff9a0361109640d05579d.ts b/crates/swc_bundler/tests/.cache/untrusted/ada9ab3a939045d8022ff9a0361109640d05579d.ts new file mode 100644 index 000000000000..45d8b4ebd1c1 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/ada9ab3a939045d8022ff9a0361109640d05579d.ts @@ -0,0 +1,85 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/muxsubscription.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { Request } from "./request.ts"; +import type { Msg } from "./types.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { createInbox } from "./protocol.ts"; +import { isRequestError } from "./msg.ts"; + +export class MuxSubscription { + baseInbox!: string; + reqs: Map; + + constructor() { + this.reqs = new Map(); + } + + size(): number { + return this.reqs.size; + } + + init(prefix?: string): string { + this.baseInbox = `${createInbox(prefix)}.`; + return this.baseInbox; + } + + add(r: Request) { + if (!isNaN(r.received)) { + r.received = 0; + } + this.reqs.set(r.token, r); + } + + get(token: string): Request | undefined { + return this.reqs.get(token); + } + + cancel(r: Request): void { + this.reqs.delete(r.token); + } + + getToken(m: Msg): string | null { + const s = m.subject || ""; + if (s.indexOf(this.baseInbox) === 0) { + return s.substring(this.baseInbox.length); + } + return null; + } + + dispatcher() { + return (err: NatsError | null, m: Msg) => { + const token = this.getToken(m); + if (token) { + const r = this.get(token); + if (r) { + if (err === null && m.headers) { + err = isRequestError(m); + } + r.resolver(err, m); + } + } + }; + } + + close() { + const err = NatsError.errorForCode(ErrorCode.Timeout); + this.reqs.forEach((req) => { + req.resolver(err, {} as Msg); + }); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/afa7059c0a96fef309a902ecebe92dbfa8dca020.ts b/crates/swc_bundler/tests/.cache/untrusted/afa7059c0a96fef309a902ecebe92dbfa8dca020.ts new file mode 100644 index 000000000000..c255d0584643 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/afa7059c0a96fef309a902ecebe92dbfa8dca020.ts @@ -0,0 +1,757 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/parser.ts + + +// deno-lint-ignore-file no-undef +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import type { Dispatcher } from "./queued_iterator.ts"; +import { DenoBuffer } from "./denobuffer.ts"; +import { TD } from "./encoders.ts"; + +export enum Kind { + OK, + ERR, + MSG, + INFO, + PING, + PONG, +} + +export interface ParserEvent { + kind: Kind; + msg?: MsgArg; + data?: Uint8Array; +} + +export function describe(e: ParserEvent): string { + let ks: string; + let data = ""; + + switch (e.kind) { + case Kind.MSG: + ks = "MSG"; + break; + case Kind.OK: + ks = "OK"; + break; + case Kind.ERR: + ks = "ERR"; + data = TD.decode(e.data); + break; + case Kind.PING: + ks = "PING"; + break; + case Kind.PONG: + ks = "PONG"; + break; + case Kind.INFO: + ks = "INFO"; + data = TD.decode(e.data); + } + return `${ks}: ${data}`; +} + +export interface MsgArg { + subject: Uint8Array; + reply?: Uint8Array; + sid: number; + hdr: number; + size: number; +} + +function newMsgArg(): MsgArg { + const ma = {} as MsgArg; + ma.sid = -1; + ma.hdr = -1; + ma.size = -1; + + return ma; +} + +const ASCII_0 = 48; +const ASCII_9 = 57; + +// This is an almost verbatim port of the Go NATS parser +// https://github.com/nats-io/nats.go/blob/master/parser.go +export class Parser { + dispatcher: Dispatcher; + state: State; + as: number; + drop: number; + hdr: number; + ma!: MsgArg; + argBuf?: DenoBuffer; + msgBuf?: DenoBuffer; + + constructor(dispatcher: Dispatcher) { + this.dispatcher = dispatcher; + this.state = State.OP_START; + this.as = 0; + this.drop = 0; + this.hdr = 0; + } + + parse(buf: Uint8Array): void { + // @ts-ignore: on node.js module is a global + if (typeof module !== "undefined" && module.exports) { + // Uint8Array.slice() copies in node it doesn't and it is faster + buf.subarray = buf.slice; + } + + let i: number; + for (i = 0; i < buf.length; i++) { + const b = buf[i]; + switch (this.state) { + case State.OP_START: + switch (b) { + case cc.M: + case cc.m: + this.state = State.OP_M; + this.hdr = -1; + this.ma = newMsgArg(); + break; + case cc.H: + case cc.h: + this.state = State.OP_H; + this.hdr = 0; + this.ma = newMsgArg(); + break; + case cc.P: + case cc.p: + this.state = State.OP_P; + break; + case cc.PLUS: + this.state = State.OP_PLUS; + break; + case cc.MINUS: + this.state = State.OP_MINUS; + break; + case cc.I: + case cc.i: + this.state = State.OP_I; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_H: + switch (b) { + case cc.M: + case cc.m: + this.state = State.OP_M; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_M: + switch (b) { + case cc.S: + case cc.s: + this.state = State.OP_MS; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MS: + switch (b) { + case cc.G: + case cc.g: + this.state = State.OP_MSG; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MSG: + switch (b) { + case cc.SPACE: + case cc.TAB: + this.state = State.OP_MSG_SPC; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MSG_SPC: + switch (b) { + case cc.SPACE: + case cc.TAB: + continue; + default: + this.state = State.MSG_ARG; + this.as = i; + } + break; + case State.MSG_ARG: + switch (b) { + case cc.CR: + this.drop = 1; + break; + case cc.NL: { + const arg: Uint8Array = this.argBuf + ? this.argBuf.bytes() + : buf.subarray(this.as, i - this.drop); + this.processMsgArgs(arg); + this.drop = 0; + this.as = i + 1; + this.state = State.MSG_PAYLOAD; + + // jump ahead with the index. If this overruns + // what is left we fall out and process a split buffer. + i = this.as + this.ma.size - 1; + break; + } + default: + if (this.argBuf) { + this.argBuf.writeByte(b); + } + } + break; + case State.MSG_PAYLOAD: + if (this.msgBuf) { + if (this.msgBuf.length >= this.ma.size) { + const data = this.msgBuf.bytes({ copy: false }); + this.dispatcher.push( + { kind: Kind.MSG, msg: this.ma, data: data }, + ); + this.argBuf = undefined; + this.msgBuf = undefined; + this.state = State.MSG_END; + } else { + let toCopy = this.ma.size - this.msgBuf.length; + const avail = buf.length - i; + + if (avail < toCopy) { + toCopy = avail; + } + + if (toCopy > 0) { + this.msgBuf.write(buf.subarray(i, i + toCopy)); + i = (i + toCopy) - 1; + } else { + this.msgBuf.writeByte(b); + } + } + } else if (i - this.as >= this.ma.size) { + this.dispatcher.push( + { kind: Kind.MSG, msg: this.ma, data: buf.subarray(this.as, i) }, + ); + this.argBuf = undefined; + this.msgBuf = undefined; + this.state = State.MSG_END; + } + break; + case State.MSG_END: + switch (b) { + case cc.NL: + this.drop = 0; + this.as = i + 1; + this.state = State.OP_START; + break; + default: + continue; + } + break; + case State.OP_PLUS: + switch (b) { + case cc.O: + case cc.o: + this.state = State.OP_PLUS_O; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PLUS_O: + switch (b) { + case cc.K: + case cc.k: + this.state = State.OP_PLUS_OK; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PLUS_OK: + switch (b) { + case cc.NL: + this.dispatcher.push({ kind: Kind.OK }); + this.drop = 0; + this.state = State.OP_START; + break; + } + break; + case State.OP_MINUS: + switch (b) { + case cc.E: + case cc.e: + this.state = State.OP_MINUS_E; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MINUS_E: + switch (b) { + case cc.R: + case cc.r: + this.state = State.OP_MINUS_ER; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MINUS_ER: + switch (b) { + case cc.R: + case cc.r: + this.state = State.OP_MINUS_ERR; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MINUS_ERR: + switch (b) { + case cc.SPACE: + case cc.TAB: + this.state = State.OP_MINUS_ERR_SPC; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_MINUS_ERR_SPC: + switch (b) { + case cc.SPACE: + case cc.TAB: + continue; + default: + this.state = State.MINUS_ERR_ARG; + this.as = i; + } + break; + case State.MINUS_ERR_ARG: + switch (b) { + case cc.CR: + this.drop = 1; + break; + case cc.NL: { + let arg: Uint8Array; + if (this.argBuf) { + arg = this.argBuf.bytes(); + this.argBuf = undefined; + } else { + arg = buf.subarray(this.as, i - this.drop); + } + this.dispatcher.push({ kind: Kind.ERR, data: arg }); + this.drop = 0; + this.as = i + 1; + this.state = State.OP_START; + break; + } + default: + if (this.argBuf) { + this.argBuf.write(Uint8Array.of(b)); + } + } + break; + case State.OP_P: + switch (b) { + case cc.I: + case cc.i: + this.state = State.OP_PI; + break; + case cc.O: + case cc.o: + this.state = State.OP_PO; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PO: + switch (b) { + case cc.N: + case cc.n: + this.state = State.OP_PON; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PON: + switch (b) { + case cc.G: + case cc.g: + this.state = State.OP_PONG; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PONG: + switch (b) { + case cc.NL: + this.dispatcher.push({ kind: Kind.PONG }); + this.drop = 0; + this.state = State.OP_START; + break; + } + break; + case State.OP_PI: + switch (b) { + case cc.N: + case cc.n: + this.state = State.OP_PIN; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PIN: + switch (b) { + case cc.G: + case cc.g: + this.state = State.OP_PING; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_PING: + switch (b) { + case cc.NL: + this.dispatcher.push({ kind: Kind.PING }); + this.drop = 0; + this.state = State.OP_START; + break; + } + break; + case State.OP_I: + switch (b) { + case cc.N: + case cc.n: + this.state = State.OP_IN; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_IN: + switch (b) { + case cc.F: + case cc.f: + this.state = State.OP_INF; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_INF: + switch (b) { + case cc.O: + case cc.o: + this.state = State.OP_INFO; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_INFO: + switch (b) { + case cc.SPACE: + case cc.TAB: + this.state = State.OP_INFO_SPC; + break; + default: + throw this.fail(buf.subarray(i)); + } + break; + case State.OP_INFO_SPC: + switch (b) { + case cc.SPACE: + case cc.TAB: + continue; + default: + this.state = State.INFO_ARG; + this.as = i; + } + break; + case State.INFO_ARG: + switch (b) { + case cc.CR: + this.drop = 1; + break; + case cc.NL: { + let arg: Uint8Array; + if (this.argBuf) { + arg = this.argBuf.bytes(); + this.argBuf = undefined; + } else { + arg = buf.subarray(this.as, i - this.drop); + } + this.dispatcher.push({ kind: Kind.INFO, data: arg }); + this.drop = 0; + this.as = i + 1; + this.state = State.OP_START; + break; + } + default: + if (this.argBuf) { + this.argBuf.writeByte(b); + } + } + break; + default: + throw this.fail(buf.subarray(i)); + } + } + + if ( + (this.state === State.MSG_ARG || this.state === State.MINUS_ERR_ARG || + this.state === State.INFO_ARG) && !this.argBuf + ) { + this.argBuf = new DenoBuffer(buf.subarray(this.as, i - this.drop)); + } + + if (this.state === State.MSG_PAYLOAD && !this.msgBuf) { + if (!this.argBuf) { + this.cloneMsgArg(); + } + this.msgBuf = new DenoBuffer(buf.subarray(this.as)); + } + } + + cloneMsgArg() { + const s = this.ma.subject.length; + const r = this.ma.reply ? this.ma.reply.length : 0; + const buf = new Uint8Array(s + r); + buf.set(this.ma.subject); + if (this.ma.reply) { + buf.set(this.ma.reply, s); + } + this.argBuf = new DenoBuffer(buf); + this.ma.subject = buf.subarray(0, s); + if (this.ma.reply) { + this.ma.reply = buf.subarray(s); + } + } + + processMsgArgs(arg: Uint8Array): void { + if (this.hdr >= 0) { + return this.processHeaderMsgArgs(arg); + } + + const args: Uint8Array[] = []; + let start = -1; + for (let i = 0; i < arg.length; i++) { + const b = arg[i]; + switch (b) { + case cc.SPACE: + case cc.TAB: + case cc.CR: + case cc.NL: + if (start >= 0) { + args.push(arg.subarray(start, i)); + start = -1; + } + break; + default: + if (start < 0) { + start = i; + } + } + } + if (start >= 0) { + args.push(arg.subarray(start)); + } + + switch (args.length) { + case 3: + this.ma.subject = args[0]; + this.ma.sid = this.protoParseInt(args[1]); + this.ma.reply = undefined; + this.ma.size = this.protoParseInt(args[2]); + break; + case 4: + this.ma.subject = args[0]; + this.ma.sid = this.protoParseInt(args[1]); + this.ma.reply = args[2]; + this.ma.size = this.protoParseInt(args[3]); + break; + default: + throw this.fail(arg, "processMsgArgs Parse Error"); + } + + if (this.ma.sid < 0) { + throw this.fail(arg, "processMsgArgs Bad or Missing Sid Error"); + } + if (this.ma.size < 0) { + throw this.fail(arg, "processMsgArgs Bad or Missing Size Error"); + } + } + + fail(data: Uint8Array, label = ""): Error { + if (!label) { + label = `parse error [${this.state}]`; + } else { + label = `${label} [${this.state}]`; + } + + return new Error(`${label}: ${TD.decode(data)}`); + } + + processHeaderMsgArgs(arg: Uint8Array): void { + const args: Uint8Array[] = []; + let start = -1; + for (let i = 0; i < arg.length; i++) { + const b = arg[i]; + switch (b) { + case cc.SPACE: + case cc.TAB: + case cc.CR: + case cc.NL: + if (start >= 0) { + args.push(arg.subarray(start, i)); + start = -1; + } + break; + default: + if (start < 0) { + start = i; + } + } + } + if (start >= 0) { + args.push(arg.subarray(start)); + } + + switch (args.length) { + case 4: + this.ma.subject = args[0]; + this.ma.sid = this.protoParseInt(args[1]); + this.ma.reply = undefined; + this.ma.hdr = this.protoParseInt(args[2]); + this.ma.size = this.protoParseInt(args[3]); + break; + case 5: + this.ma.subject = args[0]; + this.ma.sid = this.protoParseInt(args[1]); + this.ma.reply = args[2]; + this.ma.hdr = this.protoParseInt(args[3]); + this.ma.size = this.protoParseInt(args[4]); + break; + default: + throw this.fail(arg, "processHeaderMsgArgs Parse Error"); + } + + if (this.ma.sid < 0) { + throw this.fail(arg, "processHeaderMsgArgs Bad or Missing Sid Error"); + } + if (this.ma.hdr < 0 || this.ma.hdr > this.ma.size) { + throw this.fail( + arg, + "processHeaderMsgArgs Bad or Missing Header Size Error", + ); + } + if (this.ma.size < 0) { + throw this.fail(arg, "processHeaderMsgArgs Bad or Missing Size Error"); + } + } + + protoParseInt(a: Uint8Array): number { + if (a.length === 0) { + return -1; + } + let n = 0; + for (let i = 0; i < a.length; i++) { + if (a[i] < ASCII_0 || a[i] > ASCII_9) { + return -1; + } + n = n * 10 + (a[i] - ASCII_0); + } + return n; + } +} + +export enum State { + OP_START = 0, + OP_PLUS, + OP_PLUS_O, + OP_PLUS_OK, + OP_MINUS, + OP_MINUS_E, + OP_MINUS_ER, + OP_MINUS_ERR, + OP_MINUS_ERR_SPC, + MINUS_ERR_ARG, + OP_M, + OP_MS, + OP_MSG, + OP_MSG_SPC, + MSG_ARG, + MSG_PAYLOAD, + MSG_END, + OP_H, + OP_P, + OP_PI, + OP_PIN, + OP_PING, + OP_PO, + OP_PON, + OP_PONG, + OP_I, + OP_IN, + OP_INF, + OP_INFO, + OP_INFO_SPC, + INFO_ARG, +} + +enum cc { + CR = "\r".charCodeAt(0), + E = "E".charCodeAt(0), + e = "e".charCodeAt(0), + F = "F".charCodeAt(0), + f = "f".charCodeAt(0), + G = "G".charCodeAt(0), + g = "g".charCodeAt(0), + H = "H".charCodeAt(0), + h = "h".charCodeAt(0), + I = "I".charCodeAt(0), + i = "i".charCodeAt(0), + K = "K".charCodeAt(0), + k = "k".charCodeAt(0), + M = "M".charCodeAt(0), + m = "m".charCodeAt(0), + MINUS = "-".charCodeAt(0), + N = "N".charCodeAt(0), + n = "n".charCodeAt(0), + NL = "\n".charCodeAt(0), + O = "O".charCodeAt(0), + o = "o".charCodeAt(0), + P = "P".charCodeAt(0), + p = "p".charCodeAt(0), + PLUS = "+".charCodeAt(0), + R = "R".charCodeAt(0), + r = "r".charCodeAt(0), + S = "S".charCodeAt(0), + s = "s".charCodeAt(0), + SPACE = " ".charCodeAt(0), + TAB = "\t".charCodeAt(0), +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/b8f1d17ce20eb1c3baec121508b120aab05a8ee9.ts b/crates/swc_bundler/tests/.cache/untrusted/b8f1d17ce20eb1c3baec121508b120aab05a8ee9.ts new file mode 100644 index 000000000000..069827237414 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/b8f1d17ce20eb1c3baec121508b120aab05a8ee9.ts @@ -0,0 +1,242 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.ws/v1.0.1/src/ws_transport.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { + ConnectionOptions, + Deferred, + Server, + ServerInfo, + Transport, +} from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/internal_mod.ts"; +import { + checkOptions, + DataBuffer, + deferred, + delay, + ErrorCode, + extractProtocolMessage, + INFO, + NatsError, + render, +} from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/internal_mod.ts"; + +const VERSION = "1.0.1"; +const LANG = "nats.ws"; + +export class WsTransport implements Transport { + version: string; + lang: string; + closeError?: Error; + connected: boolean; + private done: boolean; + // @ts-ignore: expecting global WebSocket + private socket: WebSocket; + private options!: ConnectionOptions; + socketClosed: boolean; + encrypted: boolean; + peeked: boolean; + + yields: Uint8Array[]; + signal: Deferred; + private closedNotification: Deferred; + + constructor() { + this.version = VERSION; + this.lang = LANG; + this.connected = false; + this.done = false; + this.socketClosed = false; + this.encrypted = false; + this.peeked = false; + this.yields = []; + this.signal = deferred(); + this.closedNotification = deferred(); + } + + connect( + server: Server, + options: ConnectionOptions, + ): Promise { + const connected = false; + const connLock = deferred(); + + // ws client doesn't support TLS setting + if (options.tls) { + connLock.reject(new NatsError("tls", ErrorCode.InvalidOption)); + return connLock; + } + + this.options = options; + const u = server.src; + this.encrypted = u.indexOf("wss://") === 0; + this.socket = new WebSocket(u); + this.socket.binaryType = "arraybuffer"; + + this.socket.onopen = () => { + // we don't do anything here... + }; + + this.socket.onmessage = (me: MessageEvent) => { + this.yields.push(new Uint8Array(me.data)); + if (this.peeked) { + this.signal.resolve(); + return; + } + const t = DataBuffer.concat(...this.yields); + const pm = extractProtocolMessage(t); + if (pm) { + const m = INFO.exec(pm); + if (!m) { + if (options.debug) { + console.error("!!!", render(t)); + } + connLock.reject(new Error("unexpected response from server")); + return; + } + try { + const info = JSON.parse(m[1]) as ServerInfo; + checkOptions(info, this.options); + this.peeked = true; + this.connected = true; + this.signal.resolve(); + connLock.resolve(); + } catch (err) { + connLock.reject(err); + return; + } + } + }; + + // @ts-ignore: CloseEvent is provided in browsers + this.socket.onclose = (evt: CloseEvent) => { + this.socketClosed = true; + let reason: Error | undefined; + if (this.done) return; + if (!evt.wasClean) { + reason = new Error(evt.reason); + } + this._closed(reason); + }; + + // @ts-ignore: signature can be any + this.socket.onerror = (e: ErrorEvent | Event): void => { + const evt = e as ErrorEvent; + const err = new NatsError( + evt.message, + ErrorCode.Unknown, + new Error(evt.error), + ); + if (!connected) { + connLock.reject(err); + } else { + this._closed(err); + } + }; + return connLock; + } + + disconnect(): void { + this._closed(undefined, true); + } + + private async _closed(err?: Error, internal = true): Promise { + if (!this.connected) return; + if (this.done) return; + this.closeError = err; + if (!err) { + while (!this.socketClosed && this.socket.bufferedAmount > 0) { + console.log(this.socket.bufferedAmount); + await delay(100); + } + } + this.done = true; + try { + // 1002 endpoint error, 1000 is clean + this.socket.close(err ? 1002 : 1000, err ? err.message : undefined); + } catch (err) { + // ignore this + } + if (internal) { + this.closedNotification.resolve(err); + } + } + + get isClosed(): boolean { + return this.done; + } + + [Symbol.asyncIterator]() { + return this.iterate(); + } + + async *iterate(): AsyncIterableIterator { + while (true) { + if (this.yields.length === 0) { + await this.signal; + } + const yields = this.yields; + this.yields = []; + for (let i = 0; i < yields.length; i++) { + if (this.options.debug) { + console.info(`> ${render(yields[i])}`); + } + yield yields[i]; + } + // yielding could have paused and microtask + // could have added messages. Prevent allocations + // if possible + if (this.done) { + break; + } else if (this.yields.length === 0) { + yields.length = 0; + this.yields = yields; + this.signal = deferred(); + } + } + } + + isEncrypted(): boolean { + return this.connected && this.encrypted; + } + + send(frame: Uint8Array): Promise { + if (this.done) { + return Promise.resolve(); + } + try { + this.socket.send(frame.buffer); + if (this.options.debug) { + console.info(`< ${render(frame)}`); + } + return Promise.resolve(); + } catch (err) { + if (this.options.debug) { + console.error(`!!! ${render(frame)}: ${err}`); + } + return Promise.reject(err); + } + } + + close(err?: Error | undefined): Promise { + return this._closed(err, false); + } + + closed(): Promise { + return this.closedNotification; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/beeff4b61b8d756cab182585f34923fe63015859.ts b/crates/swc_bundler/tests/.cache/untrusted/beeff4b61b8d756cab182585f34923fe63015859.ts new file mode 100644 index 000000000000..ad092a4c23a5 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/beeff4b61b8d756cab182585f34923fe63015859.ts @@ -0,0 +1,123 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/queued_iterator.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Deferred, deferred } from "./util.ts"; +import { ErrorCode, NatsError } from "./error.ts"; + +export interface Dispatcher { + push(v: T): void; +} + +export type DispatchedFn = (data: T | null) => void; + +export interface QueuedIterator extends Dispatcher { + [Symbol.asyncIterator](): AsyncIterator; + stop(err?: Error): void; + getProcessed(): number; + getPending(): number; + getReceived(): number; +} + +export class QueuedIteratorImpl implements QueuedIterator { + inflight: number; + processed: number; + received: number; // this is updated by the protocol + protected noIterator: boolean; + protected iterClosed: Deferred; + protected done: boolean; + private signal: Deferred; + private yields: T[]; + dispatchedFn?: DispatchedFn; + private err?: Error; + + constructor() { + this.inflight = 0; + this.processed = 0; + this.received = 0; + this.noIterator = false; + this.done = false; + this.signal = deferred(); + this.yields = []; + this.iterClosed = deferred(); + } + + [Symbol.asyncIterator]() { + return this.iterate(); + } + + push(v: T): void { + if (this.done) { + return; + } + this.yields.push(v); + this.signal.resolve(); + } + + async *iterate(): AsyncIterableIterator { + if (this.noIterator) { + throw new NatsError("unsupported iterator", ErrorCode.ApiError); + } + while (true) { + if (this.yields.length === 0) { + await this.signal; + } + if (this.err) { + throw this.err; + } + const yields = this.yields; + this.inflight = yields.length; + this.yields = []; + for (let i = 0; i < yields.length; i++) { + this.processed++; + yield yields[i]; + if (this.dispatchedFn && yields[i]) { + this.dispatchedFn(yields[i]); + } + this.inflight--; + } + // yielding could have paused and microtask + // could have added messages. Prevent allocations + // if possible + if (this.done) { + break; + } else if (this.yields.length === 0) { + yields.length = 0; + this.yields = yields; + this.signal = deferred(); + } + } + } + + stop(err?: Error): void { + this.err = err; + this.done = true; + this.signal.resolve(); + this.iterClosed.resolve(); + } + + getProcessed(): number { + return this.noIterator ? this.received : this.processed; + } + + getPending(): number { + return this.yields.length + this.inflight; + } + + getReceived(): number { + return this.received; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/c5e033443d6562214fafcf58cf5686b06dbe18cd.ts b/crates/swc_bundler/tests/.cache/untrusted/c5e033443d6562214fafcf58cf5686b06dbe18cd.ts new file mode 100644 index 000000000000..42f0238c2c28 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/c5e033443d6562214fafcf58cf5686b06dbe18cd.ts @@ -0,0 +1,165 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/authenticator.ts + + +/* + * Copyright 2020 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { nkeys } from "./nkeys.ts"; +import type { ConnectionOptions } from "./types.ts"; +import { ErrorCode, NatsError } from "./mod.ts"; +import { TD, TE } from "./encoders.ts"; + +export type NoAuth = void; + +export interface TokenAuth { + "auth_token": string; +} + +export interface UserPass { + user: string; + pass?: string; +} + +export interface NKeyAuth { + nkey: string; + sig: string; +} + +export interface JwtAuth { + jwt: string; + nkey?: string; + sig?: string; +} + +type Auth = NoAuth | TokenAuth | UserPass | NKeyAuth | JwtAuth; + +/** + * Authenticator is an interface that returns credentials + */ +export interface Authenticator { + (nonce?: string): Auth; +} + +export function buildAuthenticator( + opts: ConnectionOptions, +): Authenticator { + // jwtAuthenticator is created by the user, since it + // will require possibly reading files which + // some of the clients are simply unable to do + if (opts.authenticator) { + return opts.authenticator; + } + if (opts.token) { + return tokenFn(opts.token); + } + if (opts.user) { + return passFn(opts.user, opts.pass); + } + return noAuthFn(); +} + +export function noAuthFn(): Authenticator { + return (): NoAuth => { + return; + }; +} + +/** + * Returns a user/pass authenticator + * @param { string }user + * @param {string } pass + * @return {UserPass} + */ +function passFn(user: string, pass?: string): Authenticator { + return (): UserPass => { + return { user, pass }; + }; +} + +/** + * Returns a token authenticator + * @param {string } token + * @return {TokenAuth} + */ +function tokenFn(token: string): Authenticator { + return (): TokenAuth => { + return { auth_token: token }; + }; +} + +/** + * Returns an nkey authenticator that returns a public key + * @param {Uint8Array | (() => Uint8Array)} seed + * @return {NKeyAuth} + */ +export function nkeyAuthenticator( + seed?: Uint8Array | (() => Uint8Array), +): Authenticator { + return (nonce?: string): NKeyAuth => { + seed = typeof seed === "function" ? seed() : seed; + const kp = seed ? nkeys.fromSeed(seed) : undefined; + const nkey = kp ? kp.getPublicKey() : ""; + const challenge = TE.encode(nonce || ""); + const sigBytes = kp !== undefined && nonce ? kp.sign(challenge) : undefined; + const sig = sigBytes ? nkeys.encode(sigBytes) : ""; + return { nkey, sig }; + }; +} + +/** + * Returns a jwt authenticator. If a seed is provided, the public + * key, and signature are calculated. Note if a signature is provided + * the returned value should be a base64 encoded string. + * + * @return {JwtAuth} + * @param ajwt + * @param seed + */ +export function jwtAuthenticator( + ajwt: string | (() => string), + seed?: Uint8Array | (() => Uint8Array), +): Authenticator { + return ( + nonce?: string, + ): JwtAuth => { + const jwt = typeof ajwt === "function" ? ajwt() : ajwt; + const fn = nkeyAuthenticator(seed); + const { nkey, sig } = fn(nonce) as NKeyAuth; + return { jwt, nkey, sig }; + }; +} + +/** + * Returns a jwt authenticator configured from the specified creds file contents. + * @param creds + * @returns {JwtAuth} + */ +export function credsAuthenticator(creds: Uint8Array): Authenticator { + const CREDS = + /\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/ig; + const s = TD.decode(creds); + // get the JWT + let m = CREDS.exec(s); + if (!m) { + throw NatsError.errorForCode(ErrorCode.BadCreds); + } + const jwt = m[1].trim(); + // get the nkey + m = CREDS.exec(s); + if (!m) { + throw NatsError.errorForCode(ErrorCode.BadCreds); + } + const seed = TE.encode(m[1].trim()); + return jwtAuthenticator(jwt, seed); +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/c60b8f9bffc36c678481a1e1a166ed6a04105d37.ts b/crates/swc_bundler/tests/.cache/untrusted/c60b8f9bffc36c678481a1e1a166ed6a04105d37.ts new file mode 100644 index 000000000000..a9319f6b9ded --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/c60b8f9bffc36c678481a1e1a166ed6a04105d37.ts @@ -0,0 +1,129 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/options.ts + + +/* +* Copyright 2021 The NATS Authors +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { extend } from "./util.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { + ConnectionOptions, + DEFAULT_HOST, + DEFAULT_JITTER, + DEFAULT_JITTER_TLS, + DEFAULT_MAX_PING_OUT, + DEFAULT_MAX_RECONNECT_ATTEMPTS, + DEFAULT_PING_INTERVAL, + DEFAULT_RECONNECT_TIME_WAIT, + ServerInfo, +} from "./types.ts"; +import { buildAuthenticator } from "./authenticator.ts"; +import { defaultPort } from "./transport.ts"; +import { createInbox } from "./mod.ts"; + +export function defaultOptions(): ConnectionOptions { + return { + maxPingOut: DEFAULT_MAX_PING_OUT, + maxReconnectAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS, + noRandomize: false, + pedantic: false, + pingInterval: DEFAULT_PING_INTERVAL, + reconnect: true, + reconnectJitter: DEFAULT_JITTER, + reconnectJitterTLS: DEFAULT_JITTER_TLS, + reconnectTimeWait: DEFAULT_RECONNECT_TIME_WAIT, + tls: undefined, + verbose: false, + waitOnFirstConnect: false, + } as ConnectionOptions; +} + +export function parseOptions(opts?: ConnectionOptions): ConnectionOptions { + const dhp = `${DEFAULT_HOST}:${defaultPort()}`; + opts = opts || { servers: [dhp] }; + if (opts.port) { + opts.servers = [`${DEFAULT_HOST}:${opts.port}`]; + } + if (typeof opts.servers === "string") { + opts.servers = [opts.servers]; + } + if (opts.servers && opts.servers.length === 0) { + opts.servers = [dhp]; + } + const options = extend(defaultOptions(), opts); + + // tokens don't get users + if (opts.user && opts.token) { + throw NatsError.errorForCode(ErrorCode.BadAuthentication); + } + + // if authenticator, no other options allowed + if ( + opts.authenticator && ( + opts.token || opts.user || opts.pass + ) + ) { + throw NatsError.errorForCode(ErrorCode.BadAuthentication); + } + options.authenticator = buildAuthenticator(options); + + ["reconnectDelayHandler", "authenticator"].forEach((n) => { + if (options[n] && typeof options[n] !== "function") { + throw new NatsError( + `${n} option should be a function`, + ErrorCode.NotFunction, + ); + } + }); + + if (!options.reconnectDelayHandler) { + options.reconnectDelayHandler = () => { + let extra = options.tls + ? options.reconnectJitterTLS + : options.reconnectJitter; + if (extra) { + extra++; + extra = Math.floor(Math.random() * extra); + } + return options.reconnectTimeWait + extra; + }; + } + + if (options.inboxPrefix) { + try { + createInbox(options.inboxPrefix); + } catch (err) { + throw new NatsError(err.message, ErrorCode.ApiError); + } + } + + return options; +} + +export function checkOptions(info: ServerInfo, options: ConnectionOptions) { + const { proto, tls_required: tlsRequired } = info; + if ((proto === undefined || proto < 1) && options.noEcho) { + throw new NatsError("noEcho", ErrorCode.ServerOptionNotAvailable); + } + if (options.tls && !tlsRequired) { + throw new NatsError("tls", ErrorCode.ServerOptionNotAvailable); + } +} + +export function checkUnsupportedOption(prop: string, v?: string) { + if (v) { + throw new NatsError(prop, ErrorCode.InvalidOption); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/cc78116fed8e72fa1ed3d969831ae9cfd1733ce6.ts b/crates/swc_bundler/tests/.cache/untrusted/cc78116fed8e72fa1ed3d969831ae9cfd1733ce6.ts new file mode 100644 index 000000000000..50e103dbc650 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/cc78116fed8e72fa1ed3d969831ae9cfd1733ce6.ts @@ -0,0 +1,204 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/util.ts + + +/* + * Copyright 2018-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// deno-lint-ignore-file no-explicit-any +import { DataBuffer } from "./databuffer.ts"; +import { ErrorCode, NatsError } from "./error.ts"; +import { TD } from "./encoders.ts"; + +export const CR_LF = "\r\n"; +export const CR_LF_LEN = CR_LF.length; +export const CRLF = DataBuffer.fromAscii(CR_LF); +export const CR = new Uint8Array(CRLF)[0]; // 13 +export const LF = new Uint8Array(CRLF)[1]; // 10 + +export function isUint8Array(a: unknown): boolean { + return a instanceof Uint8Array; +} + +export function protoLen(ba: Uint8Array): number { + for (let i = 0; i < ba.length; i++) { + const n = i + 1; + if (ba.byteLength > n && ba[i] === CR && ba[n] === LF) { + return n + 1; + } + } + return -1; +} + +export function extractProtocolMessage(a: Uint8Array): string { + // protocol messages are ascii, so Uint8Array + const len = protoLen(a); + if (len) { + const ba = new Uint8Array(a); + const out = ba.slice(0, len); + return TD.decode(out); + } + return ""; +} + +export function extend(a: any, ...b: any[]): any { + for (let i = 0; i < b.length; i++) { + const o = b[i]; + Object.keys(o).forEach(function (k) { + a[k] = o[k]; + }); + } + return a; +} + +export interface Pending { + pending: number; + write: (c: number) => void; + wrote: (c: number) => void; + err: (err: Error) => void; + close: () => void; + promise: () => Promise; + resolved: boolean; + done: boolean; +} + +export function pending(): Pending { + const v = {} as Pending; + const promise = new Promise((resolve) => { + v.promise = () => { + return promise; + }; + v.write = (c: number) => { + if (v.resolved) { + return; + } + v.pending += c; + }; + v.wrote = (c: number) => { + if (v.resolved) { + return; + } + v.pending -= c; + if (v.done && 0 >= v.pending) { + resolve(); + } + }; + v.close = () => { + v.done = true; + if (v.pending === 0) { + resolve(); + } + }; + v.err = () => { + v.pending = 0; + v.resolved = true; + v.close(); + }; + }); + return v; +} + +export function render(frame: Uint8Array): string { + const cr = "␍"; + const lf = "␊"; + return TD.decode(frame) + .replace(/\n/g, lf) + .replace(/\r/g, cr); +} + +export interface Timeout extends Promise { + cancel: () => void; +} + +export function timeout(ms: number): Timeout { + let methods; + let timer: number; + const p = new Promise((resolve, reject) => { + const cancel = (): void => { + if (timer) { + clearTimeout(timer); + } + }; + methods = { cancel }; + // @ts-ignore: node is not a number + timer = setTimeout(() => { + reject(NatsError.errorForCode(ErrorCode.Timeout)); + }, ms); + }); + // noinspection JSUnusedAssignment + return Object.assign(p, methods) as Timeout; +} + +export function delay(ms = 0): Promise { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, ms); + }); +} + +export interface Deferred extends Promise { + resolve: (value?: T | PromiseLike) => void; + //@ts-ignore: tsc guard + reject: (reason?: any) => void; +} + +export function deferred(): Deferred { + let methods = {}; + const p = new Promise((resolve, reject): void => { + methods = { resolve, reject }; + }); + return Object.assign(p, methods) as Deferred; +} + +export function shuffle(a: T[]): T[] { + for (let i = a.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [a[i], a[j]] = [a[j], a[i]]; + } + return a; +} + +export class Perf { + timers: Map; + measures: Map; + + constructor() { + this.timers = new Map(); + this.measures = new Map(); + } + + mark(key: string) { + this.timers.set(key, Date.now()); + } + + measure(key: string, startKey: string, endKey: string) { + const s = this.timers.get(startKey); + if (s === undefined) { + throw new Error(`${startKey} is not defined`); + } + const e = this.timers.get(endKey); + if (e === undefined) { + throw new Error(`${endKey} is not defined`); + } + this.measures.set(key, e - s); + } + + getEntries(): { name: string; duration: number }[] { + const values: { name: string; duration: number }[] = []; + this.measures.forEach((v, k) => { + values.push({ name: k, duration: v }); + }); + return values; + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/d730dbd8ba72e8a84422ed0fac15a64fa3fe06e3.ts b/crates/swc_bundler/tests/.cache/untrusted/d730dbd8ba72e8a84422ed0fac15a64fa3fe06e3.ts new file mode 100644 index 000000000000..005ef0c63d17 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/d730dbd8ba72e8a84422ed0fac15a64fa3fe06e3.ts @@ -0,0 +1,94 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/heartbeats.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Deferred, deferred } from "./util.ts"; +import { DebugEvents, Status } from "./types.ts"; + +export interface PH { + flush(p?: Deferred): Promise; + disconnect(): void; + dispatchStatus(status: Status): void; +} + +export class Heartbeat { + ph: PH; + interval: number; + maxOut: number; + timer?: number; + pendings: Promise[]; + + constructor(ph: PH, interval: number, maxOut: number) { + this.ph = ph; + this.interval = interval; + this.maxOut = maxOut; + this.pendings = []; + } + + // api to start the heartbeats, since this can be + // spuriously called from dial, ensure we don't + // leak timers + start() { + this.cancel(); + this._schedule(); + } + + // api for canceling the heartbeats, if stale is + // true it will initiate a client disconnect + cancel(stale?: boolean) { + if (this.timer) { + clearTimeout(this.timer); + this.timer = undefined; + } + this._reset(); + if (stale) { + this.ph.disconnect(); + } + } + + _schedule() { + // @ts-ignore: node is not a number - we treat this opaquely + this.timer = setTimeout(() => { + this.ph.dispatchStatus( + { type: DebugEvents.PingTimer, data: `${this.pendings.length + 1}` }, + ); + if (this.pendings.length === this.maxOut) { + this.cancel(true); + return; + } + const ping = deferred(); + this.ph.flush(ping) + .then(() => { + this._reset(); + }) + .catch(() => { + // we disconnected - pongs were rejected + this.cancel(); + }); + this.pendings.push(ping); + this._schedule(); + }, this.interval); + } + + _reset() { + // clear pendings after resolving them + this.pendings = this.pendings.filter((p) => { + const d = p as Deferred; + d.resolve(); + return false; + }); + } +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/dea4c4785f1ce7babd902f2aa6132781e1fe3c6c.ts b/crates/swc_bundler/tests/.cache/untrusted/dea4c4785f1ce7babd902f2aa6132781e1fe3c6c.ts new file mode 100644 index 000000000000..f8d397a32d71 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/dea4c4785f1ce7babd902f2aa6132781e1fe3c6c.ts @@ -0,0 +1,72 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.ws/v1.0.1/src/connect.ts + + +/* + * Copyright 2020-2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + ConnectionOptions, + NatsConnection, + NatsConnectionImpl, + setTransportFactory, + Transport, + TransportFactory, +} from "https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/internal_mod.ts"; + +import { WsTransport } from "./ws_transport.ts"; + +export function wsUrlParseFn(u: string): string { + const ut = /^(.*:\/\/)(.*)/; + if (!ut.test(u)) { + u = `https://${u}`; + } + let url = new URL(u); + const srcProto = url.protocol.toLowerCase(); + if (srcProto !== "https:" && srcProto !== "http") { + u = u.replace(/^(.*:\/\/)(.*)/gm, "$2"); + url = new URL(`http://${u}`); + } + + let protocol; + let port; + const host = url.hostname; + const path = url.pathname; + const search = url.search || ""; + + switch (srcProto) { + case "http:": + case "ws:": + case "nats:": + port = url.port || "80"; + protocol = "ws:"; + break; + default: + port = url.port || "443"; + protocol = "wss:"; + break; + } + return `${protocol}//${host}:${port}${path}${search}`; +} + +export function connect(opts: ConnectionOptions = {}): Promise { + setTransportFactory({ + defaultPort: 443, + urlParseFn: wsUrlParseFn, + factory: (): Transport => { + return new WsTransport(); + }, + } as TransportFactory); + + return NatsConnectionImpl.connect(opts); +} diff --git a/crates/swc_bundler/tests/.cache/untrusted/eeaf6dc3f9b0ce2cbfcf93d376cf373fcf943ccb.ts b/crates/swc_bundler/tests/.cache/untrusted/eeaf6dc3f9b0ce2cbfcf93d376cf373fcf943ccb.ts new file mode 100644 index 000000000000..c339b8a16b77 --- /dev/null +++ b/crates/swc_bundler/tests/.cache/untrusted/eeaf6dc3f9b0ce2cbfcf93d376cf373fcf943ccb.ts @@ -0,0 +1,80 @@ +// Loaded from https://raw.githubusercontent.com/nats-io/nats.deno/v1.0.1/nats-base-client/jslister.ts + + +/* + * Copyright 2021 The NATS Authors + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ApiPaged, ApiPagedRequest, Lister } from "./types.ts"; +import { BaseApiClient } from "./jsbaseclient_api.ts"; + +export type ListerFieldFilter = (v: unknown) => T[]; + +export class ListerImpl implements Lister, AsyncIterable { + err?: Error; + offset: number; + pageInfo: ApiPaged; + subject: string; + jsm: BaseApiClient; + filter: ListerFieldFilter; + + constructor( + subject: string, + filter: ListerFieldFilter, + jsm: BaseApiClient, + ) { + if (!subject) { + throw new Error("subject is required"); + } + this.subject = subject; + this.jsm = jsm; + this.offset = 0; + this.pageInfo = {} as ApiPaged; + this.filter = filter; + } + + async next(): Promise { + if (this.err) { + return []; + } + if (this.pageInfo && this.offset >= this.pageInfo.total) { + return []; + } + + const offset = { offset: this.offset } as ApiPagedRequest; + try { + const r = await this.jsm._request( + this.subject, + offset, + { timeout: this.jsm.timeout }, + ); + this.pageInfo = r as ApiPaged; + const a = this.filter(r); + this.offset += a.length; + return a; + } catch (err) { + this.err = err; + throw err; + } + } + + async *[Symbol.asyncIterator]() { + let page = await this.next(); + while (page.length > 0) { + for (const item of page) { + yield item; + } + page = await this.next(); + } + } +} diff --git a/crates/swc_bundler/tests/deno.rs b/crates/swc_bundler/tests/deno.rs index ee9a8c56478a..f3296e96acd3 100644 --- a/crates/swc_bundler/tests/deno.rs +++ b/crates/swc_bundler/tests/deno.rs @@ -100,62 +100,73 @@ fn oak_6_3_1_example_sse_server() { } #[test] -#[ignore = "Will be fixed by #1264"] #[timeout(60000)] -fn deno_8188_full() { +fn deno_8188_full_and_8481() { run( - "https://raw.githubusercontent.com/nats-io/nats.ws/master/src/mod.ts", + "https://raw.githubusercontent.com/nats-io/nats.ws/v1.0.1/src/mod.ts", &[ - "connect", - "NatsConnectionImpl", - "Nuid", - "nuid", - "ErrorCode", - "NatsError", + "AckPolicy", + "AdvisoryKind", + "Bench", + "Connect", + "DataBuffer", "DebugEvents", + "DeliverPolicy", + "DenoBuffer", + "DiscardPolicy", "Empty", + "ErrorCode", "Events", + "Heartbeat", + "INFO", + "JSONCodec", + "Kind", + "MAX_SIZE", + "Metric", + "MsgHdrsImpl", "MsgImpl", + "MuxSubscription", + "NatsConnectionImpl", + "NatsError", + "Nuid", + "Parser", + "ProtocolHandler", + "ReplayPolicy", + "Request", + "RetentionPolicy", + "State", + "StorageType", + "StringCodec", "SubscriptionImpl", "Subscriptions", - "setTransportFactory", - "setUrlParseFn", - "Connect", + "TD", + "TE", + "TypedSubscription", + "checkOptions", + "checkUnsupportedOption", + "connect", + "consumerOpts", "createInbox", - "INFO", - "ProtocolHandler", + "credsAuthenticator", "deferred", "delay", + "extend", "extractProtocolMessage", - "render", - "timeout", "headers", - "MsgHdrsImpl", - "Heartbeat", - "MuxSubscription", - "DataBuffer", - "checkOptions", - "Request", - "credsAuthenticator", + "isIP", "jwtAuthenticator", + "millis", + "nanos", "nkeyAuthenticator", - "JSONCodec", - "StringCodec", - "QueuedIterator", - "Kind", - "Parser", - "State", - "DenoBuffer", - "MAX_SIZE", + "nkeys", + "nuid", + "parseIP", "readAll", + "render", + "setTransportFactory", + "timeout", + "toJsMsg", "writeAll", - "Bench", - "Metric", - "TD", - "TE", - "isIP", - "parseIP", - "nkeys", ], ); } @@ -333,68 +344,6 @@ fn deno_7288_1() { } #[test] -#[ignore = "Will be fixed by #1264"] -#[timeout(60000)] -fn deno_8481_1() { - run( - "https://raw.githubusercontent.com/nats-io/nats.ws/master/src/mod.ts", - &[ - "Bench", - "Connect", - "DataBuffer", - "DebugEvents", - "DenoBuffer", - "Empty", - "ErrorCode", - "Events", - "Heartbeat", - "INFO", - "JSONCodec", - "Kind", - "MAX_SIZE", - "Metric", - "MsgHdrsImpl", - "MsgImpl", - "MuxSubscription", - "NatsConnectionImpl", - "NatsError", - "Nuid", - "Parser", - "ProtocolHandler", - "QueuedIterator", - "Request", - "State", - "StringCodec", - "SubscriptionImpl", - "Subscriptions", - "TD", - "TE", - "checkOptions", - "connect", - "createInbox", - "credsAuthenticator", - "deferred", - "delay", - "extractProtocolMessage", - "headers", - "isIP", - "jwtAuthenticator", - "nkeyAuthenticator", - "nkeys", - "nuid", - "parseIP", - "readAll", - "render", - "setTransportFactory", - "setUrlParseFn", - "timeout", - "writeAll", - ], - ) -} - -#[test] -#[ignore = "Will be fixed by #1264"] #[timeout(60000)] fn deno_8530() { run("tests/deno/deno-8530/input/entry.ts", &[]) @@ -881,7 +830,6 @@ fn deno_8597() { } #[test] -#[ignore = "Will be fixed by #1264"] #[timeout(60000)] fn deno_8620() { run("tests/deno/deno-8620/entry.ts", &[]) diff --git a/crates/swc_bundler/tests/deno/deno-8530/input/entry.ts b/crates/swc_bundler/tests/deno/deno-8530/input/entry.ts index 42d90154370d..add8ba734209 100644 --- a/crates/swc_bundler/tests/deno/deno-8530/input/entry.ts +++ b/crates/swc_bundler/tests/deno/deno-8530/input/entry.ts @@ -1,5 +1,5 @@ -import Head from "https://deno.land/x/aleph/head.ts"; -import * as Head2 from "https://deno.land/x/aleph/head.ts"; +import Head from "https://deno.land/x/aleph@v0.2.28/head.ts"; +import * as Head2 from "https://deno.land/x/aleph@v0.2.28/head.ts"; console.log(Head, Head2); if (typeof Head !== "function") { throw new Error();