@stacksjs/utils 0.75.451 → 0.75.457

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,3 +26,17 @@ Regression coverage lives in `tests/*state-contracts.test.ts`. `state-e2e.test.t
26
26
  runs real HTTP and Chrome consumers with SQLite, the native request cursor
27
27
  parser and memory storage. `published-state-contracts.test.ts` builds the package
28
28
  and checks its runtime exports and declarations in an isolated consumer.
29
+
30
+ Helper lifecycle contracts: pipelines snapshot supplied definitions; macro registries
31
+ belong to constructors, inherit base macros, restore overridden descriptors and
32
+ publish only successful installations. Native method overrides require the third
33
+ `replace` argument. Observer fallback callbacks report initial and changed bounds,
34
+ continue after callback errors, and release state on cleanup. Recursive cleanup
35
+ uses native filesystem traversal without following aliased parents. Environment
36
+ updates preserve dollar sequences; error extraction tolerates throwing accessors.
37
+
38
+ Markdown tables normalize row widths and escape backslashes/pipes and newlines by
39
+ default. `escapeCells: false` accepts caller-formatted cells. This preserves table
40
+ structure and does not sanitize arbitrary HTML. Retry budgets are validated and
41
+ backoffs saturate at the supported timer maximum. `helper-e2e.test.ts` runs real
42
+ HTTP and Chrome consumers; filesystem lifecycle cases run in isolated processes.
package/dist/clean.d.ts CHANGED
@@ -1 +1,2 @@
1
+ /** Remove generated artifacts with native filesystem operations, bounded to this project. */
1
2
  export declare function cleanProject(): Promise<void>;
package/dist/clean.js CHANGED
@@ -1 +1 @@
1
- import{path as p}from"@stacksjs/path";export async function cleanProject(){await Bun.$`rm -rf ${p.projectPath("bun.lock")}`;await Bun.$`rm -rf ${p.projectPath("yarn.lock")}`;await Bun.$`rm -rf ${p.projectPath("node_modules/")}`;await Bun.$`rm -rf ${p.frameworkPath("dist")}`;await Bun.$`rm -rf ${p.frameworkPath("node_modules")}`;await Bun.$`rm -rf ${p.frameworkPath("**/dist")}`;await Bun.$`rm -rf ${p.frameworkPath("**/node_modules")}`;await Bun.$`rm -rf ${p.frameworkCloudPath("cdk.out/")}`;await Bun.$`rm -rf ${p.frameworkCloudPath("cdk.context.json")}`;await Bun.$`rm -rf ${p.cloudPath("dist.zip")}`}
1
+ import{lstatSync,readdirSync,rmSync}from"node:fs";import{dirname,isAbsolute,join,relative,sep}from"node:path";import{path as p}from"@stacksjs/path";function ownedDirectory(root,directory){const path=relative(root,directory);if(isAbsolute(path)||path===".."||path.startsWith(`..${sep}`))return!1;let current=root;for(const part of path.split(sep).filter(Boolean)){current=join(current,part);try{const stat=lstatSync(current);if(!stat.isDirectory()||stat.isSymbolicLink())return!1}catch(error){if(error.code==="ENOENT")return!1;throw error}}return!0}export async function cleanProject(){const root=p.projectPath(),remove=(path)=>{if(ownedDirectory(root,dirname(path)))rmSync(path,{recursive:!0,force:!0})};for(const path of[p.projectPath("bun.lock"),p.projectPath("yarn.lock"),p.projectPath("node_modules"),p.frameworkCloudPath("cdk.out"),p.frameworkCloudPath("cdk.context.json"),p.cloudPath("dist.zip")])remove(path);const walk=(directory)=>{if(!ownedDirectory(root,directory))return;for(const entry of readdirSync(directory,{withFileTypes:!0})){const path=join(directory,entry.name);if(entry.name==="dist"||entry.name==="node_modules")remove(path);else if(entry.isDirectory()&&!entry.isSymbolicLink())walk(path)}};walk(p.frameworkPath())}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- export function getErrorMessage(e){if(e instanceof Error)return e.message;if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);if(e&&typeof e==="object"&&"message"in e&&typeof e.message==="string")return e.message;if(e==null)return"Unknown error";try{return String(e)}catch{return"Unknown error"}}export function getErrorStack(e){if(e instanceof Error)return e.stack;if(e&&typeof e==="object"&&"stack"in e&&typeof e.stack==="string")return e.stack;return}export function getErrorCode(e){if(e&&typeof e==="object"&&"code"in e&&typeof e.code==="string")return e.code;return}export function getErrorStatusCode(e){if(!e||typeof e!=="object")return;const obj=e;if(typeof obj.statusCode==="number"&&Number.isFinite(obj.statusCode))return obj.statusCode;if(typeof obj.status==="number"&&Number.isFinite(obj.status))return obj.status;return}export function toError(e){if(e instanceof Error)return e;return Error(getErrorMessage(e),{cause:e})}
1
+ export function getErrorMessage(e){const message=errorProperty(e,"message");if(typeof message==="string")return message;if(e==null)return"Unknown error";try{return String(e)}catch{return"Unknown error"}}function errorProperty(value,key){if(!value||typeof value!=="object"&&typeof value!=="function")return;try{return Reflect.get(value,key)}catch{return}}export function getErrorStack(e){const stack=errorProperty(e,"stack");return typeof stack==="string"?stack:void 0}export function getErrorCode(e){const code=errorProperty(e,"code");return typeof code==="string"?code:void 0}export function getErrorStatusCode(e){for(const key of["statusCode","status"]){const status=errorProperty(e,key);if(typeof status==="number"&&Number.isFinite(status))return status}return}export function toError(e){try{if(e instanceof Error)return e}catch{}return Error(getErrorMessage(e),{cause:e})}
package/dist/helpers.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import process from"node:process";import{runCommand}from"@stacksjs/cli";import{app,ui}from"@stacksjs/config";import{err,handleError}from"@stacksjs/error-handling";import{frameworkPath,projectPath}from"@stacksjs/path";import{fs,readJsonFile,readPackageJson,readTextFile,writeTextFile}from"@stacksjs/storage";export async function packageManager(){const{packageManager}=await readPackageJson(frameworkPath("package.json"));return packageManager??""}export async function ensureProjectIsInitialized(){if(!isStacksProject()){console.error("This command must be run inside a Stacks project; create one with: panx buddy new my-app");process.exit(1)}if(await isAppKeySet())return!0;if(fs.existsSync(projectPath(".env")))return!1;if(fs.existsSync(projectPath(".env.example")))fs.copyFileSync(projectPath(".env.example"),projectPath(".env"));else console.error("no .env.example file found");return await isAppKeySet()}export function isStacksProject(){if(!fs.existsSync(projectPath("package.json")))return!1;return fs.existsSync(projectPath("config"))||fs.existsSync(projectPath("storage/framework/core"))}export async function installIfVersionMismatch(){}export async function frameworkVersion(){return(await readPackageJson(frameworkPath("package.json"))).version??""}export async function isAppKeySet(){if(String(process.env.APP_KEY??"").trim().length>16)return!0;try{const appKey=(await readTextFile(".env",projectPath())).data.split(`
2
- `).find((line)=>line.startsWith("APP_KEY="));return!!(appKey&&appKey.length>16)}catch{return!1}}export function determineResetPreset(preset){if(preset===void 0&&ui.reset)preset=ui.reset;if(preset===null)return[];const resetImport={tailwind:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',preflight:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',forms:'import { tailwindFormsPreflight as reset } from "@stacksjs/ts-css/engine"'}[preset??"tailwind"];return resetImport?[resetImport]:[]}export function isManifest(obj){if(!obj||typeof obj!=="object")return!1;const candidate=obj;return isOptionalString(candidate.name)&&isOptionalString(candidate.version)&&isOptionalString(candidate.description)}export function isOptionalString(value){const type=typeof value;return value===null||type==="undefined"||type==="string"}export async function setEnvValue(key,value){const file=await readTextFile(projectPath(".env")),escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),keyPattern=new RegExp(`^${escapedKey}=.*$`,"m"),nextValue=`${key}=${value}`,data=keyPattern.test(file.data)?file.data.replace(keyPattern,nextValue):`${file.data}${file.data.endsWith(`
2
+ `).find((line)=>line.startsWith("APP_KEY="));return!!(appKey&&appKey.length>16)}catch{return!1}}export function determineResetPreset(preset){if(preset===void 0&&ui.reset)preset=ui.reset;if(preset===null)return[];const resetImport={tailwind:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',preflight:'import { tailwindPreflight as reset } from "@stacksjs/ts-css/engine"',forms:'import { tailwindFormsPreflight as reset } from "@stacksjs/ts-css/engine"'}[preset??"tailwind"];return resetImport?[resetImport]:[]}export function isManifest(obj){if(!obj||typeof obj!=="object")return!1;const candidate=obj;return isOptionalString(candidate.name)&&isOptionalString(candidate.version)&&isOptionalString(candidate.description)}export function isOptionalString(value){const type=typeof value;return value===null||type==="undefined"||type==="string"}export async function setEnvValue(key,value){const file=await readTextFile(projectPath(".env")),escapedKey=key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),keyPattern=new RegExp(`^${escapedKey}=.*$`,"m"),nextValue=`${key}=${value}`,data=keyPattern.test(file.data)?file.data.replace(keyPattern,()=>nextValue):`${file.data}${file.data.endsWith(`
3
3
  `)?"":`
4
4
  `}${nextValue}
5
5
  `;await writeTextFile({path:projectPath(".env"),data})}export async function runNpmScript(script,options){const{data:manifest}=await readJsonFile("package.json",frameworkPath());if(isManifest(manifest)&&hasScript(manifest,script))return await runCommand(`bun run ${script}`,options);return err(handleError(`The ${script} script does not exist in the package.json file.`))}export function hasScript(manifest,script){const scripts=manifest.scripts;if(scripts&&typeof scripts==="object")return Boolean(scripts[script]);return!1}export function parseYaml(content){return Bun.YAML.parse(content)}export function determineDebugLevel(options){if(options?.verbose===!0)return!0;return app.debug===!0}export function isIpv6(address){return address.family==="IPv6"||address.family===6}export function dumpYaml(content){const yaml=Bun.YAML;if(typeof yaml.stringify==="function")return yaml.stringify(content);return JSON.stringify(content,null,2)}export function loadYaml(content){return Bun.YAML.parse(content)}
@@ -1,15 +1,7 @@
1
- /**
2
- * Create a macroable class
3
- */
4
- export declare function createMacroable<T extends new (..._args: any[]) => any>(BaseClass?: T): T & MacroableConstructor;
5
- /**
6
- * Mixin for adding macroable functionality to existing classes
7
- */
8
- export declare function macroable<T extends new (..._args: any[]) => any>(target: T): T & MacroableConstructor;
9
- /**
10
- * Native Macroable implementation
11
- * Inspired by Laravel's Macroable trait - allows adding methods dynamically to classes
12
- */
1
+ export declare function createMacroable<T extends Constructor>(BaseClass?: T): T & MacroableConstructor;
2
+ /** Static methods use their receiver, so decorated subclasses own their mutations. */
3
+ export declare function macroable<T extends Constructor>(target: T): T & MacroableConstructor;
4
+ /** Dynamic methods with constructor-local registration and reversible overrides. */
13
5
  export declare interface MacroableConstructor {
14
6
  new (...args: any[]): any
15
7
  macro(name: string, fn: Function, replace?: boolean): void
@@ -18,11 +10,14 @@ export declare interface MacroableConstructor {
18
10
  flushMacros(): void
19
11
  getMacros(): string[]
20
12
  }
13
+ declare interface MacroTarget { prototype: object }
14
+ // eslint-disable-next-line pickier/no-unused-vars
15
+ declare type Constructor = new (...args: any[]) => any;
21
16
  export declare class Macroable {
22
- static macro(name: string, fn: Function, replace?: boolean): void;
23
- static mixin(obj: Record<string, any>, replace?: boolean): void;
24
- static hasMacro(name: string): boolean;
25
- static flushMacros(): void;
26
- static getMacros(): string[];
17
+ static macro(this: MacroTarget, name: string, fn: Function, replace?: boolean): void;
18
+ static mixin(this: MacroTarget & Pick<MacroableConstructor, 'macro'>, obj: Record<string, any>, replace?: boolean): void;
19
+ static hasMacro(this: MacroTarget, name: string): boolean;
20
+ static flushMacros(this: MacroTarget): void;
21
+ static getMacros(this: MacroTarget): string[];
27
22
  protected callMacro(name: string, ...args: any[]): any;
28
23
  }
package/dist/macroable.js CHANGED
@@ -1 +1 @@
1
- export class Macroable{static macros=new Map;static macro(name,fn,replace=!1){if(this.macros.has(name)&&!replace)throw Error(`Macro "${name}" is already registered`);this.macros.set(name,fn);Object.defineProperty(this.prototype,name,{value:fn,writable:!0,configurable:!0,enumerable:!1})}static mixin(obj,replace=!0){const methods=Object.getOwnPropertyNames(obj);for(const method of methods){if(method==="constructor")continue;if(this.macros.has(method)&&!replace)continue;const descriptor=Object.getOwnPropertyDescriptor(obj,method);if(descriptor&&typeof descriptor.value==="function")this.macro(method,descriptor.value,replace)}}static hasMacro(name){return this.macros.has(name)}static flushMacros(){for(const name of this.macros.keys())delete this.prototype[name];this.macros.clear()}static getMacros(){return Array.from(this.macros.keys())}callMacro(name,...args){const macro=this.constructor.macros.get(name);if(!macro)throw Error(`Macro "${name}" is not registered`);return macro.apply(this,args)}}export function createMacroable(BaseClass=class{}){return class extends BaseClass{static macros=new Map;static macro(name,fn,replace=!1){if(this.macros.has(name)&&!replace)throw Error(`Macro "${name}" is already registered`);this.macros.set(name,fn);Object.defineProperty(this.prototype,name,{value:fn,writable:!0,configurable:!0,enumerable:!1})}static mixin(obj,replace=!0){const methods=Object.getOwnPropertyNames(obj);for(const method of methods){if(method==="constructor")continue;if(this.macros.has(method)&&!replace)continue;const descriptor=Object.getOwnPropertyDescriptor(obj,method);if(descriptor&&typeof descriptor.value==="function")this.macro(method,descriptor.value,replace)}}static hasMacro(name){return this.macros.has(name)}static flushMacros(){for(const name of this.macros.keys())delete this.prototype[name];this.macros.clear()}static getMacros(){return Array.from(this.macros.keys())}}}export function macroable(target){const macros=new Map,decorated=target;decorated.macro=function(name,fn,replace=!1){if(macros.has(name)&&!replace)throw Error(`Macro "${name}" is already registered`);macros.set(name,fn);Object.defineProperty(target.prototype,name,{value:fn,writable:!0,configurable:!0,enumerable:!1})};decorated.mixin=function(obj,replace=!0){const methods=Object.getOwnPropertyNames(obj);for(const method of methods){if(method==="constructor")continue;if(macros.has(method)&&!replace)continue;const descriptor=Object.getOwnPropertyDescriptor(obj,method);if(descriptor&&typeof descriptor.value==="function")decorated.macro(method,descriptor.value,replace)}};decorated.hasMacro=function(name){return macros.has(name)};decorated.flushMacros=function(){for(const name of macros.keys())delete target.prototype[name];macros.clear()};decorated.getMacros=function(){return Array.from(macros.keys())};return target}
1
+ const registries=new WeakMap;function parentOf(target){const parent=Object.getPrototypeOf(target);return typeof parent==="function"&&parent.prototype?parent:void 0}function registration(target,name){for(let current=target;current;current=parentOf(current)){const own=registries.get(current)?.get(name);if(own)return own;if(Object.hasOwn(current.prototype,name))return}}export class Macroable{static macro(name,fn,replace=!1){if(name==="constructor")throw Error("The constructor cannot be a macro");if(typeof fn!=="function")throw TypeError("A macro must be a function");if(!replace&&name in this.prototype){if(registration(this,name))throw Error(`Macro "${name}" is already registered`);throw Error(`Method "${name}" already exists; pass replace to override it`)}const records=registries.get(this)??new Map,previous=records.get(name),original=previous?previous.original:Object.getOwnPropertyDescriptor(this.prototype,name);Object.defineProperty(this.prototype,name,{value:fn,writable:!0,configurable:!0,enumerable:!1});records.set(name,{fn,original});registries.set(this,records)}static mixin(obj,replace=!0){for(const name of Object.getOwnPropertyNames(obj)){if(name==="constructor"||!replace&&name in this.prototype)continue;const descriptor=Object.getOwnPropertyDescriptor(obj,name);if(descriptor&&typeof descriptor.value==="function")this.macro(name,descriptor.value,replace)}}static hasMacro(name){return registration(this,name)!==void 0}static flushMacros(){const records=registries.get(this);if(!records)return;for(const[name,record]of records){if(record.original)Object.defineProperty(this.prototype,name,record.original);else if(!Reflect.deleteProperty(this.prototype,name))throw TypeError(`Cannot remove macro "${name}"`);records.delete(name)}registries.delete(this)}static getMacros(){const names=new Set;for(let current=this;current;current=parentOf(current))for(const name of registries.get(current)?.keys()??[])names.add(name);return[...names].filter((name)=>registration(this,name)!==void 0)}callMacro(name,...args){const found=registration(this.constructor,name);if(!found)throw Error(`Macro "${name}" is not registered`);return found.fn.apply(this,args)}}export function createMacroable(BaseClass=class{}){return macroable(class extends BaseClass{})}export function macroable(target){const decorated=target;for(const name of["macro","mixin","hasMacro","flushMacros","getMacros"])Object.defineProperty(decorated,name,{value:Macroable[name],writable:!0,configurable:!0});return decorated}
@@ -38,6 +38,7 @@ export declare interface MarkdownTableOptions {
38
38
  delimiterStart?: boolean
39
39
  delimiterEnd?: boolean
40
40
  alignDelimiter?: string
41
+ escapeCells?: boolean
41
42
  }
42
43
  declare type CellValue = string | number | boolean | null | undefined;
43
44
  declare type Row = CellValue[];
package/dist/markdown.js CHANGED
@@ -1,2 +1,2 @@
1
- export function markdownTable(table,options={}){const{align=[],padding=!0,delimiter="|",delimiterStart=!0,delimiterEnd=!0,alignDelimiter="-"}=options;if(!table||table.length===0)return"";const normalized=table.map((row)=>row.map((cell)=>{if(cell===null||cell===void 0)return"";return String(cell)})),columnCount=Math.max(...normalized.map((row)=>row.length)),columnWidths=Array.from({length:columnCount}).fill(0);for(const row of normalized)for(let i=0;i<row.length;i++){const cellLength=row[i]?.length??0;if(cellLength>(columnWidths[i]??0))columnWidths[i]=cellLength}const rows=[];if(normalized.length>0){const header=normalized[0]??[];rows.push(buildRow(header,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));const separatorCells=columnWidths.map((width,index)=>{const alignment=normalizeAlignment(align[index]);return buildSeparator(width,alignment,alignDelimiter)});rows.push(buildRow(separatorCells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));for(let i=1;i<normalized.length;i++){const dataRow=normalized[i]??[];rows.push(buildRow(dataRow,columnWidths,padding,delimiter,delimiterStart,delimiterEnd))}}return rows.join(`
2
- `)}function buildRow(cells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd){const paddedCells=cells.map((cell,index)=>{const width=columnWidths[index]??0;return cell.padEnd(width," ")}),space=padding?" ":"";let row=paddedCells.map((cell)=>`${space}${cell}${space}`).join(delimiter);if(delimiterStart)row=delimiter+row;if(delimiterEnd)row=row+delimiter;return row}function buildSeparator(width,alignment,char){const minWidth=alignment==="center"?3:alignment?2:1;if(width<minWidth)width=minWidth;let separator=char.repeat(width);if(alignment==="left")separator=`:${separator.slice(1)}`;else if(alignment==="right")separator=separator.slice(0,-1)+":";else if(alignment==="center")separator=`:${separator.slice(2)}:`;return separator}function normalizeAlignment(align){if(!align)return null;switch(align){case"l":case"left":return"left";case"c":case"center":return"center";case"r":case"right":return"right";default:return null}}export function markdownTableFromObjects(objects,options={}){if(!objects||objects.length===0)return"";const keys=Array.from(new Set(objects.flatMap((obj)=>Object.keys(obj)))),table=[keys,...objects.map((obj)=>keys.map((key)=>obj[key]))];return markdownTable(table,options)}export{markdownTable as default};
1
+ export function markdownTable(table,options={}){const{align=[],padding=!0,delimiter="|",delimiterStart=!0,delimiterEnd=!0,alignDelimiter="-",escapeCells=!0}=options;if(!table||table.length===0)return"";const normalized=table.map((row)=>row.map((cell)=>{if(cell===null||cell===void 0)return"";const text=String(cell);return escapeCells?text.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\r|\n/g,"<br>"):text})),columnCount=normalized.reduce((max,row)=>Math.max(max,row.length),0),columnWidths=Array.from({length:columnCount}).fill(0);for(const row of normalized)for(let i=0;i<row.length;i++){const cellLength=row[i]?.length??0;if(cellLength>(columnWidths[i]??0))columnWidths[i]=cellLength}const rows=[];if(normalized.length>0){const header=normalized[0]??[];rows.push(buildRow(header,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));const separatorCells=columnWidths.map((width,index)=>{const alignment=normalizeAlignment(align[index]);return buildSeparator(width,alignment,alignDelimiter)});rows.push(buildRow(separatorCells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd));for(let i=1;i<normalized.length;i++){const dataRow=normalized[i]??[];rows.push(buildRow(dataRow,columnWidths,padding,delimiter,delimiterStart,delimiterEnd))}}return rows.join(`
2
+ `)}function buildRow(cells,columnWidths,padding,delimiter,delimiterStart,delimiterEnd){const paddedCells=columnWidths.map((width,index)=>{return(cells[index]??"").padEnd(width," ")}),space=padding?" ":"";let row=paddedCells.map((cell)=>`${space}${cell}${space}`).join(delimiter);if(delimiterStart)row=delimiter+row;if(delimiterEnd)row=row+delimiter;return row}function buildSeparator(width,alignment,char){const minWidth=alignment==="center"?3:alignment?2:1;if(width<minWidth)width=minWidth;let separator=char.repeat(width);if(alignment==="left")separator=`:${separator.slice(1)}`;else if(alignment==="right")separator=separator.slice(0,-1)+":";else if(alignment==="center")separator=`:${separator.slice(2)}:`;return separator}function normalizeAlignment(align){if(!align)return null;switch(align){case"l":case"left":return"left";case"c":case"center":return"center";case"r":case"right":return"right";default:return null}}export function markdownTableFromObjects(objects,options={}){if(!objects||objects.length===0)return"";const keys=Array.from(new Set(objects.flatMap((obj)=>Object.keys(obj)))),table=[keys,...objects.map((obj)=>keys.map((key)=>obj[key]))];return markdownTable(table,options)}export{markdownTable as default};
package/dist/observer.js CHANGED
@@ -1 +1 @@
1
- export function isResizeObserverSupported(){return typeof window<"u"&&"ResizeObserver"in window}export function getResizeObserver(){if(isResizeObserverSupported())return window.ResizeObserver;return class ResizeObserverPolyfill{callback;observedElements=new Set;rafId=null;scheduling=!1;constructor(callback){this.callback=callback}observe(target){if(!this.observedElements.has(target)){this.observedElements.add(target);this.scheduleCheck()}}unobserve(target){this.observedElements.delete(target);if(this.observedElements.size===0&&this.rafId!==null){(typeof cancelAnimationFrame<"u"?cancelAnimationFrame:clearTimeout)(this.rafId);this.rafId=null}}disconnect(){this.observedElements.clear();if(this.rafId!==null){(typeof cancelAnimationFrame<"u"?cancelAnimationFrame:clearTimeout)(this.rafId);this.rafId=null}}scheduleCheck(){if(this.rafId!==null||this.scheduling)return;const raf=typeof requestAnimationFrame<"u"?requestAnimationFrame:setTimeout;this.scheduling=!0;try{this.rafId=raf(()=>{this.check();this.rafId=null;if(this.observedElements.size>0)this.scheduleCheck()})}finally{this.scheduling=!1}}check(){const entries=[];for(const element of this.observedElements){const rect=element.getBoundingClientRect(),entry={target:element,contentRect:rect,borderBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],contentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],devicePixelContentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}]};entries.push(entry)}if(entries.length>0)this.callback(entries,this)}}}export function createResizeObserver(callback,target){const observer=new(getResizeObserver())(callback),targets=Array.isArray(target)?target:[target];for(const element of targets)observer.observe(element);return()=>{observer.disconnect()}}export function observeElementSize(element,callback){return createResizeObserver((entries)=>{const entry=entries.find((e)=>e.target===element);if(entry)callback(entry)},element)}export const ResizeObserver=getResizeObserver();export default ResizeObserver;
1
+ export function isResizeObserverSupported(){return typeof window<"u"&&typeof window.ResizeObserver==="function"}export function getResizeObserver(){if(isResizeObserverSupported())return window.ResizeObserver;return class ResizeObserverPolyfill{callback;observedElements=new Map;pending=null;scheduling=!1;constructor(callback){this.callback=callback}observe(target){if(this.observedElements.has(target))return;this.observedElements.set(target,void 0);this.scheduleCheck()}unobserve(target){this.observedElements.delete(target);if(this.observedElements.size===0)this.cancelCheck()}disconnect(){this.observedElements.clear();this.cancelCheck()}cancelCheck(){const pending=this.pending;this.pending=null;pending?.cancel?.()}scheduleCheck(){if(this.pending||this.scheduling||this.observedElements.size===0)return;const pending={};this.pending=pending;this.scheduling=!0;const run=()=>{if(this.pending!==pending)return;this.pending=null;try{this.check()}finally{this.scheduleCheck()}};try{if(typeof requestAnimationFrame==="function"){const id=requestAnimationFrame(run);pending.cancel=()=>cancelAnimationFrame(id)}else{const id=setTimeout(run,16);pending.cancel=()=>clearTimeout(id)}}catch(error){if(this.pending===pending)this.pending=null;throw error}finally{this.scheduling=!1}}check(){const entries=[];for(const[element,previous]of this.observedElements){const rect=element.getBoundingClientRect();if(previous&&previous.width===rect.width&&previous.height===rect.height)continue;this.observedElements.set(element,{width:rect.width,height:rect.height});entries.push({target:element,contentRect:rect,borderBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],contentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}],devicePixelContentBoxSize:[{inlineSize:rect.width,blockSize:rect.height}]})}if(entries.length>0)this.callback(entries,this)}}}export function createResizeObserver(callback,target){const observer=new(getResizeObserver())(callback),targets=Array.isArray(target)?target:[target];for(const element of targets)observer.observe(element);return()=>{observer.disconnect()}}export function observeElementSize(element,callback){return createResizeObserver((entries)=>{const entry=entries.find((e)=>e.target===element);if(entry)callback(entry)},element)}export const ResizeObserver=getResizeObserver();export default ResizeObserver;
@@ -5,7 +5,7 @@ declare type PipeFunction<T> = (data: T, next: (data: T) => T) => T;
5
5
  declare type Pipe<T> = PipeFunction<T> | PipeClass<T>;
