@stacksjs/utils 0.75.447 → 0.75.450

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
@@ -1,423 +1,28 @@
1
- ![Social Card of Stacks](./public/images/social.png)
2
-
3
- # Rapid App & Library Development
4
-
5
- [![npm version](https://img.shields.io/npm/v/stacks?style=flat-square)](https://npmjs.com/package/stacks)
6
- [![GitHub Actions](https://img.shields.io/github/actions/workflow/status/stacksjs/stacks/ci.yml?style=flat-square&branch=main)](https://github.com/stacksjs/stacks/actions?query=workflow%3Aci)
7
- [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
8
- [![npm downloads](https://img.shields.io/npm/dm/stacks?style=flat-square)](https://npmjs.com/package/stacks)
9
- <!-- [![Codecov][codecov-src]][codecov-href] -->
10
-
11
- > [!NOTE]
12
- > Stacks is in active development and usable today — every section below
13
- > is real, runnable functionality. Expect occasional breaking changes
14
- > while we cut the official 1.0. Feedback and issue reports are welcome.
15
-
16
- Stacks is a rapid development framework, where the goal is to _help you_ create & maintain frontends, backends, and clouds—without having to worry about the boilerplate. _An all-in-one toolkit that meets all your full stack needs._
17
-
18
- <a href="https://stacksjs.com/docs/diagrams/stacks-runtime">
19
- <picture>
20
- <source media="(prefers-color-scheme: dark)" srcset="./docs/public/diagrams/stacks-runtime/dark.png">
21
- <img alt="Stacks runtime architecture: developer to Buddy CLI to Stacks Cloud, and web or desktop client through rpx to stx, router, actions, ORM, and database" src="./docs/public/diagrams/stacks-runtime/light.png">
22
- </picture>
23
- </a>
24
-
25
- _[Open the interactive diagram](https://stacksjs.com/docs/diagrams/stacks-runtime) for a theme toggle, node search, route tracing, presentation mode, and SVG, PNG, JPEG, WebP and share-card exports._
26
-
27
- - Web & Desktop Applications _(including system tray apps)_
28
- - Serverless & Traditional APIs
29
- - Cloud Infrastructure Creation & Maintenance
30
- - Interactive CLIs
31
- - Framework-agnostic Component & Function Libraries
32
- - Deployment & Release Manager _(CI & CD)_
33
-
34
- ## Convention Over Configuration
35
-
36
- As a developer, Stacks helps you every step along the way—in beginner & expert-friendly ways, allowing you to focus on the _what & why_ of your project, all while enabling you to stay in control & ownership of your _(& your users’)_ data.
37
-
38
- > “It is the framework’s responsibility to remove patterns that lead to boilerplate code. And Stacks is really good at that.” _- Chris_
39
-
40
- <!-- ![Atomic UI & FX Design](./docs/assets/diagram.png) -->
41
-
42
- ## Prerequisites
43
-
44
- Stacks uses [Pantry](https://pantry.dev) to provision Bun, Git, SQLite, and the project-specific tools declared by the framework. You'll need:
45
-
46
- - **Pantry** - install it with `curl -fsSL https://pantry.dev | bash`, then run `pantry bootstrap` once to configure your shell.
47
- - **macOS, Linux, or WSL** - Windows-native support is on the roadmap. The current toolchain assumes a POSIX shell.
48
-
49
- Pantry installs and pins Bun 1.4.4 for this Stacks workspace, then keeps the rest of the machine and project dependencies in sync. Features such as PostgreSQL, Redis, and cloud deployment add their requirements through the same Pantry manifest where possible, with feature-specific configuration documented alongside them.
50
-
51
- Stacks pins Pantry [`v0.11.50`](https://github.com/pantry-pm/pantry/tree/v0.11.50)
52
- as an external toolchain contract. Resolution sources, lockfile and integrity
53
- rules, lifecycle trust, registry routes, authentication, storage, and failure
54
- modes are documented in the source-linked whitepaper references for the
55
- [package manager](https://whitepaper.stacksjs.com/reference/package-manager) and
56
- [registry](https://whitepaper.stacksjs.com/reference/registry). Stacks does not
57
- redefine those behaviors.
58
-
59
- ## Get Started
60
-
61
- ### In the browser
62
-
63
- [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/stacksjs/stacks)
64
-
65
- A Codespace provisions Pantry, installs dependencies, runs `buddy setup` and
66
- forwards the dev ports, so `./buddy dev` works on first open. Nothing to
67
- install locally.
68
-
69
- ### On your machine
70
-
71
- The fastest path after Pantry is installed:
72
-
73
- ```bash
74
- panx buddy new my-project
75
- ```
76
-
77
- Pantry executes Buddy in an isolated environment and provisions the generated project's declared toolchain during setup.
78
-
79
- From there: the [documentation](https://stacksjs.com/docs/guide/intro), the [Buddy command reference](https://stacksjs.com/docs/guide/buddy/commands), and the [agent skills](https://stacksjs.com/docs/skills) that teach Claude Code, Codex, and Cursor how each subsystem works.
80
-
81
- For frontend experiments in the browser, open the live stx starter:
82
-
83
- [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/fork/github/stacksjs/stackblitz?title=Stacks%20Starter)
84
-
85
- ## Usage
86
-
87
- Stacks ships with `buddy`, a single CLI for everything you'll do day to day. The handful below covers the common workflows; the full reference is collapsed underneath.
88
-
89
- ```bash
90
- buddy dev # start the dev server (frontend, API, dashboard, …)
91
- buddy build # build for production (CLI prompts for what to build)
92
- buddy test # run tests
93
- buddy migrate # run database migrations
94
- buddy make:action UpdateUser # scaffold a new Action (also: model, view, job, …)
95
- buddy --help # show every available command
96
- ```
97
-
98
- For the full command reference, see the collapsible section below or the [Buddy CLI documentation](https://stacksjs.com/docs/guide/buddy/commands).
99
-
100
- <details>
101
- <summary>View the complete Buddy Toolkit</summary>
102
-
103
- ```bash
104
- buddy --version # get the Stacks version
105
- buddy --help # view help menu
106
- # please note: you may suffix any command with the
107
- # `command --help` flag to review the help menu
108
-
109
- buddy new my-project # creates a new Stacks project
110
- buddy install # installs dependencies
111
- buddy add calendar # pulls a registered project-shaped stack into this project
112
- buddy fresh # fresh reinstall of all deps (--force skips the confirmation)
113
- buddy clean # removes all deps (--force skips the confirmation)
114
- buddy setup # sets up the project initially
115
- buddy setup:oh-my-zsh # optional: sets up Oh My Zsh with auto-completions & "aliases"
116
-
117
- buddy upgrade # upgrades the Stacks framework (alias: buddy update)
118
- buddy upgrade:dependencies # auto-upgrades package.json deps
119
- buddy upgrade:shell # upgrades the shell integration
120
- buddy upgrade:binary # upgrades the `stacks` binary
121
- buddy upgrade:bun # upgrades to latest project-defined Bun version
122
- buddy upgrade:all # auto-upgrades all of the above
123
-
124
- # if you need any more info on any command listed here, you may suffix
125
- # any of them via the "help option", i.e. `buddy ... --help`
126
-
127
- buddy dev # starts the dev servers (frontend, api & docs)
128
- buddy dev -i # prompts you to select which dev server to start
129
- buddy dev:api # starts the API dev server
130
- buddy dev:dashboard # starts the Admin/Dashboard dev server
131
- buddy dev:desktop # starts the Desktop dev server
132
- buddy dev:views # starts frontend dev server
133
- buddy dev:components # starts component dev server
134
- buddy dev:docs # starts local docs dev server
135
- buddy dev docs # also starts the local docs dev server (dev takes the server name as an argument)
136
-
137
- buddy share # creates a sharable link to your local project
138
-
139
- # production servers (the same entries the deploy target runs as services)
140
- buddy serve # starts the production HTTP server (STX views + /api proxy)
141
- buddy serve:api # starts the production API server
142
-
143
- # building for production (e.g. AWS, Google Cloud, npm, Vercel, Netlify, et al.)
144
- buddy build # select a specific build (follow CLI prompts)
145
- buddy build:frontend # builds the frontend (aliases: build:views, build:pages)
146
- buddy build:desktop # builds Desktop application
147
- buddy build:mobile # builds both native iOS and Android applications
148
- buddy build:ios # builds the native iOS application
149
- buddy build:android # builds the native Android application
150
- buddy build:functions # builds function library
151
- buddy build:components # builds the STX component library and Web Component library
152
- buddy build:web-components # builds framework agnostic Web Component library (i.e. Custom Elements)
153
- buddy build:cli # builds the Buddy CLI binary
154
- buddy build:server # builds the Stacks cloud server (Docker image)
155
- buddy build:docs # builds the documentation site
156
-
157
- # `buddy build:*` aliases
158
- buddy prod:components # alias for build:components
159
- buddy prod:desktop # alias for build:desktop
160
- buddy prod:mobile # alias for build:mobile
161
- buddy prod:ios # alias for build:ios
162
- buddy prod:android # alias for build:android
163
- buddy prod:web-components # alias for build:web-components
164
- buddy prod:frontend # alias for build:frontend
165
- buddy prod:cli # alias for build:cli
166
- buddy prod:server # alias for build:server
167
- buddy prod:docs # alias for build:docs
168
- buddy prod:frontend-static # alias for build:frontend-static
169
-
170
- # sets your application key
171
- buddy key:generate
172
-
173
- buddy make:component HelloWorld # bootstraps a HelloWorld component
174
- buddy make:function hello-world # bootstraps a hello-world function
175
- buddy make:view hello-world # bootstraps a hello-word page
176
- buddy make:model Car # bootstraps a Car model
177
- buddy make:database cars # prints guidance: tables come from models + migrations, there is no separate create step
178
- buddy make:migration create_cars_table # creates a cars migration file
179
- buddy make:factory cars # creates a Car factory file
180
- buddy make:notification welcome-email # bootstraps a welcome-email notification
181
- buddy make:lang de # bootstraps a lang/de.yml language file
182
- buddy make:stack my-plugin # scaffolds a project-shaped registry stack (new project? use `panx buddy new`)
183
-
184
- buddy migrate # runs database migrations
185
- buddy migrate:fresh # drops all tables & re-runs migrations (destroys all data; --seed reseeds)
186
- buddy dns:pull # prints the live zone as a ./config/dns.ts block
187
- buddy seed # runs database seeders
188
-
189
- buddy dns example.com # list all DNS records for example.com
190
- buddy dns example.com --type MX # list MX records for example.com
191
-
192
- buddy http example.com/api/hello # sends a GET request & prints the response
193
- buddy http -v example.com/api/get # same, with verbose output
194
-
195
- buddy lint # runs linter
196
- buddy lint:fix # runs linter and fixes issues
197
- buddy format # formats your project codebase
198
- buddy format:check # checks formatting without making changes
199
-
200
- buddy commit # follow CLI prompts for committing staged changes
201
- buddy release # creates the releases for the stack & triggers the Release Action (workflow)
202
- buddy changelog # generates CHANGELOG.md
203
-
204
- # when deploying your app/s to a remote server or cloud provider
205
- buddy deploy # select a specific deployment (follow CLI prompts)
206
- buddy undeploy # be careful: "undeploys" removes/deletes your deployed resources (--yes skips the confirmation)
207
-
208
- buddy cloud:remove # removes cloud setup
209
- buddy cloud:cleanup # removes cloud setup & cleans up all potentially leftover resources
210
- buddy cloud:add --jump-box # adds a jump box to your cloud setup
211
-
212
- # you likely won’t need to run these commands as they are auto-triggered, but they are available
213
- buddy generate # prompts you to select which generator to run
214
- buddy generate:types # generates types for your components, functions, & views
215
- buddy generate:entries # generates entry files for components, functions, & views
216
- buddy generate:web-types # generates Web Component types
217
- buddy generate:vscode-custom-data # generates VSCode custom data
218
- buddy generate:ide-helpers # generates IDE helpers
219
- buddy generate:component-meta # generates component meta
220
-
221
- # generates your application key
222
- buddy key:generate # generates your application key
223
-
224
- # manage your environment variables
225
- buddy env:get # get an environment variable
226
- buddy env:set # set an environment variable
227
- buddy env:encrypt # encrypt an environment variable
228
- buddy env:decrypt # decrypt an environment variable
229
- buddy env:keypair # generate a keypair
230
- buddy env:rotate # rotate a keypair
231
-
232
- # generate your TypeScript declarations
233
- buddy types:generate # generates types for your components, functions, & views
234
- buddy types:fix # auto-fixes types for your components, functions, & views
235
-
236
- buddy domains:add stacksjs.com # adds a domain
237
- buddy domains:remove stacksjs.com # removes a domain
238
- buddy domains:purchase stacksjs.com # purchase a new domain
239
-
240
- # handy utilities
241
- buddy doctor # runs health checks on your Stacks installation
242
- buddy list # lists all available Buddy commands
243
- buddy route:list # lists your routes
244
- buddy ports # checks your project for port issues & misconfigurations
245
- buddy outdated # lists outdated project dependencies
246
- buddy env:check # checks your environment configuration & validates setup
247
- buddy tinker # interactive REPL with the Stacks framework preloaded
248
- buddy down # puts the app into maintenance mode
249
- buddy up # brings the app out of maintenance mode
250
-
251
- # test your stack
252
- buddy test # runs your test suite
253
- buddy test:unit # runs unit tests
254
- buddy test:feature # runs feature tests
255
- buddy test:types # runs typecheck
256
-
257
- # the published @stacksjs/buddy package ships
258
- # `buddy`, `bud`, & `stx` bins; inside this repo
259
- # the CLI is invoked as ./buddy
260
- ./buddy fresh
261
- ```
262
-
263
- </details>
264
-
265
- Read more about the Buddy CLI in the [official docs](https://stacksjs.com/docs/guide/buddy/commands): every command, every flag, every prompt explained.
266
-
267
- ## Features
268
-
269
- The Stacks framework is a harmony of several “engines” to build any web and/or desktop application, in highly scalable & privacy-friendly ways. It consists of the following engines:
270
-
271
- ### Frontend Development
272
-
273
- _Develop dynamic UIs with helpers for atomic design, and much more._
274
-
275
- - 🧩 **Components** _primitive to develop user interfaces_
276
- - 🤖 **Functions** _primitive to develop business logic (and grant your UI superpowers)_
277
- - 🎨 **UI Kit** _modern & deeply-integrated components_
278
- - 🌐 **Web** _“a routing & templating engine that makes sense”_
279
- - 🖥️ **Desktop** _transforms your web app into a desktop app, plus more_
280
- - 📝 **Documentation** _markdown-based documentation, auto-generated_
281
- - 📚 **Library** _auto-builds & manages component & function libraries_
282
- - ⚡️ Powered by Bun, Craft, Headwind
283
-
284
- ### Backend Development
285
-
286
- _Develop serverless (or server) functions with countless helpers to build scalable & fast APIs._
287
-
288
- - 🪄 **AI** _deep AI integrations to simplify building agentic workflow_
289
- - 🤖 **APIs** _scalability & maintainability built-in_
290
- - 🏎️ **Cache** _unified caching for DynamoDB, Redis and more_
291
- - ⚙️ **CLIs** _create beautiful CLIs for Linux, Windows, and Mac (dependency-free binaries)_
292
- - 🛍️ **Commerce** _own & grow your own online business with ease (SaaS-optimized)_
293
- - 📀 **Database** _DynamoDB, SQLite, MySQL, Postgres, and more_
294
- - 👾 **Errors** _native type-safe error handling_
295
- - 🗓️ **Events** _functional event (front & backend) communication_
296
- - 📢 **Notifications** _emails, SMSs, direct, and push notifications & webhooks_
297
- - 🗺️ **ORM** _automated schemas for scale & a pretty API_
298
- - 💳 **Payments** _unified API for one-off & subscription billing methods for Stripe_
299
- - ⚙️ **Queues** _run any heavy workload in the background_
300
- - 🛠️ **Query Builder** _powerful, type-safe SQL query builder_
301
- - 💬 **Realtime** _“everything you need to build dynamic real-time apps”_
302
- - 🧭 **Router** _smart routing, file-based or Laravel-like_
303
- - 🔎 **Search Engine** _smart searching, advanced filtering & sorting, pagination, headless UI_
304
- - 💾 **Storage** _a secure-by-default File API that feels right_
305
- - 🧪 **Tinker** _a powerful TypeScript REPL_
306
- - 🌪️ **Validation** _e2e type-safety (true frontend & backend harmony)_
307
-
308
- ### Cloud Development
309
-
310
- _Develop & maintain cloud infrastructure with ease. “Imagine Vercel, Vapor and Forge having been unified.”_
311
-
312
- - ☁️ **Server** _local development server & production-ready servers out-of-the-box_
313
- - ⛅️ **Serverless** _on-demand, auto-scaling, zero maintenance_
314
- - ⏰ **Alarms** _built-in cloud infrastructure monitoring to avoid surprises_
315
- - 🚏 **CDN** _zero-config, low-latency, request life-cycle hooks, optimized request compressions (Brotli & gzip)_
316
- - 🔀 **Domain** _version-controlled & zero-config domain management (e.g. DNS management)_
317
- - 🤖 **AI** _fine-tune a foundational model using your application data_
318
- - 📧 **Email** _secure & zero-setup <easy-peasy@custom-domains.com> mailboxes_
319
- - 🔐 **Firewall** _native web application firewall support_
320
- - 📦 **Storage** _unlimited cloud storage & automatic backups_
321
- - 🚜 **Maintenance** _maintain your cloud infrastructure with ease using Buddy & Stacks_
322
- - 🚦 **Infrastructure as Code** _version-controlled cloud infrastructure (AWS, Google next?)_
323
-
324
- ### CI/CD
325
-
326
- _Focus on coding, not publishing._
327
-
328
- - 🚀 **Deployment Manager** _takes the sweat out of production deployments—zero-setup push-to-deploy_
329
- - 0️⃣ **Zero Downtime** _deploy with confidence using a zero-downtime deployment strategy_
330
- - 📫 **Release Manager** _libraries (component & function) auto-published to npm, git helpers, and more_
331
-
332
- ### Developer Experience (DX)
333
-
334
- Convention over configuration, while staying wholly configurable. _No more boilerplate._
335
-
336
- - 🧠 **LLM-Friendly Authoring** _models generate compact application intent instead of repeating framework glue or reading `node_modules`_
337
- - 💎 **Automated Upgrades** _no need to worry about upgrading to the latest versions, Stacks upgrades you_
338
- - 🦋 **Pretty Dev URLs** _your-project.localhost instead of localhost:3000_
339
- - 💡 **IDE Integration** _auto-completions, inline docs & a powerful IDE setup_
340
- - 🪄 **Zero-Config** _yet highly configurable—convention over configuration_
341
- - 💅 **Linter & Formatter** _auto-configured & built into your IDE_
342
- - 💪🏼 **Type Strong** _built-in e2e type-safety_
343
- - ✨ **Git Workflows** _committing with ease_
344
- - 🚗 **Auto Imports** _your components & functions, including date, string, array, & object helpers_
345
- - ⏩ **Code Snippets** _goodbye to the boilerplate code—thank you Sarah Drasner_
346
- - 🔤 **Spell Checker** _be notified once there are typos_
347
- - 🛠️ **Essential Utilities** _powers at your fingertips. Collections, STX composables, and more_
348
- - 👥 **Team Management** _manage your team & their permissions_
349
- - 🧪 **Streamlined Testing** _unit, feature & component tests powered by Bun & very-happy-dom_
350
-
351
- No matter whether you are a beginner or an expert, the approachable Stacks design allows you to learn at your own pace, using our thorough documentation covering every aspect of the framework. Stacks is extremely beginner & expert-friendly.
352
-
353
- Develop beautiful, reactive, composable UIs without learning a new set of languages. HTML, CSS, and minimal JavaScript—that’s all you need to dive in now! _Or TypeScript ✌🏼_
354
-
355
- > _An actual rapid application development framework for all Full Stack needs. Next-level simplicity & DX._
356
-
357
- ## Testing
358
-
359
- ```bash
360
- ./buddy test
361
- ```
362
-
363
- ## Changelog
364
-
365
- Please see our [releases](https://github.com/stacksjs/stacks/releases) page for more information on what has changed recently.
366
-
367
- ## Contributing
368
-
369
- Please see the [Contributing Guide](https://github.com/stacksjs/contributing) for details.
370
-
371
- ## Community
372
-
373
- For help, discussion about best practices, or any other conversation that would benefit from being searchable:
374
-
375
- [Discussions on GitHub](https://github.com/stacksjs/stacks/discussions)
376
-
377
- For casual chit-chat with others using this package:
378
-
379
- [Join the Stacks Discord Server](https://stacksjs.com/discord)
380
-
381
- To hear when 1.0 lands, leave your email at [stacksjs.com](https://stacksjs.com). The site is in
382
- its pre-launch state, so that signup is currently the shortest path to being told when
383
- something changes.
384
-
385
- ## Postcardware
386
-
387
- “Software that is free, but hopes for a postcard.” We love receiving postcards from around the world showing where Stacks is being used! We showcase them on our website too.
388
-
389
- Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States 🌎
390
-
391
- ## Sponsors
392
-
393
- We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
394
-
395
- - [JetBrains](https://www.jetbrains.com/)
396
- - [The Solana Foundation](https://solana.com/)
397
-
398
- ## Credits
399
-
400
- - [Laravel](https://laravel.com) _many thanks to their community_
401
- - [Chris Breuer](https://github.com/chrisbbreuer)
402
- - [All Contributors](../../contributors)
403
-
404
- And a special thanks to [Dan Scanlon](https://twitter.com/danscan) for donating the `stacks` name on npm ✨
405
-
406
- ## License
407
-
408
- The MIT License (MIT). Please see [LICENSE](LICENSE.md) for more information.
409
-
410
- Made with 💙
411
-
412
- <!-- Badges -->
413
- [npm-version-src]: https://img.shields.io/npm/v/stacks?style=flat-square
414
- [npm-version-href]: https://npmjs.com/package/stacks
415
-
416
- [npm-downloads-src]: https://img.shields.io/npm/dm/stacks?style=flat-square
417
- [npm-downloads-href]: https://npmjs.com/package/stacks
418
-
419
- [github-actions-src]: https://img.shields.io/github/actions/workflow/status/stacksjs/stacks/ci.yml?style=flat-square&branch=main
420
- [github-actions-href]: https://github.com/stacksjs/stacks/actions?query=workflow%3Aci
421
-
422
- <!-- [codecov-src]: https://img.shields.io/codecov/c/gh/stacksjs/stacks/main?style=flat-square
423
- [codecov-href]: https://codecov.io/gh/stacksjs/buddy -->
1
+ # Stacks Utils
2
+
3
+ Import individual helpers from `@stacksjs/utils/<entry>` or the package root.
4
+
5
+ - `isDeepEqual` compares cyclic structures without requiring identical sharing
6
+ or cycle topology. Own object keys must match. Array holes differ from own
7
+ undefined slots. Dates, Maps, Sets and binary data compare by value; host
8
+ objects such as URLs retain identity semantics.
9
+ - `safeJsonStringify` replaces ancestor cycles with `[Circular]` and converts
10
+ BigInts to decimal strings. Shared non-cyclic values serialize fully. The
11
+ return type is `string | undefined`, as unsupported JSON roots yield undefined.
12
+ User getters and `toJSON` methods can still throw.
13
+ - `debounce` and `throttle` preserve arguments and receivers. Calls return the
14
+ latest callback result, or undefined before an invocation. Debounce `flush()`
15
+ invokes pending work and returns its result, even with `trailing: false`.
16
+ Reentrant callbacks retain newly queued work. Both offer `cancel()`; throttle
17
+ cancellation resets its interval. Async results remain Promises.
18
+ - `merge` reads only own enumerable string keys. Arrays concatenate; plain
19
+ records recursively merge. Non-plain nested values retain identity. A plain
20
+ source record replaces a non-plain target; `__proto__` is skipped.
21
+ - `parseBytes` requires a complete decimal with an optional recognized decimal
22
+ or binary unit. It accepts fractions and negative values, rejects unknown
23
+ units and partial input, and rejects non-finite results.
24
+
25
+ Regression coverage lives in `tests/*state-contracts.test.ts`. `state-e2e.test.ts`
26
+ runs real HTTP and Chrome consumers with SQLite, the native request cursor
27
+ parser and memory storage. `published-state-contracts.test.ts` builds the package
28
+ and checks its runtime exports and declarations in an isolated consumer.
package/dist/bytes.js CHANGED
@@ -1 +1 @@
1
- const DECIMAL_UNITS=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],BINARY_UNITS=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];export function formatBytes(bytes,options={}){const{precision=1,binary=!1,space=!0,locale="en-US",minimumFractionDigits=0,maximumFractionDigits=precision}=options;if(!Number.isFinite(bytes))throw TypeError(`Expected a finite number, got ${typeof bytes}: ${bytes}`);const isNegative=bytes<0,prefix=isNegative?"-":"";if(isNegative)bytes=-bytes;if(bytes<1){const numberString=bytes.toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits});return`${prefix}${numberString}${space?" ":""}B`}const base=binary?1024:1000,units=binary?BINARY_UNITS:DECIMAL_UNITS,exponent=Math.min(Math.floor(Math.log(bytes)/Math.log(base)),units.length-1),numberString=(bytes/base**exponent).toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits}),unit=units[exponent];return`${prefix}${numberString}${space?" ":""}${unit}`}export function parseBytes(input){const match=input.match(/^(-?[\d.]+)\s*([A-Za-z]+)?$/);if(!match)throw Error(`Invalid byte string: ${input}`);const[,numberStr,unit="B"]=match;if(numberStr===void 0)throw Error(`Invalid byte string: ${input}`);const number=Number.parseFloat(numberStr);if(!Number.isFinite(number))throw Error(`Invalid number in byte string: ${numberStr}`);const normalizedUnit=unit.toUpperCase(),isBinary=normalizedUnit.endsWith("IB"),base=isBinary?1024:1000;let exponent=0;const units=isBinary?BINARY_UNITS:DECIMAL_UNITS;for(let i=0;i<units.length;i++)if(units[i]?.toUpperCase()===normalizedUnit){exponent=i;break}return number*base**exponent}export function compareBytes(a,b){const bytesA=typeof a==="string"?parseBytes(a):a,bytesB=typeof b==="string"?parseBytes(b):b;return bytesA-bytesB}export const prettyBytes=formatBytes,readableSize=formatBytes;export{formatBytes as default};
1
+ const DECIMAL_UNITS=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],BINARY_UNITS=["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];export function formatBytes(bytes,options={}){const{precision=1,binary=!1,space=!0,locale="en-US",minimumFractionDigits=0,maximumFractionDigits=precision}=options;if(!Number.isFinite(bytes))throw TypeError(`Expected a finite number, got ${typeof bytes}: ${bytes}`);const isNegative=bytes<0,prefix=isNegative?"-":"";if(isNegative)bytes=-bytes;if(bytes<1){const numberString=bytes.toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits});return`${prefix}${numberString}${space?" ":""}B`}const base=binary?1024:1000,units=binary?BINARY_UNITS:DECIMAL_UNITS,exponent=Math.min(Math.floor(Math.log(bytes)/Math.log(base)),units.length-1),numberString=(bytes/base**exponent).toLocaleString(locale,{minimumFractionDigits,maximumFractionDigits}),unit=units[exponent];return`${prefix}${numberString}${space?" ":""}${unit}`}export function parseBytes(input){const match=input.trim().match(/^(-?(?:\d+(?:\.\d*)?|\.\d+))\s*([A-Za-z]+)?$/);if(!match)throw Error(`Invalid byte string: ${input}`);const[,numberStr,unit="B"]=match;if(numberStr===void 0)throw Error(`Invalid byte string: ${input}`);const number=Number(numberStr);if(!Number.isFinite(number))throw Error(`Invalid number in byte string: ${numberStr}`);const normalizedUnit=unit.toUpperCase(),isBinary=normalizedUnit.endsWith("IB"),base=isBinary?1024:1000,exponent=(isBinary?BINARY_UNITS:DECIMAL_UNITS).findIndex((value)=>value.toUpperCase()===normalizedUnit);if(exponent<0)throw Error(`Unknown byte unit: ${unit}`);const bytes=number*base**exponent;if(!Number.isFinite(bytes))throw RangeError("Byte value out of range");return bytes}export function compareBytes(a,b){const bytesA=typeof a==="string"?parseBytes(a):a,bytesB=typeof b==="string"?parseBytes(b):b;return bytesA-bytesB}export const prettyBytes=formatBytes,readableSize=formatBytes;export{formatBytes as default};
@@ -7,7 +7,7 @@
7
7
  * @param options - Options object
8
8
  * @returns The debounced function
9
9
  */
10
- export declare function debounce<T extends (..._args: any[]) => any>(fn: T, wait?: number, options?: DebounceOptions): T & { cancel: () => void; flush: () => void };
10
+ export declare function debounce<T extends Callback>(fn: T, wait?: number, options?: DebounceOptions): DebouncedFunction<T>;
11
11
  /**
12
12
  * Creates a throttled function that only invokes func at most once per every wait milliseconds
13
13
  *
@@ -15,7 +15,7 @@ export declare function debounce<T extends (..._args: any[]) => any>(fn: T, wait
15
15
  * @param wait - The number of milliseconds to throttle
16
16
  * @returns The throttled function
17
17
  */
18
- export declare function throttle<T extends (...args: any[]) => any>(fn: T, wait?: number): T & { cancel: () => void };
18
+ export declare function throttle<T extends Callback>(fn: T, wait?: number): ThrottledFunction<T>;
19
19
  /**
20
20
  * Delays execution of a function
21
21
  */
@@ -27,3 +27,7 @@ export declare interface DebounceOptions {
27
27
  leading?: boolean
28
28
  trailing?: boolean
29
29
  }
30
+ declare type Callback = (...args: any[]) => any;
31
+ declare type ControlledCall<T extends Callback> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T> | undefined;
32
+ export type DebouncedFunction<T extends Callback> = ControlledCall<T> & { cancel: () => void, flush: () => ReturnType<T> | undefined }
33
+ export type ThrottledFunction<T extends Callback> = ControlledCall<T> & { cancel: () => void }
package/dist/debounce.js CHANGED
@@ -1 +1 @@
1
- export function debounce(fn,wait=0,options={}){const{leading=!1,trailing=!0}=options;let timeout=null,lastArgs=null,lastThis=null,result;const invokeFunc=()=>{if(lastArgs){result=fn.apply(lastThis,lastArgs);lastArgs=null;lastThis=null}return result},cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null},flush=()=>{if(timeout){clearTimeout(timeout);timeout=null;return invokeFunc()}return result},debounced=function(...args){lastArgs=args;lastThis=this;const shouldCallNow=leading&&!timeout;if(timeout)clearTimeout(timeout);timeout=setTimeout(()=>{timeout=null;if(trailing&&lastArgs)invokeFunc()},wait);if(shouldCallNow)return invokeFunc();return result};debounced.cancel=cancel;debounced.flush=flush;return debounced}export function throttle(fn,wait=0){let timeout=null,lastRun=0,lastArgs=null,lastThis=null;const invokeFunc=()=>{if(lastArgs){fn.apply(lastThis,lastArgs);lastArgs=null;lastThis=null;lastRun=Date.now()}},cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null},throttled=function(...args){lastArgs=args;lastThis=this;const timeSinceLastRun=Date.now()-lastRun;if(timeSinceLastRun>=wait)invokeFunc();else if(!timeout)timeout=setTimeout(()=>{timeout=null;invokeFunc()},wait-timeSinceLastRun)};throttled.cancel=cancel;return throttled}export function delay(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}
1
+ export function debounce(fn,wait=0,options={}){const{leading=!1,trailing=!0}=options;let timeout=null,lastArgs=null,lastThis=null,result;const invokeFunc=()=>{if(lastArgs){const args=lastArgs,receiver=lastThis;lastArgs=null;lastThis=null;result=fn.apply(receiver,args)}return result},cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null},flush=()=>{if(timeout){clearTimeout(timeout);timeout=null;return invokeFunc()}return result},debounced=function(...args){lastArgs=args;lastThis=this;const shouldCallNow=leading&&!timeout;if(timeout)clearTimeout(timeout);timeout=setTimeout(()=>{timeout=null;if(trailing&&lastArgs)invokeFunc();else{lastArgs=null;lastThis=null}},wait);if(shouldCallNow)return invokeFunc();return result};debounced.cancel=cancel;debounced.flush=flush;return debounced}export function throttle(fn,wait=0){let timeout=null,lastRun,lastArgs=null,lastThis=null,result;const invokeFunc=()=>{if(lastArgs){const args=lastArgs,receiver=lastThis;lastArgs=null;lastThis=null;lastRun=Date.now();result=fn.apply(receiver,args)}return result},cancel=()=>{if(timeout){clearTimeout(timeout);timeout=null}lastArgs=null;lastThis=null;lastRun=void 0},throttled=function(...args){lastArgs=args;lastThis=this;const now=Date.now(),timeSinceLastRun=lastRun===void 0?1/0:now-lastRun;if(timeSinceLastRun>=wait||timeSinceLastRun<0){if(timeout){clearTimeout(timeout);timeout=null}return invokeFunc()}else if(!timeout)timeout=setTimeout(()=>{timeout=null;invokeFunc()},wait-timeSinceLastRun);return result};throttled.cancel=cancel;return throttled}export function delay(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}
package/dist/equal.d.ts CHANGED
@@ -6,9 +6,10 @@
6
6
  * `[NaN, NaN]` pair compared element-by-element worked, but compound
7
7
  * structures relied on the tail. The new shape preserves that.
8
8
  * - Circular references used to send isDeepEqual into infinite recursion
9
- * (`a.self = a; isDeepEqual(a, a)` blew the stack). A WeakSet of
10
- * already-visited objects breaks the cycle and treats two structurally
11
- * identical cycles as equal.
9
+ * (`a.self = a; isDeepEqual(a, a)` blew the stack). Active object pairs
10
+ * break cycles without requiring identical sharing/topology. A self-cycle
11
+ * and a longer cycle with the same fields are structurally equal. Pairs
12
+ * leave the active path after each branch, including failed candidates.
12
13
  * - Dates, regular expressions, Maps and Sets are compared by what they
13
14
  * HOLD. Only arrays and plain objects had branches, so everything else
14
15
  * fell through to the `Object.is` tail — which for an object means
@@ -27,3 +28,4 @@
27
28
  * what made the cases above wrong.
28
29
  */
29
30
  export declare function isDeepEqual(value1: unknown, value2: unknown, seen?: WeakMap<object, object>): boolean;
31
+ declare type ActivePairs = WeakMap<object, WeakSet<object>>;
package/dist/equal.js CHANGED
@@ -1 +1 @@
1
- import{getTypeName}from"@stacksjs/types";function unorderedMatch(a,b,matches){if(a.length!==b.length)return!1;const consumed=Array.from({length:b.length},()=>!1);for(const item of a){let found=!1;for(let i=0;i<b.length;i++){if(consumed[i])continue;if(matches(item,b[i])){consumed[i]=!0;found=!0;break}}if(!found)return!1}return!0}function mapsEqual(a,b,seen){if(a.size!==b.size)return!1;let sameKeys=!0;for(const key of a.keys())if(!b.has(key)){sameKeys=!1;break}if(sameKeys){for(const[key,value]of a)if(!isDeepEqual(value,b.get(key),seen))return!1;return!0}return unorderedMatch([...a.entries()],[...b.entries()],(x,y)=>isDeepEqual(x[0],y[0],seen)&&isDeepEqual(x[1],y[1],seen))}export function isDeepEqual(value1,value2,seen=new WeakMap){if(value1===value2)return!0;if(typeof value1==="number"&&typeof value2==="number"&&Number.isNaN(value1)&&Number.isNaN(value2))return!0;const type1=getTypeName(value1),type2=getTypeName(value2);if(type1!==type2)return!1;if(value1&&typeof value1==="object"){if(seen.get(value1)===value2)return!0;seen.set(value1,value2)}if(type1==="date")return Object.is(value1.getTime(),value2.getTime());if(type1==="regexp")return value1.source===value2.source&&value1.flags===value2.flags;if(type1==="map")return mapsEqual(value1,value2,seen);if(type1==="set")return unorderedMatch([...value1],[...value2],(x,y)=>isDeepEqual(x,y,seen));if(ArrayBuffer.isView(value1)&&ArrayBuffer.isView(value2)){const bytes1=new Uint8Array(value1.buffer,value1.byteOffset,value1.byteLength),bytes2=new Uint8Array(value2.buffer,value2.byteOffset,value2.byteLength);if(bytes1.length!==bytes2.length)return!1;return bytes1.every((byte,i)=>byte===bytes2[i])}if(type1==="arraybuffer"){const bytes1=new Uint8Array(value1),bytes2=new Uint8Array(value2);if(bytes1.length!==bytes2.length)return!1;return bytes1.every((byte,i)=>byte===bytes2[i])}if(Array.isArray(value1)&&Array.isArray(value2)){if(value1.length!==value2.length)return!1;return value1.every((item,i)=>isDeepEqual(item,value2[i],seen))}if(type1==="object"){const object1=value1,object2=value2,keyArr=Object.keys(object1);if(keyArr.length!==Object.keys(object2).length)return!1;return keyArr.every((key)=>isDeepEqual(object1[key],object2[key],seen))}return Object.is(value1,value2)}
1
+ import{getTypeName}from"@stacksjs/types";function unorderedMatch(a,b,matches){if(a.length!==b.length)return!1;const consumed=Array.from({length:b.length},()=>!1);for(const item of a){let found=!1;for(let i=0;i<b.length;i++){if(consumed[i])continue;if(matches(item,b[i])){consumed[i]=!0;found=!0;break}}if(!found)return!1}return!0}function mapsEqual(a,b,seen){if(a.size!==b.size)return!1;let sameKeys=!0;for(const key of a.keys())if(!b.has(key)){sameKeys=!1;break}if(sameKeys){for(const[key,value]of a)if(!equalValues(value,b.get(key),seen))return!1;return!0}return unorderedMatch([...a.entries()],[...b.entries()],(x,y)=>equalValues(x[0],y[0],seen)&&equalValues(x[1],y[1],seen))}export function isDeepEqual(value1,value2,seen){if(seen&&value1&&typeof value1==="object"&&seen.get(value1)===value2)return!0;const equal=equalValues(value1,value2,new WeakMap);if(equal&&value1&&typeof value1==="object"&&value2&&typeof value2==="object")seen?.set(value1,value2);return equal}function equalValues(value1,value2,seen){if(value1===value2)return!0;if(typeof value1==="number"&&typeof value2==="number"&&Number.isNaN(value1)&&Number.isNaN(value2))return!0;const type1=getTypeName(value1),type2=getTypeName(value2);if(type1!==type2)return!1;if(value1&&typeof value1==="object"&&value2&&typeof value2==="object"){let pairs=seen.get(value1);if(pairs?.has(value2))return!0;if(!pairs)seen.set(value1,pairs=new WeakSet);pairs.add(value2);try{return compareValues(value1,value2,type1,seen)}finally{pairs.delete(value2)}}return Object.is(value1,value2)}function compareValues(value1,value2,type1,seen){if(type1==="date")return Object.is(value1.getTime(),value2.getTime());if(type1==="regexp")return value1.source===value2.source&&value1.flags===value2.flags;if(type1==="map")return mapsEqual(value1,value2,seen);if(type1==="set")return unorderedMatch([...value1],[...value2],(x,y)=>equalValues(x,y,seen));if(ArrayBuffer.isView(value1)&&ArrayBuffer.isView(value2)){const bytes1=new Uint8Array(value1.buffer,value1.byteOffset,value1.byteLength),bytes2=new Uint8Array(value2.buffer,value2.byteOffset,value2.byteLength);if(bytes1.length!==bytes2.length)return!1;return bytes1.every((byte,i)=>byte===bytes2[i])}if(type1==="arraybuffer"){const bytes1=new Uint8Array(value1),bytes2=new Uint8Array(value2);if(bytes1.length!==bytes2.length)return!1;return bytes1.every((byte,i)=>byte===bytes2[i])}if(Array.isArray(value1)&&Array.isArray(value2)){if(value1.length!==value2.length)return!1;for(let index=0;index<value1.length;index++){const own=Object.hasOwn(value1,index);if(own!==Object.hasOwn(value2,index))return!1;if(own&&!equalValues(value1[index],value2[index],seen))return!1}return!0}if(type1==="object"){const object1=value1,object2=value2,keyArr=Object.keys(object1);if(keyArr.length!==Object.keys(object2).length)return!1;return keyArr.every((key)=>Object.prototype.propertyIsEnumerable.call(object2,key)&&equalValues(object1[key],object2[key],seen))}return Object.is(value1,value2)}
package/dist/merge.js CHANGED
@@ -1 +1 @@
1
- export function merge(...objects){const result={};for(const obj of objects){if(!obj||typeof obj!=="object")continue;for(const key in obj){if(key==="__proto__")continue;const value=obj[key],existing=result[key];if(value===void 0)continue;if(Array.isArray(value))result[key]=Array.isArray(existing)?[...existing,...value]:[...value];else if(value&&typeof value==="object"&&!isSpecialObject(value))result[key]=merge(existing||{},value);else result[key]=value}}return result}export function createMerger(defaults){return(...objects)=>{return merge(defaults,...objects)}}export function mergeDefaults(obj,...defaults){return merge({},...defaults,obj)}function isSpecialObject(obj){if(obj instanceof Date)return!0;if(obj instanceof RegExp)return!0;if(obj instanceof Error)return!0;if(obj instanceof Promise)return!0;if(obj instanceof Map)return!0;if(obj instanceof Set)return!0;if(obj instanceof WeakMap)return!0;if(obj instanceof WeakSet)return!0;if(ArrayBuffer.isView(obj))return!0;return!1}export const defu=mergeDefaults,defuArrayFn=merge;export{merge as default};
1
+ export function merge(...objects){const result={};for(const obj of objects){if(!obj||typeof obj!=="object")continue;for(const key of Object.keys(obj)){if(key==="__proto__")continue;const value=obj[key],existing=Object.hasOwn(result,key)?result[key]:void 0;if(value===void 0)continue;if(Array.isArray(value))result[key]=Array.isArray(existing)?[...existing,...value]:[...value];else if(isPlainObject(value))result[key]=merge(isPlainObject(existing)?existing:{},value);else result[key]=value}}return result}export function createMerger(defaults){return(...objects)=>{return merge(defaults,...objects)}}export function mergeDefaults(obj,...defaults){return merge({},...defaults,obj)}function isPlainObject(value){if(!value||typeof value!=="object")return!1;const prototype=Object.getPrototypeOf(value);if(prototype===null||prototype===Object.prototype)return!0;if(Object.getPrototypeOf(prototype)!==null)return!1;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;return typeof constructor==="function"&&Function.prototype.toString.call(constructor)===Function.prototype.toString.call(Object)}export const defu=mergeDefaults,defuArrayFn=merge;export{merge as default};
@@ -22,9 +22,10 @@ export declare function safeJsonParseResult<T = unknown>(text: unknown): { ok: t
22
22
  * with database IDs that overflow Number). This wrapper substitutes
23
23
  * `[Circular]` for cycles and converts bigints to strings — same shape
24
24
  * downstream consumers expect from a "best-effort serialize this for
25
- * logs" call.
25
+ * logs" call. Shared non-cyclic values serialize fully. Unsupported roots
26
+ * return undefined, as JSON.stringify does. User getters/toJSON can still throw.
26
27
  */
27
- export declare function safeJsonStringify(value: unknown, space?: number): string;
28
+ export declare function safeJsonStringify(value: unknown, space?: number): string | undefined;
28
29
  /**
29
30
  * Safe JSON wrappers.
30
31
  *
package/dist/safe-json.js CHANGED
@@ -1 +1 @@
1
- export function safeJsonParse(text,defaultValue){if(typeof text!=="string"||text.length===0)return defaultValue;try{return JSON.parse(text)}catch{return defaultValue}}export function safeJsonParseResult(text){if(typeof text!=="string")return{ok:!1,reason:"not-string"};if(text.length===0)return{ok:!1,reason:"empty"};try{return{ok:!0,value:JSON.parse(text)}}catch(err){return{ok:!1,reason:"malformed",error:err}}}export function safeJsonStringify(value,space){const seen=new WeakSet;return JSON.stringify(value,(_key,v)=>{if(typeof v==="bigint")return v.toString();if(v&&typeof v==="object"){if(seen.has(v))return"[Circular]";seen.add(v)}return v},space)}
1
+ export function safeJsonParse(text,defaultValue){if(typeof text!=="string"||text.length===0)return defaultValue;try{return JSON.parse(text)}catch{return defaultValue}}export function safeJsonParseResult(text){if(typeof text!=="string")return{ok:!1,reason:"not-string"};if(text.length===0)return{ok:!1,reason:"empty"};try{return{ok:!0,value:JSON.parse(text)}}catch(err){return{ok:!1,reason:"malformed",error:err}}}export function safeJsonStringify(value,space){const ancestors=[];return JSON.stringify(value,function(_key,v){if(typeof v==="bigint")return v.toString();if(v&&typeof v==="object"){while(ancestors.length&&ancestors.at(-1)!==this)ancestors.pop();if(ancestors.includes(v))return"[Circular]";ancestors.push(v)}return v},space)}
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.447",
5
+ "version": "0.75.450",
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.447",
66
- "@stacksjs/cli": "0.75.447",
67
- "@stacksjs/config": "0.75.447",
68
- "@stacksjs/enums": "0.75.447",
69
- "@stacksjs/error-handling": "0.75.447",
70
- "@stacksjs/logging": "0.75.447",
71
- "@stacksjs/path": "0.75.447",
72
- "@stacksjs/storage": "0.75.447",
73
- "@stacksjs/strings": "0.75.447",
74
- "@stacksjs/types": "0.75.447"
65
+ "@stacksjs/browser": "0.75.450",
66
+ "@stacksjs/cli": "0.75.450",
67
+ "@stacksjs/config": "0.75.450",
68
+ "@stacksjs/enums": "0.75.450",
69
+ "@stacksjs/error-handling": "0.75.450",
70
+ "@stacksjs/logging": "0.75.450",
71
+ "@stacksjs/path": "0.75.450",
72
+ "@stacksjs/storage": "0.75.450",
73
+ "@stacksjs/strings": "0.75.450",
74
+ "@stacksjs/types": "0.75.450"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/arrays": "0.75.447",
78
- "@stacksjs/lint": "0.75.447",
77
+ "@stacksjs/arrays": "0.75.450",
78
+ "@stacksjs/lint": "0.75.450",
79
79
  "better-dx": "^0.2.24",
80
80
  "filesize": "^11.0.25",
81
81
  "markdown-table": "^3.0.4"