als-render
Advanced tools
Comparing version 0.2.3 to 0.2.4
@@ -10,3 +10,6 @@ const { readdirSync, readFileSync, writeFileSync } = require('fs') | ||
const Require = readFileSync(`${nodeModulesDir}/als-require/require.js`) | ||
const renderConent = readFileSync(join(__dirname,'render.js'),'utf-8').replace(/.*require\(.*\).*?|module.exports.*/g,'') | ||
const renderConent = readFileSync(join(__dirname,'render.js'),'utf-8') | ||
.replace(/.*require\(.*\).*?|module.exports.*/g,'') | ||
const simple = readFileSync(join(nodeModulesDir,'als-simple-css','simple.js')) | ||
const Obj = readFileSync(join(nodeModulesDir,'als-object-serializer','index.js')) | ||
const contents = fileNames.map(filename => { | ||
@@ -17,2 +20,4 @@ if(filename === 'index.js') return '' | ||
}).filter(Boolean); | ||
contents.unshift(Obj) | ||
contents.unshift(simple) | ||
contents.unshift(ReplaceBetween) | ||
@@ -19,0 +24,0 @@ contents.unshift(Require) |
const renderJsx = require('../lib/render-jsx') | ||
const newContext = require('../lib/new-context') | ||
const bind = require('../lib/bind') | ||
const { parse } = require('als-object-serializer') | ||
const Obj = require('als-object-serializer') | ||
const Simple = require('als-simple-css') | ||
@@ -16,3 +16,3 @@ | ||
if(styles.length) { | ||
const simple = new Simple(styles.map((style,i) => ({[`[style${i}]`]:parse(style)}))) | ||
const simple = new Simple(styles.map((style,i) => ({[`[style${i}]`]:Obj.parse(style)}))) | ||
styles = `<style>${simple.stylesheet()}</style>` | ||
@@ -19,0 +19,0 @@ } else styles = '' |
@@ -21,3 +21,3 @@ function newContext() { | ||
componentFn.update = function(newParams,key) {context.update(componentName,newParams,key)} | ||
context.components[componentName] = function(props) { | ||
context.components[componentName] = function(props={}) { | ||
let result = componentFn(props).trim() | ||
@@ -24,0 +24,0 @@ if(result.startsWith('<>')) return result.slice(2,-3) // remove <> and </> |
{ | ||
"name": "als-render", | ||
"version": "0.2.3", | ||
"version": "0.2.4", | ||
"main": "index.js", | ||
@@ -5,0 +5,0 @@ "scripts": { |
const render = (function() { | ||
async function render(path,selector='body') { let styles = [] const context = newContext() const app = new Require(path) await app.getContent() for(const path in app.contents) { app.contents[path] = renderJsx(app.contents[path],styles) } if(styles.length) { const simple = new Simple(styles.map((style,i) => ({[`[style${i}]`]:parse(style)}))) styles = `<style>${simple.stylesheet()}</style>` } else styles = '' const result = app.build({},context,'context') const rawHtml = result()+styles bind(selector,rawHtml,context) } class Require { static contents = {} static async fetch(path, type = 'text') { let response = await fetch(path) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return await response[type]() } static isCyclyc(fullPath, path) { if (Require.contents[fullPath] && Require.contents[fullPath].children.includes(path)) { throw `cyclic dependency between ${path} and ${fullPath}` } } static async getModule(path, context, contextName, modules) { const mod = new Require(path) await mod.getContent() return mod.build(modules, context, contextName) } static getFullPath(path, relative) { const pathParts = path.split('/'); const relativeParts = relative.split('/').slice(0, -1); const fullPathParts = []; for (let part of [...relativeParts, ...pathParts]) { if (part === '..') { if (fullPathParts.length > 0 && fullPathParts[fullPathParts.length - 1] !== '..') fullPathParts.pop(); else fullPathParts.push(part); } else if (part !== '.') fullPathParts.push(part); } let fullPath = fullPathParts.join('/'); return fullPath.endsWith('.js') ? fullPath : fullPath + '.js' } static async getNodeModules(nodeModules, children, content) { if (nodeModules.length === 0) return content for (const { match, modulePath } of nodeModules) { const pkgJsonPath = `/node_modules/${modulePath}/package.json` const exists = await fetch(pkgJsonPath, { method: 'HEAD' }) if (!exists.ok) { console.warn(`The module "${modulePath}" can't be imported and will be replaced with null`) continue } const { main: filename = 'index.js' } = await Require.fetch(pkgJsonPath, 'json') const fullPath = `/node_modules/${modulePath}/${filename}` Require.isCyclyc(fullPath, modulePath) children.push(fullPath); content = content.replace(match, match.replace(modulePath, fullPath)) } return content } static relativePath = location.pathname constructor(path) { this.contents = {} this.path = path this.fullPath = Require.getFullPath(path, Require.relativePath) this.contentReady = false } async getContent() { if (this.contentReady) return this const getContent = async (path) => { if (this.contents[path] !== undefined) return // allready fetched if (!Require.contents[path]) { let content = await Require.fetch(path) const children = [], nodeModules = []; content = content.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm, (match, modulePath) => { if (!modulePath.startsWith('.')) { nodeModules.push({ match, modulePath }) return match } const fullPath = Require.getFullPath(modulePath, path) Require.isCyclyc(fullPath, path) children.push(fullPath); return match.replace(modulePath, fullPath) }); content = await Require.getNodeModules(nodeModules, children, content) Require.contents[path] = { content, children } } const { content, children } = Require.contents[path] this.contents[path] = content for (let childPath of children) { await getContent(childPath) } } await getContent(this.fullPath) this.contentReady = true this.prepareContents() return this } prepareContents() { const newKeys = new Set() const addKeys = (keys) => { keys.forEach(key => { if (!this.contents[key]) return addKeys(Require.contents[key].children) newKeys.add(key) }) } addKeys(Object.keys(this.contents).reverse()) this.keys = Array.from(newKeys) } build(modules = {}, context = {}, contextName = 'context') { function require(path) { return modules[path] || null } this.keys.map(path => { const module = { exports: {} } const params = { module, require, exports: module.exports, [contextName]: context } try { new Function(...Object.keys(params), this.contents[path])(...Object.values(params)) } catch (error) { this.error(error, path) } modules[path] = module.exports }) return modules[this.keys[this.keys.length - 1]] } error(error, path) { const stack = [], contents = Require.contents; const pathes = Object.keys(contents).reverse() function addToStack(curPath) { stack.push(curPath) for (const modPath of pathes) { if (contents[modPath].children.includes(curPath)) { addToStack(` at ${modPath}`) break } } } addToStack(path) const errorsStack = error.stack.split('\n') errorsStack.splice(1, 1, ...stack) error.stack = errorsStack.join('\n') throw error } }; const require = Require.getModule; | ||
async function render(path,selector='body') { let styles = [] const context = newContext() const app = new Require(path) await app.getContent() for(const path in app.contents) { app.contents[path] = renderJsx(app.contents[path],styles) } if(styles.length) { const simple = new Simple(styles.map((style,i) => ({[`[style${i}]`]:Obj.parse(style)}))) styles = `<style>${simple.stylesheet()}</style>` } else styles = '' const result = app.build({},context,'context') const rawHtml = result()+styles bind(selector,rawHtml,context) } class Require { static contents = {} static async fetch(path, type = 'text') { let response = await fetch(path) if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return await response[type]() } static isCyclyc(fullPath, path) { if (Require.contents[fullPath] && Require.contents[fullPath].children.includes(path)) { throw `cyclic dependency between ${path} and ${fullPath}` } } static async getModule(path, context, contextName, modules) { const mod = new Require(path) await mod.getContent() return mod.build(modules, context, contextName) } static getFullPath(path, relative) { const pathParts = path.split('/'); const relativeParts = relative.split('/').slice(0, -1); const fullPathParts = []; for (let part of [...relativeParts, ...pathParts]) { if (part === '..') { if (fullPathParts.length > 0 && fullPathParts[fullPathParts.length - 1] !== '..') fullPathParts.pop(); else fullPathParts.push(part); } else if (part !== '.') fullPathParts.push(part); } let fullPath = fullPathParts.join('/'); return fullPath.endsWith('.js') ? fullPath : fullPath + '.js' } static async getNodeModules(nodeModules, children, content) { if (nodeModules.length === 0) return content for (const { match, modulePath } of nodeModules) { const pkgJsonPath = `/node_modules/${modulePath}/package.json` const exists = await fetch(pkgJsonPath, { method: 'HEAD' }) if (!exists.ok) { console.warn(`The module "${modulePath}" can't be imported and will be replaced with null`) continue } const { main: filename = 'index.js' } = await Require.fetch(pkgJsonPath, 'json') const fullPath = `/node_modules/${modulePath}/${filename}` Require.isCyclyc(fullPath, modulePath) children.push(fullPath); content = content.replace(match, match.replace(modulePath, fullPath)) } return content } static relativePath = location.pathname constructor(path) { this.contents = {} this.path = path this.fullPath = Require.getFullPath(path, Require.relativePath) this.contentReady = false } async getContent() { if (this.contentReady) return this const getContent = async (path) => { if (this.contents[path] !== undefined) return // allready fetched if (!Require.contents[path]) { let content = await Require.fetch(path) const children = [], nodeModules = []; content = content.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm, (match, modulePath) => { if (!modulePath.startsWith('.')) { nodeModules.push({ match, modulePath }) return match } const fullPath = Require.getFullPath(modulePath, path) Require.isCyclyc(fullPath, path) children.push(fullPath); return match.replace(modulePath, fullPath) }); content = await Require.getNodeModules(nodeModules, children, content) Require.contents[path] = { content, children } } const { content, children } = Require.contents[path] this.contents[path] = content for (let childPath of children) { await getContent(childPath) } } await getContent(this.fullPath) this.contentReady = true this.prepareContents() return this } prepareContents() { const newKeys = new Set() const addKeys = (keys) => { keys.forEach(key => { if (!this.contents[key]) return addKeys(Require.contents[key].children) newKeys.add(key) }) } addKeys(Object.keys(this.contents).reverse()) this.keys = Array.from(newKeys) } build(modules = {}, context = {}, contextName = 'context') { function require(path) { return modules[path] || null } this.keys.map(path => { const module = { exports: {} } const params = { module, require, exports: module.exports, [contextName]: context } try { new Function(...Object.keys(params), this.contents[path])(...Object.values(params)) } catch (error) { this.error(error, path) } modules[path] = module.exports }) return modules[this.keys[this.keys.length - 1]] } error(error, path) { const stack = [], contents = Require.contents; const pathes = Object.keys(contents).reverse() function addToStack(curPath) { stack.push(curPath) for (const modPath of pathes) { if (contents[modPath].children.includes(curPath)) { addToStack(` at ${modPath}`) break } } } addToStack(path) const errorsStack = error.stack.split('\n') errorsStack.splice(1, 1, ...stack) error.stack = errorsStack.join('\n') throw error } }; const require = Require.getModule; | ||
const ReplaceBetween = (function() { | ||
class BaseNode { constructor() {this.children = []} get outer() { return this.before + this.inner + this.after } get inner() {return this.children.map(child => child.outer).join('')} set outer(value) {this.inner = value; this.before = ''; this.after = ''} set inner(value) {this.children = []; this.children.push(new TextNode(value,this))} walkNodes(modifiers=[],parent = this) { parent.children.forEach(child => { if(child instanceof BaseNode === false) return this.walkNodes(modifiers,child) this.runModifiers(modifiers,child,true) }); } walkTextNodes(modifiers=[],parent = this) { parent.children.forEach(child => { if(child instanceof BaseNode) this.walkTextNodes(modifiers,child) else this.runModifiers(modifiers,child,false) }); } walk(modifiers=[],parent = this) { parent.children.forEach(child => { const isNode = child instanceof BaseNode if(isNode) this.walk(modifiers,child) this.runModifiers(modifiers,child,isNode) }); } runModifiers(modifiers,child,isNode) { for(const modifier of modifiers) { const result = modifier(child,isNode) if(result === false) return false } } } function buildTree(starts, ends) { if(starts[0].n > ends[0].n) ends.shift() if(starts[starts.length-1].n > ends[ends.length-1].n) starts.pop() if (starts.length !== ends.length) throw new Error(`Parsing error: unmatched tags detected. (${starts.length},${ends.length})`); let pairs = starts.map((start, i) => ({ start, end: ends[i], children: [] })); pairs.forEach((curPair, i) => { for (let k = i; k < pairs.length; k++) { if (curPair.end.n > pairs[k].start.n) { const end = pairs[k].end const curEnd = curPair.end curPair.end = end pairs[k].end = curEnd } } }) pairs.sort((a, b) => a.end.n - b.end.n); pairs.forEach((curPair, i) => { for (let k = i; k < pairs.length; k++) { if (curPair.start.n > pairs[k].start.n && curPair.end.n < pairs[k].end.n) { if (!curPair.level) curPair.level = 0 curPair.level++ pairs[k].children.push(curPair) } } }); function filterPairs(pairs, curLevel = 0) { pairs = pairs.filter(({ level }) => (!level || level <= curLevel)) pairs.forEach(pair => { if (pair.children.length === 0) return pair.children = filterPairs(pair.children, curLevel + 1) }); return pairs } pairs = filterPairs(pairs) return pairs } function find(string, r, add, offset = 0) { const arr = [] while (true) { const match = string.match(r) if (!match) break offset += match.index + 1 const n = add < 0 ? add : add * (match[0].length - 1) arr.push({n:offset + n,length:match[0].length}) string = string.slice(match.index + 1) } return arr } class ReplaceBetween extends BaseNode { constructor(content, startR, endR) { super() if (typeof content !== 'string') throw `Expected 'content' to be a string, but got '${typeof content}'` if (startR instanceof RegExp == false) throw '"startR" should be an instance of RegExp.' if (endR instanceof RegExp == false) throw '"endR" should be an instance of RegExp.' this.content = content this.startR = startR this.endR = endR this.build() } build() { const { content, startR, endR } = this const starts = find(content, startR, -1) const ends = find(content, endR, 1) if(starts.length === 0 || ends.length === 0) return const children = buildTree(starts, ends) if(children.length === 0) return const start = children[0].start.n const end = children[children.length - 1].end.n this.before = start > 0 ? content.slice(0, start) : '' this.after = end < content.length ? content.slice(end, content.length) : '' children.forEach((child,i) => { this.children.push(new Node(this, child, this)) if(i === children.length-1) return const nextStart = children[i+1].start.n const curendEnd = child.end.n if(nextStart !== curendEnd) { this.children.push(new TextNode(content.slice(curendEnd,nextStart),this)) } }); } } class Node extends BaseNode { constructor(root, obj, parent = null) { super() this.parent = parent if(parent) this.index = parent.children.length this.root = root this.addChildren(obj) } addChildren(obj) { const { start, end, children } = obj const root = this.root let curStart = start.n + start.length, curEnd = end.n - end.length this.open = root.content.slice(start.n, curStart) children.forEach((child,i) => { if(child.start.n > curStart) this.children.push(new TextNode(root.content.slice(curStart, child.start.n),this)) this.children.push(new Node(root, child, this)) curStart = child.end.n }); if(curEnd > curStart) this.children.push(new TextNode(root.content.slice(curStart,curEnd),this)) this.close = root.content.slice(curEnd, end.n) return this } get outer() {return this.open + this.inner + this.close} set outer(value) {this.inner = value; this.open = ''; this.close = ''} get prev() {return this.parent ? this.parent.children[this.index - 1] : null} get next() {return this.parent ? this.parent.children[this.index + 1] : null} } class TextNode { constructor(content,parent) { this.outer = content this.parent = parent if(parent) this.index = parent.children.length this.open = '' this.close = '' } get prev() {return this.parent.children[this.index - 1] || null} get next() {return this.parent.children[this.index + 1] || null} } return ReplaceBetween | ||
})() | ||
const Simple = (function() { | ||
let stylesheet function publishRules(rules) { if(!stylesheet) { if (document.styleSheets.length == 0) { let head = document.getElementsByTagName('head')[0] head.insertAdjacentHTML('afterbegin', '<style id="simple-css"></style>') } stylesheet = document.styleSheets[0] } rules.filter(rule => !(rule.startsWith('/*'))) .forEach(rule => { try {stylesheet.insertRule(rule)} catch (error) {console.log(error.message)} }) } | ||
function $(varName, varVal, varVal2) { const docEl = document.documentElement if (varVal == undefined) return getComputedStyle(docEl).getPropertyValue('--' + varName) else if (varVal2 === undefined) docEl.style.setProperty('--' + varName, varVal) else if (varVal2 !== undefined) { let curVal = getComputedStyle(docEl).getPropertyValue('--' + varName) if (curVal == varVal) docEl.style.setProperty('--' + varName, varVal2) else if (curVal == varVal2) docEl.style.setProperty('--' + varName, varVal) } return varVal } const defaultShorts = { a: 'animation', bgc: 'background-color', c: 'color', bg: 'background', bgi: 'background-image', b: 'border', br: 'border-right', bl: 'border-left', bt: 'border-top', bb: 'border-bottom', bc: 'border-color', brc: 'border-right-color', blc: 'border-left-color', btc: 'border-top-color', bbc: 'border-bottom-color', bs: 'border-style', brs: 'border-right-style', bls: 'border-left-style', bts: 'border-top-style', bbs: 'border-bottom-style', bw: 'border-width', brw: 'border-right-width', blw: 'border-left-width', btw: 'border-top-width', bbw: 'border-bottom-width', radius: 'border-radius', o: 'outline', oc: 'outline-color', os: 'outline-style', ow: 'outline-width', maxw: 'max-width', minw: 'min-width', h: 'height', w: 'width', maxh: 'max-height', minh: 'min-height', of: 'overflow', ofx: 'overflow-x', ofy: 'overflow-y', scrollb: 'scroll-behavior', p: 'padding', m: 'margin', pr: 'padding-right', pl: 'padding-left', pt: 'padding-top', pb: 'padding-bottom', mr: 'margin-right', ml: 'margin-left', mt: 'margin-top', mb: 'margin-bottom', d: 'display', flexw: 'flex-wrap', flexg: 'flex-grow', flexdir: 'flex-direction', ai: 'align-items', ac: 'aline-content', jc: 'justify-content', gcols: 'grid-template-columns', grows: 'grid-template-rows', gacols: 'grid-auto-columns', garows: 'grid-auto-rows', areas: 'grid-template-areas', area: 'grid-area', dir: 'direction', textt: 'text-transform', ta: 'text-align', td: 'text-decoration', ws: 'white-space', ww: 'word-wrap', ff: 'font-family', to: 'text-overflow', ls: 'letter-spacing', lh: 'line-height', wb: 'word-break', fv: 'font-variant', fs: 'font-size', fw: 'font-weight', fstyle: 'font-style', f: 'font', pos: 'position', z: 'z-index', tr: 'transform', cur: 'cursor' } function flatStyles(styles,newStyles = {}) { for(let selector in styles) { const rules = styles[selector] if(Array.isArray(rules)) { // it's @media/@keyframes/... newStyles[selector] = rules continue } for(let prop in rules) { let value = rules[prop] if(typeof value === 'object') { // nested styles const nestedSelecor = prop.split(',').map(p => selector.trim().split(',').map(s => s+p).join()).join() flatStyles({[nestedSelecor]:value},newStyles) } else { // prop:value if(!newStyles[selector]) newStyles[selector] = {} newStyles[selector][prop] = value } } } return newStyles } function buildRules(rules, shorts, newRules = {}) { for (let propName in rules) { let propValue = buildPropValue(rules[propName]) propName = shorts[propName] ? shorts[propName] : camelCase(propName) propName = propName.replace(/^\$/, '--') newRules[propName] = propValue } return newRules } function camelCase(v) { return v.split('').map((l,i) => { const last = v[i-1] if(i === 0 || last === ' ' || last == '-' || !(/[A-Z]/.test(l))) return l return '-'+l.toLowerCase() }).join('') } function buildCalc(propValue) { const operations = ['*', '-', '+', '/'] return propValue.replace(/\[(.*?)\]/g, (match, calc) => { return 'calc(' + calc.split('').map((l, i) => { if (!operations.includes(l)) return l if(l === '-' && /[^\d\s]/.test(calc[i+1])) return l if (calc[i - 1] !== ' ') l = ' ' + l if (calc[i + 1] !== ' ') l = l + ' ' return l }).join('') + ')' }) } function getVars(values) { return values.replace(/\$([\w-$]*)(\(\$?([\w-()$]*)\))?/g, (match, name, value) => { value = value ? ',' + getVars(value.replace(/[()]/g, '')) : '' return `var(--${camelCase(name)}${value})` }) } function buildPropValue(propValue) { propValue = propValue.toString().trim() if (/["'].*["']/.test(propValue)) return propValue propValue = buildCalc(propValue) propValue = getVars(propValue) propValue = propValue.replace(/\!/, '!important') return propValue } function getCssRules(styles, space = ' ', n = '\n', s = '') { return styles.map(obj => { if (typeof obj == 'string') return obj.trim() const [selector, props] = Object.entries(obj)[0] return Array.isArray(props) ? `${selector} {${n}${getCssRules(props, space + space, n, space).join(n)}${n}}` : `${s}${selector} {${n}${Object.entries(props).map( ([name, value]) => `${space}${name}:${value}` ).join(`;${n}`)}${n}${s}}` }) } class Simple { constructor(simples = [], shorts = {}) { if (!Array.isArray(simples)) throw new Error('simples parameter should be arrray') if (typeof shorts !== 'object') throw new Error('shorts parameter should be object') this.shorts = Object.assign({}, defaultShorts, shorts); this.styles = [] this.selectors = [] this.buildStyles(simples, this.styles) } buildStyles(simples, styles = []) { simples.forEach(obj => { if (typeof obj === 'string') return this.buildString(obj, styles) if (typeof obj !== 'object' || obj === null) return obj = flatStyles(obj) for (let selector in obj) { const rules = Array.isArray(obj[selector]) ? this.buildStyles(obj[selector]) // @media/@keyframes/... : buildRules(obj[selector], this.shorts) const index = styles.findIndex(obj => obj[selector] !== undefined) if(index >= 0) styles[index][selector] = {...styles[index][selector],...rules} // group by selector else styles.push({ [selector]: rules }) } }); return styles } buildString(string, styles) { string = string.trim() if (string.startsWith('#')) string = '/*' + string.replace(/^\#/, '') + '*/' // It's a comment styles.push(string) } stylesheet(spaces) { const rules = (spaces && typeof spaces === 'number' && spaces > 0) ? getCssRules(this.styles,' '.repeat(spaces),'\n') : getCssRules(this.styles,'','') return rules.join('\n') } publish() { | ||
publishRules(getCssRules(this.styles,'','')) | ||
} | ||
} | ||
Simple.$ = $ | ||
return Simple | ||
})() | ||
class Obj { static recursiveName = 'recursiveReference' static stringify(obj, spaces = 0) { const space = ' '.repeat(spaces) const n = space ? '\n' : '', hash = new WeakMap(); function stringify(obj, curSpace, upSpace = '',path) { if (hash.has(obj)) return `function ${Obj.recursiveName}(self) {return ${hash.get(obj)}}` if (['number', 'boolean', 'undefined'].includes(typeof obj) || obj === null) return String(obj); if (typeof obj === 'string') return `"${obj.replace(/"/g, '\\"')}"`; if (obj instanceof Date) return `new Date("${obj}")`; if (obj instanceof RegExp) return `new RegExp("${obj.source}", "${obj.flags}")`; hash.set(obj, path); if (typeof obj === 'function') return obj.toString(); let result, end = n + upSpace const recursive = (item,k) => stringify(item, curSpace + space, curSpace,path+`[${k}]`) if (Array.isArray(obj)) { result = `[${n}${obj.map((item,i) => curSpace + recursive(item,i)).join(',' + n)}${end}]` } else { if (obj instanceof Set) result = 'new Set(' + recursive(Array.from(obj)) + ')' else if (obj instanceof Map) result = 'new Map(' + recursive(Array.from(obj.entries())) + ')' else if (obj instanceof Error) result = `new Error('${obj.message}')` else result = `{${n}${Object.entries(obj).map(([key, value]) => { return `${curSpace}"${key}":${recursive(value,`'${key}'`)}` }).join(',' + n)}${end}}`; } return result; } let result = stringify(obj, space, '','self') return result } static parse(string) { const self = new Function(`return ${string}`)() function updateRecursive(obj) { for(let key in obj) { if(typeof obj[key] === 'function' && obj[key].name === Obj.recursiveName) obj[key] = obj[key](self) else if(obj[key] !== null && typeof obj[key] === 'object') updateRecursive(obj[key]) } } updateRecursive(self) return self } } try { module.exports = Obj; } catch (error) { } | ||
function bind(selector,rawHtml,context,update = true) { function getElement(selector) { const element = document.querySelector(selector) if(!element) throw `The element with selector "${selector}" not exists` return element } if(update) getElement(selector).innerHTML = rawHtml context.actions.forEach(({ fn, id, event }) => { getElement('#'+id).addEventListener(event, fn); }); context.actions = [] } function newContext() { const context = { components: {}, actions: [], counter: 0, update: (componentName,newParams, key) => { const component = context.components[componentName] const selector = `[component=${ componentName}]`; if (key) selector += `[key=${key}]`; const element = document.querySelector(selector) element.outerHTML = component(newParams); context.actions = context.actions.map(({ fn, id, event }) => { const element = document.getElementById(id) if(element) element.addEventListener(event, fn); return false; }).filter(Boolean); } } context.buildComponent = function(componentFn,componentName) { if(context.components[componentName]) return componentFn.update = function(newParams,key) {context.update(componentName,newParams,key)} context.components[componentName] = function(props) { let result = componentFn(props).trim() if(result.startsWith('<>')) return result.slice(2,-3) // remove <> and </> result = result.replace(/^<\w*/,(tag) => { key = props.key ? ` key="${props.key}"` : '' return tag + ` component="${componentName}"${key}` }) return result } context.components[componentName].update = function(newParams,key) {context.update(componentName,newParams,key)} } return context } const removeComments = str => str.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//gm, '') function renderJsx(content,styles) { const transformer = new ReplaceBetween(content, new RegExp(/\(\s*?</), new RegExp(/\>\s*?\)/)) if (transformer.children.length === 0) return content transformer.before = removeComments(transformer.before) transformer.after = removeComments(transformer.after) const componentNames = [] transformer.walkNodes([node => replaceComponents(node, componentNames)]) transformer.children.forEach(node => replaceActions(node,styles)); const fns = componentNames.map(cName => `context.buildComponent(${cName},'${cName}')`).join('\n') content = transformer.outer .replace(/className\=/g, 'class=') .replace(/^\s*$(?:\r\n?|\n)/gm, '') return content + '\n' + fns }; function buildAction(event, value) { const obj = `{event:'${event}',fn:${value},id:'action'+(context.counter++).toString()}` return '"${' + `context.actions.push(${obj})` + ` ? '' : ''}" id="\${'action'+(context.counter-1).toString()}" ` } function getBefore(node) { if (node.prev) return { beforeNode: node.prev, before: node.prev.outer.trim() } if (node.parent.before) return { beforeNode: node.parent, before: node.parent.before.trim() } return getBefore(node.parent) } function replaceActions(node, styles) { if (!node.inner) return const varTransformer = new ReplaceBetween(node.inner, /\{/, /\}/) if (varTransformer.children.length === 0) return varTransformer.walkNodes([node => { const outer = node.outer if (node.inner.startsWith('...')) return // Spreaded variable if (outer.startsWith('{/*') && outer.endsWith('*/}')) { // comment node.outer = ''; return; } const { before, beforeNode } = getBefore(node) const lastChar = before[before.length - 1]; if (lastChar === '$') return if (before[before.length - 2] + lastChar === '=>') return // Arrow function body if (lastChar === '(' || lastChar === ',') return // variable is part of object if (lastChar === '=') { let propName = '', i = before.length - 2 while (i >= 0) { propName = before[i] + propName i-- if (before[i] === ' ') break } if (propName === 'style') { if(node.parent.open === '{' && node.parent.close === '}') { styles.push(outer) if(beforeNode.before) beforeNode.before = beforeNode.before.slice(0,-1)+String(styles.length-1) node.parent.outer = '' return } } if (propName.startsWith('on')) { node.outer = buildAction(propName.split('on')[1].toLowerCase(), node.inner) } else node.outer = '"${' + `${node.inner}}"` } else if(node.open === '{') { // if((node.prev ? node.prev.outer : node.parent.before).slice(-1) === '$') return node.open = '${' } }]) node.inner = varTransformer.outer } function replaceComponents(node,componentNames) { const inner = '<'+node.inner.trim()+'>' node.open = '`'; node.close = '`'; node.inner = inner.replace(/\<([A-Z]\w*)[\s\S]*?\/\>/g,(m,cName,index) => { componentNames.push(cName) let props = [], restParams = ''; m.replace(/(\w*)\s*?\=\"([\s\S]*?)\"/g, (m1, name, val) => {props.push(`${name}:"${val}"`)}) m.replace(/(\w*)\s*?\=\s*?\{\{?(.*?)\}?\}/g, (m1, name, val) => {props.push(`${name}:${val}`)}) m.replace(/\{(\.\.\..*?)\}/, (m1, varName) => {props.push(varName)}) const code = `context.components.${cName}({${props.join()}${restParams}})` if(index === 0 && m.length === inner.length) { node.open = ''; node.close = ''; return code } return '${'+code+'}' }) .replace(/(checked|disabled)\=\{([\s\S]*?)\}/g,(m,prop,condition) => '${'+`${condition} ? '${prop}' : '' `+'}') .replace(/\/>/g, '>') } return render | ||
})() |
@@ -1,1 +0,1 @@ | ||
let render=function(){class h{static contents={};static async fetch(e,t="text"){e=await fetch(e);if(e.ok)return e[t]();throw new Error("HTTP error! status: "+e.status)}static isCyclyc(e,t){if(h.contents[e]&&h.contents[e].children.includes(t))throw`cyclic dependency between ${t} and `+e}static async getModule(e,t,n,r){e=new h(e);return await e.getContent(),e.build(r,t,n)}static getFullPath(e,t){var n,e=e.split("/"),r=[];for(n of[...t.split("/").slice(0,-1),...e])".."===n?0<r.length&&".."!==r[r.length-1]?r.pop():r.push(n):"."!==n&&r.push(n);t=r.join("/");return t.endsWith(".js")?t:t+".js"}static async getNodeModules(e,t,n){if(0!==e.length)for(var{match:r,modulePath:s}of e){var i=`/node_modules/${s}/package.json`;(await fetch(i,{method:"HEAD"})).ok?({main:i="index.js"}=await h.fetch(i,"json"),i=`/node_modules/${s}/`+i,h.isCyclyc(i,s),t.push(i),n=n.replace(r,r.replace(s,i))):console.warn(`The module "${s}" can't be imported and will be replaced with null`)}return n}static relativePath=location.pathname;constructor(e){this.contents={},this.path=e,this.fullPath=h.getFullPath(e,h.relativePath),this.contentReady=!1}async getContent(){if(!this.contentReady){let r=async i=>{if(void 0===this.contents[i]){if(!h.contents[i]){let e=await h.fetch(i),r=[],s=[];e=e.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm,(e,t)=>{var n;return t.startsWith(".")?(n=h.getFullPath(t,i),h.isCyclyc(n,i),r.push(n),e.replace(t,n)):(s.push({match:e,modulePath:t}),e)}),e=await h.getNodeModules(s,r,e),h.contents[i]={content:e,children:r}}let{content:e,children:t}=h.contents[i];this.contents[i]=e;for(var n of t)await r(n)}};await r(this.fullPath),this.contentReady=!0,this.prepareContents()}return this}prepareContents(){let t=new Set,n=e=>{e.forEach(e=>{this.contents[e]&&(n(h.contents[e].children),t.add(e))})};n(Object.keys(this.contents).reverse()),this.keys=Array.from(t)}build(r={},s={},i="context"){function o(e){return r[e]||null}return this.keys.map(t=>{var e={exports:{}},n={module:e,require:o,exports:e.exports,[i]:s};try{new Function(...Object.keys(n),this.contents[t])(...Object.values(n))}catch(e){this.error(e,t)}r[t]=e.exports}),r[this.keys[this.keys.length-1]]}error(e,t){let r=[],s=h.contents,i=Object.keys(s).reverse();!function e(t){r.push(t);for(var n of i)if(s[n].children.includes(t)){e(" at "+n);break}}(t);t=e.stack.split("\n");throw t.splice(1,1,...r),e.stack=t.join("\n"),e}}h;let c=function(){class r{constructor(){this.children=[]}get outer(){return this.before+this.inner+this.after}get inner(){return this.children.map(e=>e.outer).join("")}set outer(e){this.inner=e,this.before="",this.after=""}set inner(e){this.children=[],this.children.push(new c(e,this))}walkNodes(t=[],e=this){e.children.forEach(e=>{e instanceof r!=!1&&(this.walkNodes(t,e),this.runModifiers(t,e,!0))})}walkTextNodes(t=[],e=this){e.children.forEach(e=>{e instanceof r?this.walkTextNodes(t,e):this.runModifiers(t,e,!1)})}walk(n=[],e=this){e.children.forEach(e=>{var t=e instanceof r;t&&this.walk(n,e),this.runModifiers(n,e,t)})}runModifiers(e,t,n){for(var r of e)if(!1===r(t,n))return!1}}function o(e,n){if(e[0].n>n[0].n&&n.shift(),e[e.length-1].n>n[n.length-1].n&&e.pop(),e.length!==n.length)throw new Error(`Parsing error: unmatched tags detected. (${e.length},${n.length})`);let i=e.map((e,t)=>({start:e,end:n[t],children:[]}));return i.forEach((t,n)=>{for(let e=n;e<i.length;e++){var r,s;t.end.n>i[e].start.n&&(r=i[e].end,s=t.end,t.end=r,i[e].end=s)}}),i.sort((e,t)=>e.end.n-t.end.n),i.forEach((t,n)=>{for(let e=n;e<i.length;e++)t.start.n>i[e].start.n&&t.end.n<i[e].end.n&&(t.level||(t.level=0),t.level++,i[e].children.push(t))}),i=function t(e,n=0){return(e=e.filter(({level:e})=>!e||e<=n)).forEach(e=>{0!==e.children.length&&(e.children=t(e.children,n+1))}),e}(i)}function n(e,t,n,r=0){for(var s=[];;){var i=e.match(t);if(!i)break;r+=i.index+1;var o=n<0?n:n*(i[0].length-1);s.push({n:r+o,length:i[0].length}),e=e.slice(i.index+1)}return s}r;class h extends r{constructor(e,t,n=null){super(),(this.parent=n)&&(this.index=n.children.length),this.root=e,this.addChildren(t)}addChildren(e){var{start:e,end:t,children:n}=e;let r=this.root,s=e.n+e.length,i=t.n-t.length;return this.open=r.content.slice(e.n,s),n.forEach((e,t)=>{e.start.n>s&&this.children.push(new c(r.content.slice(s,e.start.n),this)),this.children.push(new h(r,e,this)),s=e.end.n}),i>s&&this.children.push(new c(r.content.slice(s,i),this)),this.close=r.content.slice(i,t.n),this}get outer(){return this.open+this.inner+this.close}set outer(e){this.inner=e,this.open="",this.close=""}get prev(){return this.parent?this.parent.children[this.index-1]:null}get next(){return this.parent?this.parent.children[this.index+1]:null}}class c{constructor(e,t){this.outer=e,(this.parent=t)&&(this.index=t.children.length),this.open="",this.close=""}get prev(){return this.parent.children[this.index-1]||null}get next(){return this.parent.children[this.index+1]||null}}return class extends r{constructor(e,t,n){if(super(),"string"!=typeof e)throw`Expected 'content' to be a string, but got '${typeof e}'`;if(t instanceof RegExp==0)throw'"startR" should be an instance of RegExp.';if(n instanceof RegExp==0)throw'"endR" should be an instance of RegExp.';this.content=e,this.startR=t,this.endR=n,this.build()}build(){let{content:r,startR:e,endR:t}=this;var s=n(r,e,-1),i=n(r,t,1);if(0!==s.length&&0!==i.length){let n=o(s,i);0!==n.length&&(s=n[0].start.n,i=n[n.length-1].end.n,this.before=0<s?r.slice(0,s):"",this.after=i<r.length?r.slice(i,r.length):"",n.forEach((e,t)=>{this.children.push(new h(this,e,this)),t!==n.length-1&&(t=n[t+1].start.n)!==(e=e.end.n)&&this.children.push(new c(r.slice(e,t),this))}))}}}}();let l=e=>e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//gm,"");return async function(e,t="body"){let n=[];var r=function(){let i={components:{},actions:[],counter:0,update:(e,t,n)=>{var r=i.components[e];const s=`[component=${e}]`;n&&(s+=`[key=${n}]`),document.querySelector(s).outerHTML=r(t),i.actions=i.actions.map(({fn:e,id:t,event:n})=>{t=document.getElementById(t);return t&&t.addEventListener(n,e),!1}).filter(Boolean)},buildComponent:function(n,r){i.components[r]||(n.update=function(e,t){i.update(r,e,t)},i.components[r]=function(t){let e=n(t).trim();return e.startsWith("<>")?e.slice(2,-3):e=e.replace(/^<\w*/,e=>(key=t.key?` key="${t.key}"`:"",e+(` component="${r}"`+key)))},i.components[r].update=function(e,t){i.update(r,e,t)})}};return i}(),s=new h(e);await s.getContent();for(let e in s.contents)s.contents[e]=function(e,n){var t=new c(e,new RegExp(/\(\s*?</),new RegExp(/\>\s*?\)/));if(0===t.children.length)return e;t.before=l(t.before),t.after=l(t.after);let r=[],s=(t.walkNodes([e=>{{var i=e,o=r;let s="<"+i.inner.trim()+">";i.open="`",i.close="`",i.inner=s.replace(/\<([A-Z]\w*)[\s\S]*?\/\>/g,(e,t,n)=>{o.push(t);let r=[];e.replace(/(\w*)\s*?\=\"([\s\S]*?)\"/g,(e,t,n)=>{r.push(t+`:"${n}"`)}),e.replace(/(\w*)\s*?\=\s*?\{\{?(.*?)\}?\}/g,(e,t,n)=>{r.push(t+":"+n)}),e.replace(/\{(\.\.\..*?)\}/,(e,t)=>{r.push(t)});t=`context.components.${t}({${r.join()}${""}})`;return 0===n&&e.length===s.length?(i.open="",i.close="",t):"${"+t+"}"}).replace(/(checked|disabled)\=\{([\s\S]*?)\}/g,(e,t,n)=>"${"+n+` ? '${t}' : '' `+"}").replace(/\/>/g,">")}}]),t.children.forEach(e=>{var o,t;o=n,(e=e).inner&&0!==(t=new c(e.inner,/\{/,/\}/)).children.length&&(t.walkNodes([n=>{var r=n.outer;if(!n.inner.startsWith("..."))if(r.startsWith("{/*")&&r.endsWith("*/}"))n.outer="";else{var{before:s,beforeNode:i}=function e(t){if(t.prev)return{beforeNode:t.prev,before:t.prev.outer.trim()};if(t.parent.before)return{beforeNode:t.parent,before:t.parent.before.trim()};return e(t.parent)}(n),e=s[s.length-1];if("$"!==e&&s[s.length-2]+e!=="=>"&&"("!==e&&","!==e)if("="===e){let e="",t=s.length-2;for(;0<=t&&(e=s[t]+e," "!==s[--t]););"style"===e&&"{"===n.parent.open&&"}"===n.parent.close?(o.push(r),i.before&&(i.before=i.before.slice(0,-1)+String(o.length-1)),n.parent.outer=""):e.startsWith("on")?n.outer=function(e,t){e=`{event:'${e}',fn:${t},id:'action'+(context.counter++).toString()}`;return'"${'+`context.actions.push(${e})`+` ? '' : ''}" id="\${'action'+(context.counter-1).toString()}" `}(e.split("on")[1].toLowerCase(),n.inner):n.outer='"${'+n.inner+'}"'}else"{"===n.open&&(n.open="${")}}]),e.inner=t.outer)}),r.map(e=>`context.buildComponent(${e},'${e}')`).join("\n"));return(e=t.outer.replace(/className\=/g,"class=").replace(/^\s*$(?:\r\n?|\n)/gm,""))+"\n"+s}(s.contents[e],n);n=n.length?`<style>${new Simple(n.map((e,t)=>({[`[style${t}]`]:parse(e)}))).stylesheet()}</style>`:"";var[e,t,r,i=!0]=[t,s.build({},r,"context")()+n,r];function o(e){var t=document.querySelector(e);if(t)return t;throw`The element with selector "${e}" not exists`}i&&(o(e).innerHTML=t),r.actions.forEach(({fn:e,id:t,event:n})=>{o("#"+t).addEventListener(n,e)}),r.actions=[]}}(); | ||
let render=function(){class l{static contents={};static async fetch(e,t="text"){e=await fetch(e);if(e.ok)return e[t]();throw new Error("HTTP error! status: "+e.status)}static isCyclyc(e,t){if(l.contents[e]&&l.contents[e].children.includes(t))throw`cyclic dependency between ${t} and `+e}static async getModule(e,t,n,r){e=new l(e);return await e.getContent(),e.build(r,t,n)}static getFullPath(e,t){var n,e=e.split("/"),r=[];for(n of[...t.split("/").slice(0,-1),...e])".."===n?0<r.length&&".."!==r[r.length-1]?r.pop():r.push(n):"."!==n&&r.push(n);t=r.join("/");return t.endsWith(".js")?t:t+".js"}static async getNodeModules(e,t,n){if(0!==e.length)for(var{match:r,modulePath:i}of e){var o=`/node_modules/${i}/package.json`;(await fetch(o,{method:"HEAD"})).ok?({main:o="index.js"}=await l.fetch(o,"json"),o=`/node_modules/${i}/`+o,l.isCyclyc(o,i),t.push(o),n=n.replace(r,r.replace(i,o))):console.warn(`The module "${i}" can't be imported and will be replaced with null`)}return n}static relativePath=location.pathname;constructor(e){this.contents={},this.path=e,this.fullPath=l.getFullPath(e,l.relativePath),this.contentReady=!1}async getContent(){if(!this.contentReady){let r=async o=>{if(void 0===this.contents[o]){if(!l.contents[o]){let e=await l.fetch(o),r=[],i=[];e=e.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm,(e,t)=>{var n;return t.startsWith(".")?(n=l.getFullPath(t,o),l.isCyclyc(n,o),r.push(n),e.replace(t,n)):(i.push({match:e,modulePath:t}),e)}),e=await l.getNodeModules(i,r,e),l.contents[o]={content:e,children:r}}let{content:e,children:t}=l.contents[o];this.contents[o]=e;for(var n of t)await r(n)}};await r(this.fullPath),this.contentReady=!0,this.prepareContents()}return this}prepareContents(){let t=new Set,n=e=>{e.forEach(e=>{this.contents[e]&&(n(l.contents[e].children),t.add(e))})};n(Object.keys(this.contents).reverse()),this.keys=Array.from(t)}build(r={},i={},o="context"){function s(e){return r[e]||null}return this.keys.map(t=>{var e={exports:{}},n={module:e,require:s,exports:e.exports,[o]:i};try{new Function(...Object.keys(n),this.contents[t])(...Object.values(n))}catch(e){this.error(e,t)}r[t]=e.exports}),r[this.keys[this.keys.length-1]]}error(e,t){let r=[],i=l.contents,o=Object.keys(i).reverse();!function e(t){r.push(t);for(var n of o)if(i[n].children.includes(t)){e(" at "+n);break}}(t);t=e.stack.split("\n");throw t.splice(1,1,...r),e.stack=t.join("\n"),e}}l;let a=function(){class r{constructor(){this.children=[]}get outer(){return this.before+this.inner+this.after}get inner(){return this.children.map(e=>e.outer).join("")}set outer(e){this.inner=e,this.before="",this.after=""}set inner(e){this.children=[],this.children.push(new a(e,this))}walkNodes(t=[],e=this){e.children.forEach(e=>{e instanceof r!=!1&&(this.walkNodes(t,e),this.runModifiers(t,e,!0))})}walkTextNodes(t=[],e=this){e.children.forEach(e=>{e instanceof r?this.walkTextNodes(t,e):this.runModifiers(t,e,!1)})}walk(n=[],e=this){e.children.forEach(e=>{var t=e instanceof r;t&&this.walk(n,e),this.runModifiers(n,e,t)})}runModifiers(e,t,n){for(var r of e)if(!1===r(t,n))return!1}}function s(e,n){if(e[0].n>n[0].n&&n.shift(),e[e.length-1].n>n[n.length-1].n&&e.pop(),e.length!==n.length)throw new Error(`Parsing error: unmatched tags detected. (${e.length},${n.length})`);let o=e.map((e,t)=>({start:e,end:n[t],children:[]}));return o.forEach((t,n)=>{for(let e=n;e<o.length;e++){var r,i;t.end.n>o[e].start.n&&(r=o[e].end,i=t.end,t.end=r,o[e].end=i)}}),o.sort((e,t)=>e.end.n-t.end.n),o.forEach((t,n)=>{for(let e=n;e<o.length;e++)t.start.n>o[e].start.n&&t.end.n<o[e].end.n&&(t.level||(t.level=0),t.level++,o[e].children.push(t))}),o=function t(e,n=0){return(e=e.filter(({level:e})=>!e||e<=n)).forEach(e=>{0!==e.children.length&&(e.children=t(e.children,n+1))}),e}(o)}function n(e,t,n,r=0){for(var i=[];;){var o=e.match(t);if(!o)break;r+=o.index+1;var s=n<0?n:n*(o[0].length-1);i.push({n:r+s,length:o[0].length}),e=e.slice(o.index+1)}return i}r;class l extends r{constructor(e,t,n=null){super(),(this.parent=n)&&(this.index=n.children.length),this.root=e,this.addChildren(t)}addChildren(e){var{start:e,end:t,children:n}=e;let r=this.root,i=e.n+e.length,o=t.n-t.length;return this.open=r.content.slice(e.n,i),n.forEach((e,t)=>{e.start.n>i&&this.children.push(new a(r.content.slice(i,e.start.n),this)),this.children.push(new l(r,e,this)),i=e.end.n}),o>i&&this.children.push(new a(r.content.slice(i,o),this)),this.close=r.content.slice(o,t.n),this}get outer(){return this.open+this.inner+this.close}set outer(e){this.inner=e,this.open="",this.close=""}get prev(){return this.parent?this.parent.children[this.index-1]:null}get next(){return this.parent?this.parent.children[this.index+1]:null}}class a{constructor(e,t){this.outer=e,(this.parent=t)&&(this.index=t.children.length),this.open="",this.close=""}get prev(){return this.parent.children[this.index-1]||null}get next(){return this.parent.children[this.index+1]||null}}return class extends r{constructor(e,t,n){if(super(),"string"!=typeof e)throw`Expected 'content' to be a string, but got '${typeof e}'`;if(t instanceof RegExp==0)throw'"startR" should be an instance of RegExp.';if(n instanceof RegExp==0)throw'"endR" should be an instance of RegExp.';this.content=e,this.startR=t,this.endR=n,this.build()}build(){let{content:r,startR:e,endR:t}=this;var i=n(r,e,-1),o=n(r,t,1);if(0!==i.length&&0!==o.length){let n=s(i,o);0!==n.length&&(i=n[0].start.n,o=n[n.length-1].end.n,this.before=0<i?r.slice(0,i):"",this.after=o<r.length?r.slice(o,r.length):"",n.forEach((e,t)=>{this.children.push(new l(this,e,this)),t!==n.length-1&&(t=n[t+1].start.n)!==(e=e.end.n)&&this.children.push(new a(r.slice(e,t),this))}))}}}}(),c=function(){let t;let n={a:"animation",bgc:"background-color",c:"color",bg:"background",bgi:"background-image",b:"border",br:"border-right",bl:"border-left",bt:"border-top",bb:"border-bottom",bc:"border-color",brc:"border-right-color",blc:"border-left-color",btc:"border-top-color",bbc:"border-bottom-color",bs:"border-style",brs:"border-right-style",bls:"border-left-style",bts:"border-top-style",bbs:"border-bottom-style",bw:"border-width",brw:"border-right-width",blw:"border-left-width",btw:"border-top-width",bbw:"border-bottom-width",radius:"border-radius",o:"outline",oc:"outline-color",os:"outline-style",ow:"outline-width",maxw:"max-width",minw:"min-width",h:"height",w:"width",maxh:"max-height",minh:"min-height",of:"overflow",ofx:"overflow-x",ofy:"overflow-y",scrollb:"scroll-behavior",p:"padding",m:"margin",pr:"padding-right",pl:"padding-left",pt:"padding-top",pb:"padding-bottom",mr:"margin-right",ml:"margin-left",mt:"margin-top",mb:"margin-bottom",d:"display",flexw:"flex-wrap",flexg:"flex-grow",flexdir:"flex-direction",ai:"align-items",ac:"aline-content",jc:"justify-content",gcols:"grid-template-columns",grows:"grid-template-rows",gacols:"grid-auto-columns",garows:"grid-auto-rows",areas:"grid-template-areas",area:"grid-area",dir:"direction",textt:"text-transform",ta:"text-align",td:"text-decoration",ws:"white-space",ww:"word-wrap",ff:"font-family",to:"text-overflow",ls:"letter-spacing",lh:"line-height",wb:"word-break",fv:"font-variant",fs:"font-size",fw:"font-weight",fstyle:"font-style",f:"font",pos:"position",z:"z-index",tr:"transform",cur:"cursor"};function o(t,n,r={}){for(let e in t){i=(i=t[e]).toString().trim();i=i=/["'].*["']/.test(i)?i:(i=function r(e){return e.replace(/\$([\w-$]*)(\(\$?([\w-()$]*)\))?/g,(e,t,n)=>(n=n?","+r(n.replace(/[()]/g,"")):"",`var(--${s(t)}${n})`))}(i=function(e){let r=["*","-","+","/"];return e.replace(/\[(.*?)\]/g,(e,n)=>"calc("+n.split("").map((e,t)=>(!r.includes(e)||"-"===e&&/[^\d\s]/.test(n[t+1])||(" "!==n[t-1]&&(e=" "+e)," "!==n[t+1]&&(e+=" ")),e)).join("")+")")}(i))).replace(/\!/,"!important");r[e=(e=n[e]||s(e)).replace(/^\$/,"--")]=i}var i;return r}function s(r){return r.split("").map((e,t)=>{var n=r[t-1];return 0!==t&&" "!==n&&"-"!=n&&/[A-Z]/.test(e)?"-"+e.toLowerCase():e}).join("")}function l(e,n=" ",r="\n",i=""){return e.map(e=>{var t;return"string"==typeof e?e.trim():([e,t]=Object.entries(e)[0],Array.isArray(t)?`${e} {${r}${l(t,n+n,r,n).join(r)}${r}}`:""+i+e+` {${r}${Object.entries(t).map(([e,t])=>""+n+e+":"+t).join(";"+r)}${r}${i}}`)})}class e{constructor(e=[],t={}){if(!Array.isArray(e))throw new Error("simples parameter should be arrray");if("object"!=typeof t)throw new Error("shorts parameter should be object");this.shorts=Object.assign({},n,t),this.styles=[],this.selectors=[],this.buildStyles(e,this.styles)}buildStyles(e,i=[]){return e.forEach(e=>{if("string"==typeof e)return this.buildString(e,i);if("object"==typeof e&&null!==e)for(let t in e=function t(n,r={}){for(let e in n){var i=n[e];if(Array.isArray(i))r[e]=i;else for(var o in i){var s=i[o];"object"==typeof s?t({[o.split(",").map(t=>e.trim().split(",").map(e=>e+t).join()).join()]:s},r):(r[e]||(r[e]={}),r[e][o]=s)}}return r}(e)){var n=Array.isArray(e[t])?this.buildStyles(e[t]):o(e[t],this.shorts),r=i.findIndex(e=>void 0!==e[t]);0<=r?i[r][t]={...i[r][t],...n}:i.push({[t]:n})}}),i}buildString(e,t){(e=e.trim()).startsWith("#")&&(e="/*"+e.replace(/^\#/,"")+"*/"),t.push(e)}stylesheet(e){return(e&&"number"==typeof e&&0<e?l(this.styles," ".repeat(e),"\n"):l(this.styles,"","")).join("\n")}publish(){var e;e=l(this.styles,"",""),t||(0==document.styleSheets.length&&document.getElementsByTagName("head")[0].insertAdjacentHTML("afterbegin",'<style id="simple-css"></style>'),t=document.styleSheets[0]),e.filter(e=>!e.startsWith("/*")).forEach(e=>{try{t.insertRule(e)}catch(e){console.log(e.message)}})}}return e.$=function(e,t,n){var r,i=document.documentElement;return null==t?getComputedStyle(i).getPropertyValue("--"+e):(void 0===n?i.style.setProperty("--"+e,t):void 0!==n&&((r=getComputedStyle(i).getPropertyValue("--"+e))==t?i.style.setProperty("--"+e,n):r==n&&i.style.setProperty("--"+e,t)),t)},e}();class u{static recursiveName="recursiveReference";static stringify(e,t=0){let a=" ".repeat(t),c=a?"\n":"",h=new WeakMap;return function n(e,r,t="",i){if(h.has(e))return`function ${u.recursiveName}(self) {return ${h.get(e)}}`;if(["number","boolean","undefined"].includes(typeof e)||null===e)return String(e);if("string"==typeof e)return`"${e.replace(/"/g,'\\"')}"`;if(e instanceof Date)return`new Date("${e}")`;if(e instanceof RegExp)return`new RegExp("${e.source}", "${e.flags}")`;if(h.set(e,i),"function"==typeof e)return e.toString();let o,s=c+t,l=(e,t)=>n(e,r+a,r,i+`[${t}]`);return o=Array.isArray(e)?`[${c}${e.map((e,t)=>r+l(e,t)).join(","+c)}${s}]`:e instanceof Set?"new Set("+l(Array.from(e))+")":e instanceof Map?"new Map("+l(Array.from(e.entries()))+")":e instanceof Error?`new Error('${e.message}')`:`{${c}${Object.entries(e).map(([e,t])=>r+`"${e}":`+l(t,`'${e}'`)).join(","+c)}${s}}`}(e,a,"","self")}static parse(e){let r=new Function("return "+e)();return function e(t){for(var n in t)"function"==typeof t[n]&&t[n].name===u.recursiveName?t[n]=t[n](r):null!==t[n]&&"object"==typeof t[n]&&e(t[n])}(r),r}}try{module.exports=u}catch(e){}let h=e=>e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//gm,"");return async function(e,t="body"){let n=[];var r=function(){let o={components:{},actions:[],counter:0,update:(e,t,n)=>{var r=o.components[e];const i=`[component=${e}]`;n&&(i+=`[key=${n}]`),document.querySelector(i).outerHTML=r(t),o.actions=o.actions.map(({fn:e,id:t,event:n})=>{t=document.getElementById(t);return t&&t.addEventListener(n,e),!1}).filter(Boolean)},buildComponent:function(n,r){o.components[r]||(n.update=function(e,t){o.update(r,e,t)},o.components[r]=function(t){let e=n(t).trim();return e.startsWith("<>")?e.slice(2,-3):e=e.replace(/^<\w*/,e=>(key=t.key?` key="${t.key}"`:"",e+(` component="${r}"`+key)))},o.components[r].update=function(e,t){o.update(r,e,t)})}};return o}(),i=new l(e);await i.getContent();for(let e in i.contents)i.contents[e]=function(e,n){var t=new a(e,new RegExp(/\(\s*?</),new RegExp(/\>\s*?\)/));if(0===t.children.length)return e;t.before=h(t.before),t.after=h(t.after);let r=[],i=(t.walkNodes([e=>{{var o=e,s=r;let i="<"+o.inner.trim()+">";o.open="`",o.close="`",o.inner=i.replace(/\<([A-Z]\w*)[\s\S]*?\/\>/g,(e,t,n)=>{s.push(t);let r=[];e.replace(/(\w*)\s*?\=\"([\s\S]*?)\"/g,(e,t,n)=>{r.push(t+`:"${n}"`)}),e.replace(/(\w*)\s*?\=\s*?\{\{?(.*?)\}?\}/g,(e,t,n)=>{r.push(t+":"+n)}),e.replace(/\{(\.\.\..*?)\}/,(e,t)=>{r.push(t)});t=`context.components.${t}({${r.join()}${""}})`;return 0===n&&e.length===i.length?(o.open="",o.close="",t):"${"+t+"}"}).replace(/(checked|disabled)\=\{([\s\S]*?)\}/g,(e,t,n)=>"${"+n+` ? '${t}' : '' `+"}").replace(/\/>/g,">")}}]),t.children.forEach(e=>{var s,t;s=n,(e=e).inner&&0!==(t=new a(e.inner,/\{/,/\}/)).children.length&&(t.walkNodes([n=>{var r=n.outer;if(!n.inner.startsWith("..."))if(r.startsWith("{/*")&&r.endsWith("*/}"))n.outer="";else{var{before:i,beforeNode:o}=function e(t){if(t.prev)return{beforeNode:t.prev,before:t.prev.outer.trim()};if(t.parent.before)return{beforeNode:t.parent,before:t.parent.before.trim()};return e(t.parent)}(n),e=i[i.length-1];if("$"!==e&&i[i.length-2]+e!=="=>"&&"("!==e&&","!==e)if("="===e){let e="",t=i.length-2;for(;0<=t&&(e=i[t]+e," "!==i[--t]););"style"===e&&"{"===n.parent.open&&"}"===n.parent.close?(s.push(r),o.before&&(o.before=o.before.slice(0,-1)+String(s.length-1)),n.parent.outer=""):e.startsWith("on")?n.outer=function(e,t){e=`{event:'${e}',fn:${t},id:'action'+(context.counter++).toString()}`;return'"${'+`context.actions.push(${e})`+` ? '' : ''}" id="\${'action'+(context.counter-1).toString()}" `}(e.split("on")[1].toLowerCase(),n.inner):n.outer='"${'+n.inner+'}"'}else"{"===n.open&&(n.open="${")}}]),e.inner=t.outer)}),r.map(e=>`context.buildComponent(${e},'${e}')`).join("\n"));return(e=t.outer.replace(/className\=/g,"class=").replace(/^\s*$(?:\r\n?|\n)/gm,""))+"\n"+i}(i.contents[e],n);n=n.length?`<style>${new c(n.map((e,t)=>({[`[style${t}]`]:u.parse(e)}))).stylesheet()}</style>`:"";var[e,t,r,o=!0]=[t,i.build({},r,"context")()+n,r];function s(e){var t=document.querySelector(e);if(t)return t;throw`The element with selector "${e}" not exists`}o&&(s(e).innerHTML=t),r.actions.forEach(({fn:e,id:t,event:n})=>{s("#"+t).addEventListener(n,e)}),r.actions=[]}}(); |
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
66064
310
8