6
6
  export declare class Pipeline<T> {
7
7
  static send<T>(passable: T): Pipeline<T>;
8
- through(pipes: Pipe<T>[]): this;
8
+ through(pipes: readonly Pipe<T>[]): this;
9
9
  pipe(...pipes: Pipe<T>[]): this;
10
10
  via(method: string): this;
11
11
  then(destination: (data: T) => T): T;
package/dist/pipeline.js CHANGED
@@ -1 +1 @@
1
- export class Pipeline{passable;pipes=[];method="handle";static send(passable){const pipeline=new Pipeline;pipeline.passable=passable;return pipeline}through(pipes){this.pipes=pipes;return this}pipe(...pipes){this.pipes.push(...pipes);return this}via(method){this.method=method;return this}then(destination){return this.pipes.reduceRight((next,pipe)=>{return(passable)=>{if(typeof pipe==="function")return pipe(passable,next);const handler=pipe[this.method];if(typeof handler==="function")return handler.call(pipe,passable,next);return next(passable)}},destination)(this.passable)}thenReturn(){return this.then((passable)=>passable)}}
1
+ export class Pipeline{passable;pipes=[];method="handle";static send(passable){const pipeline=new Pipeline;pipeline.passable=passable;return pipeline}through(pipes){this.pipes=[...pipes];return this}pipe(...pipes){this.pipes.push(...pipes);return this}via(method){this.method=method;return this}then(destination){return this.pipes.reduceRight((next,pipe)=>{return(passable)=>{if(typeof pipe==="function")return pipe(passable,next);const handler=pipe[this.method];if(typeof handler==="function")return handler.call(pipe,passable,next);return next(passable)}},destination)(this.passable)}thenReturn(){return this.then((passable)=>passable)}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/utils",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.451",
5
+ "version": "0.75.457",
6
6
  "description": "The Stacks helper functions.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -62,20 +62,20 @@
62
62
  "size": "bun scripts/export-size.ts"
63
63
  },
64
64
  "dependencies": {
65
- "@stacksjs/browser": "0.75.451",
66
- "@stacksjs/cli": "0.75.451",
67
- "@stacksjs/config": "0.75.451",
68
- "@stacksjs/enums": "0.75.451",
69
- "@stacksjs/error-handling": "0.75.451",
70
- "@stacksjs/logging": "0.75.451",
71
- "@stacksjs/path": "0.75.451",
72
- "@stacksjs/storage": "0.75.451",
73
- "@stacksjs/strings": "0.75.451",
74
- "@stacksjs/types": "0.75.451"
65
+ "@stacksjs/browser": "0.75.457",
66
+ "@stacksjs/cli": "0.75.457",
67
+ "@stacksjs/config": "0.75.457",
68
+ "@stacksjs/enums": "0.75.457",
69
+ "@stacksjs/error-handling": "0.75.457",
70
+ "@stacksjs/logging": "0.75.457",
71
+ "@stacksjs/path": "0.75.457",
72
+ "@stacksjs/storage": "0.75.457",
73
+ "@stacksjs/strings": "0.75.457",
74
+ "@stacksjs/types": "0.75.457"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/arrays": "0.75.451",
78
- "@stacksjs/lint": "0.75.451",
77
+ "@stacksjs/arrays": "0.75.457",
78
+ "@stacksjs/lint": "0.75.457",
79
79
  "better-dx": "^0.2.24",
80
80
  "filesize": "^11.0.25",
81
81
  "markdown-table": "^3.0.4"