schemasim 0.0.0-stage → 0.1.0

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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +270 -2
  3. package/dist/chunk-3HASZBJQ.js +228 -0
  4. package/dist/chunk-52WE5VVJ.js +781 -0
  5. package/dist/chunk-K3ZMJMF2.js +1 -0
  6. package/dist/chunk-MZ6VONVM.js +1927 -0
  7. package/dist/chunk-RSJ2MVTI.js +15652 -0
  8. package/dist/cli.js +22 -0
  9. package/dist/index.js +3 -0
  10. package/dist/node.js +5 -0
  11. package/dist/schemasim.browser.js +170 -0
  12. package/dist/types/check/html.d.ts +9 -0
  13. package/dist/types/check/report.d.ts +198 -0
  14. package/dist/types/check/stats.d.ts +40 -0
  15. package/dist/types/check/text.d.ts +11 -0
  16. package/dist/types/cli.d.ts +2 -0
  17. package/dist/types/columns.d.ts +10 -0
  18. package/dist/types/describe.d.ts +95 -0
  19. package/dist/types/engine/engine.d.ts +80 -0
  20. package/dist/types/engine/numeric.d.ts +61 -0
  21. package/dist/types/engine/record.d.ts +125 -0
  22. package/dist/types/engine/strings.d.ts +78 -0
  23. package/dist/types/engine/types.d.ts +184 -0
  24. package/dist/types/engine/value.d.ts +320 -0
  25. package/dist/types/errors.d.ts +32 -0
  26. package/dist/types/index.d.ts +42 -0
  27. package/dist/types/io/columns.d.ts +14 -0
  28. package/dist/types/io/delimited.d.ts +14 -0
  29. package/dist/types/io/format.d.ts +15 -0
  30. package/dist/types/io/index.d.ts +23 -0
  31. package/dist/types/io/json.d.ts +19 -0
  32. package/dist/types/io/node.d.ts +19 -0
  33. package/dist/types/io/parquet.d.ts +16 -0
  34. package/dist/types/io/shared.d.ts +79 -0
  35. package/dist/types/io/types.d.ts +71 -0
  36. package/dist/types/io/xlsx.d.ts +22 -0
  37. package/dist/types/json.d.ts +26 -0
  38. package/dist/types/node/cli.d.ts +18 -0
  39. package/dist/types/node/files.d.ts +66 -0
  40. package/dist/types/node/load.d.ts +25 -0
  41. package/dist/types/node.d.ts +22 -0
  42. package/dist/types/rng.d.ts +76 -0
  43. package/dist/types/schema/cond.d.ts +96 -0
  44. package/dist/types/schema/domain.d.ts +113 -0
  45. package/dist/types/schema/formats.d.ts +16 -0
  46. package/dist/types/schema/kinds.d.ts +55 -0
  47. package/dist/types/schema/model.d.ts +207 -0
  48. package/dist/types/schema/numset.d.ts +94 -0
  49. package/dist/types/schema/package.d.ts +117 -0
  50. package/dist/types/schema/resolve.d.ts +141 -0
  51. package/dist/types/schema/validate.d.ts +102 -0
  52. package/dist/types/simulate.d.ts +152 -0
  53. package/dist/types/spec/apply.d.ts +52 -0
  54. package/dist/types/spec/conditions.d.ts +38 -0
  55. package/dist/types/spec/dist.d.ts +41 -0
  56. package/dist/types/spec/expr.d.ts +44 -0
  57. package/dist/types/spec/issues.d.ts +27 -0
  58. package/dist/types/spec/marginal.d.ts +81 -0
  59. package/dist/types/spec/targets.d.ts +113 -0
  60. package/dist/types/spec/types.d.ts +366 -0
  61. package/dist/types/stats/distributions.d.ts +149 -0
  62. package/dist/types/stats/fit.d.ts +74 -0
  63. package/dist/types/stats/linalg.d.ts +67 -0
  64. package/dist/types/stats/special.d.ts +130 -0
  65. package/dist/types/template.d.ts +18 -0
  66. package/dist/types/text/automaton.d.ts +64 -0
  67. package/dist/types/text/charset.d.ts +18 -0
  68. package/dist/types/text/errors.d.ts +24 -0
  69. package/dist/types/text/language.d.ts +108 -0
  70. package/dist/types/text/regex-parse.d.ts +64 -0
  71. package/dist/types/version.d.ts +2 -0
  72. package/dist/types/worker.d.ts +1 -0
  73. package/dist/worker.js +21 -0
  74. package/package.json +84 -4
  75. package/schemas/spec.schema.json +2088 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeya Balaji Balasubramanian
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,271 @@
1
- # Temporary Holding Version
1
+ # <img src="site/logo.svg" alt="" width="32" height="32" align="absmiddle"> schemasim
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/schemasim)](https://www.npmjs.com/package/schemasim) [![CI](https://github.com/jeyabbalas/schemasim/actions/workflows/ci.yml/badge.svg)](https://github.com/jeyabbalas/schemasim/actions/workflows/ci.yml)
4
+
5
+ Simulate valid tabular datasets from the JSON Schema that describes them, and from whatever summary statistics you have.
6
+
7
+ **[Try it in the browser](https://jeyabbalas.github.io/schemasim/)** · [Guide](docs/guide.md) · [Specification reference](docs/specification.md) · [API and command line](docs/api.md) · [Examples](examples)
8
+
9
+ schemasim reads a JSON Schema that describes a table as an array of records: its variables, code lists, ranges, skip patterns, special codes and nested values. It writes records that are valid against that schema, every one of them. If you also tell it what you know about the data (the figures of a Table 1, a few odds ratios, how much is missing and why), the simulated data follow that too.
10
+
11
+ It is written for cancer epidemiology, where a dataset is more than columns of numbers:
12
+
13
+ - **Skip patterns.** A never-smoker has no number of cigarettes per day. schemasim reads the `if`/`then` rules of the schema and honours them, including stacked ones (a question gated by a question that is itself gated).
14
+ - **Special codes.** `-666` not applicable, `-888` don't know, `-999` refused: schemasim tells them apart from answers and from each other. "Not applicable" appears exactly where a rule calls for it; "refused" appears only as often as you ask.
15
+ - **Nested values.** Lists of entries (pregnancies, follow-up visits), lists of codes (tick all that apply), groups and lookups are simulated in place, with rules that reach into and out of them, and with repeated measurements that hang together within a person.
16
+ - **Missing data.** Missing completely at random, at random or not at random, written as the variable's own missing code, as `null`, or by leaving the property out.
17
+ - **Effect sizes you can find again.** Odds ratios, rate ratios, hazard ratios and slopes go in as a paper reports them. A regression on the simulated data gives them back.
18
+
19
+ No real record is involved at any point. schemasim never looks at data: what goes in is a schema and numbers that you type.
20
+
21
+ ## Install
22
+
23
+ schemasim is [on npm](https://www.npmjs.com/package/schemasim). It needs Node.js 22 or later.
24
+
25
+ ```sh
26
+ npm install -g schemasim # the "schemasim" command, as the examples below use it
27
+ npm install schemasim # into a project: the library, and the command as "npx schemasim"
28
+ npx schemasim --help # the command line without installing anything
29
+ ```
30
+
31
+ The development version, ahead of the latest release, installs from GitHub and builds itself on the way: `npm install github:jeyabbalas/schemasim`.
32
+
33
+ ## Five minutes on the command line
34
+
35
+ The [`examples/smoking-survey`](examples/smoking-survey) folder holds a ten-variable schema with two skip patterns.
36
+
37
+ ```sh
38
+ # 1. What does the schema say? Variable names, levels, which codes are special, the rules.
39
+ schemasim describe smoking-survey.schema.json
40
+
41
+ # 2. Simulate straight away. Valid, but with every answer equally likely.
42
+ schemasim simulate smoking-survey.schema.json -n 1000 -o survey.csv
43
+
44
+ # 3. Write down what you know. "init" gives a file that spells out every default.
45
+ schemasim init smoking-survey.schema.json -o survey.spec.json
46
+
47
+ # 4. Check it before you simulate: errors, then asked against simulated for every variable.
48
+ schemasim check smoking-survey.schema.json -s survey.spec.json --html check.html
49
+
50
+ # 5. Simulate.
51
+ schemasim simulate smoking-survey.schema.json -s survey.spec.json -n 100000 -o survey.parquet
52
+ ```
53
+
54
+ `<schema>` is the index schema file, or a folder with the schema files anywhere in it (the files they refer to are found automatically).
55
+
56
+ ### The output of schemify, as it is
57
+
58
+ Give schemasim the whole folder that the [schemify](https://github.com/jeyabbalas/skills) skill wrote, or a clone of the repository it is kept in. Only the schema files are read. Toy data, ledgers, web pages, scripts and project state are passed over, wherever they lie:
59
+
60
+ ```sh
61
+ schemasim describe my-study/
62
+ schemasim simulate my-study/ -n 1000 -o my-study.csv
63
+ ```
64
+
65
+ A folder can describe several tables. schemasim then lists them and asks which one you mean. Name it with `--root`, or give its index schema file in place of the folder:
66
+
67
+ ```sh
68
+ schemasim simulate my-study/ --root visits.schema.json -n 1000 -o visits.csv
69
+ schemasim simulate my-study/visits/visits.schema.json -n 1000 -o visits.csv
70
+ schemasim init my-study/ --root visits.schema.json -o visits.spec.json
71
+ ```
72
+
73
+ The first two lines do the same. The third writes `"root"` into the specification, so that the commands that take the specification need no `--root`.
74
+
75
+ The [demo](https://jeyabbalas.github.io/schemasim/) takes the same folder: drop it on the page or choose it, and pick the table from a list when there are several. The files are read by your browser and are not sent anywhere.
76
+
77
+ ## A specification
78
+
79
+ A specification is a JSON file. Everything in it is optional; a variable you do not mention keeps its default. This one is the core of [the survey example](examples/smoking-survey/smoking-survey.spec.json):
80
+
81
+ <!-- check: smoking-survey -->
82
+ ```json
83
+ {
84
+ "records": 2000,
85
+ "seed": 7,
86
+ "variables": {
87
+ "age": { "mean": 47, "sd": 16 },
88
+ "sex": { "probabilities": { "Male": 0.48, "Female": 0.52 } },
89
+ "ever_smoked": {
90
+ "probabilities": { "Refused": 0.01 },
91
+ "model": {
92
+ "type": "logistic",
93
+ "prevalence": 0.41,
94
+ "terms": [
95
+ { "variable": "sex", "level": "Male", "oddsRatio": 1.5 },
96
+ { "variable": "education", "level": "University degree", "oddsRatio": 0.55 }
97
+ ]
98
+ }
99
+ },
100
+ "smoking_status": {
101
+ "cases": [
102
+ { "when": { "age": { "max": 39 } }, "probabilities": { "Current smoker": 0.55, "Former smoker": 0.44, "Refused": 0.01 } },
103
+ { "probabilities": { "Current smoker": 0.3, "Former smoker": 0.69, "Refused": 0.01 } }
104
+ ]
105
+ },
106
+ "cigarettes_per_day": { "probabilities": { "Don't know": 0.03, "Refused": 0.01 }, "median": 12, "iqr": [7, 20] },
107
+ "pack_years": { "formula": "round(cigarettes_per_day / 20 * (age - age_started - coalesce(years_since_quit, 0)), 1)" }
108
+ },
109
+ "missing": { "variables": { "age_started": { "rate": 0.02 } } }
110
+ }
111
+ ```
112
+
113
+ Levels are named by their code or by their label in the schema. The skip pattern is not mentioned anywhere: it is in the schema, so never-smokers get `-666` for `smoking_status` and `cigarettes_per_day` whatever the specification says, and the probabilities describe the people who were asked.
114
+
115
+ | You know | You write | |
116
+ |---|---|---|
117
+ | Frequencies of a coded variable | `probabilities`, or `weights` for counts from a table | marginal |
118
+ | Mean and SD, or median and quartiles | `"mean": 56, "sd": 11` · `"median": 1.4, "iqr": [1.0, 2.1]` (17 families by name when you want one) | marginal |
119
+ | A different distribution by group | `cases` with `when` | conditional probability table |
120
+ | A cross-tabulation | `joint` | joint distribution |
121
+ | Correlations | `correlations` (Gaussian copula; margins are kept exactly) | joint distribution |
122
+ | A prevalence and odds ratios | `model`: logistic, ordinal, multinomial, linear, log-linear, Poisson, negative binomial, survival | regression |
123
+ | How a variable is derived | `formula` | deterministic |
124
+ | An unmeasured common cause, an event time before censoring | `latent` | helper variables |
125
+ | How many visits, pregnancies, tumours | `count`, with `ascending`, `sequence`, `include` | nested values |
126
+ | How much is missing and for whom | `missing`: a rate, rates by group, or a logistic model | MCAR, MAR, MNAR |
127
+
128
+ Chained `cases` over coded variables are the conditional probability tables of a Bayesian network. Models and formulas carry the same idea over to continuous variables, counts and times. The [specification reference](docs/specification.md) documents every key, and the [guide](docs/guide.md) explains when to use which.
129
+
130
+ ## Check before you simulate
131
+
132
+ `schemasim check` reports what is wrong with a specification (a misspelt variable, a level that does not exist, probabilities above 1, a formula that does not parse), each with the place and a suggestion. Then it simulates a pilot sample and sets it against what you asked for:
133
+
134
+ ```text
135
+ ever_smoked — categorical — Ever smoked 100 cigarettes
136
+ specified (model): logistic model for 1 (Yes): prevalence 0.41; oddsRatio 1.5 for sex = "Male"; oddsRatio 0.55 for education = "University degree"; special codes beside the model keep 1% of the records whatever the terms; the model decides among the others
137
+ simulated: n 2000 · missing 1.0%
138
+ fitted to 41% with 1 (Yes): simulated 39.7%
139
+ 0 No 59.7% ██████████████
140
+ 1 Yes 39.4% █████████
141
+ -999 Refused 1.0% ▏ (missing)
142
+
143
+ cigarettes_per_day — number (cigarettes per day) — Cigarettes per day
144
+ specified (marginal): -888 (Don't know) 3%, -999 (Refused) 1%; lognormal (median 12, mean 16.24, sd 14.82) (chosen because the upper quartile lies further from the median than the lower) 96%
145
+ simulated: n 2000 · not applicable 60.7% · missing 1.2%
146
+ values: n 763 · mean 15.3 (asked 15.58) · sd 12.27 (asked 12.39) · min 1 · p25 7 · median 12 · p75 20 · max 80
147
+ -0.5 ▄█▆▄▃▂▂▁▂▁▁▁ ▁ 69.5
148
+ -666 Not applicable (skipped by desig… 60.7% ███████████████ (n/a)
149
+ -888 Don't know 0.75% ▏ (missing) asked 3.0%, got 1.9% where it applies
150
+ -999 Refused 0.45% ▏ (missing) asked 1.0%, got 1.1% where it applies
151
+ ```
152
+
153
+ `--html` writes the same report as a self-contained page with a chart per variable, in which answers, "not applicable" and missing codes are drawn apart. The [demo](https://jeyabbalas.github.io/schemasim/) shows it live.
154
+
155
+ ## Output formats
156
+
157
+ | Format | Extension | Nested values | Notes |
158
+ |---|---|---|---|
159
+ | JSON | `.json` | as they are | an array of records; the default |
160
+ | NDJSON | `.ndjson` | as they are | one record per line |
161
+ | CSV, TSV | `.csv`, `.tsv` | as JSON text in the cell | UTF-8, RFC 4180 quoting |
162
+ | Excel | `.xlsx` | as JSON text in the cell | one sheet, at most 1,048,575 records |
163
+ | Parquet | `.parquet` | native lists and structs | column types from the schema; the format for large tables |
164
+
165
+ CSV, TSV, Excel and Parquet have one empty state, so `null` and a property that is left out both become an empty cell there. JSON and NDJSON keep them apart. Parquet files carry a `schemasim` metadata entry that says the data are simulated, with the seed.
166
+
167
+ ## Large datasets
168
+
169
+ Records are produced in batches and written as they are produced, so memory use does not grow with the size of the table. Record number *k* depends only on the seed and on *k*, which is what makes parallel runs possible: `--parts 8` writes eight files at once, and together they are exactly the dataset that one run would have written.
170
+
171
+ ```sh
172
+ schemasim simulate schemas/ -s study.spec.json -n 20000000 -o study.parquet --parts 8
173
+ ```
174
+
175
+ On a laptop (Apple M5 Pro), with every record validated against the schema before it is written:
176
+
177
+ | Example, each with its specification | Variables | One process | Eight parts |
178
+ |---|---|---|---|
179
+ | [Smoking survey](examples/smoking-survey), to CSV | 10 | 98,000 records/s | |
180
+ | [Cohort follow-up](examples/cohort-followup), to Parquet | 14 (1 nested), 4 rules | 39,000 records/s | 195,000 records/s |
181
+ | [Juniper Ridge](examples/juniper-ridge), to Parquet | 60 (6 nested), 45 rules | 8,300 records/s | 39,000 records/s |
182
+
183
+ From 100,000 records on, the command line writes Parquet unless you name another format. `--no-validate` skips the proof of validity for a little more speed.
184
+
185
+ ## As a library
186
+
187
+ The library runs in Node.js and in the browser. Nothing in the main entry touches the file system.
188
+
189
+ ```js
190
+ import { createSimulator, check, renderReportText } from 'schemasim';
191
+
192
+ const schemas = [{ uri: 'survey.schema.json', schema: surveySchema }];
193
+ const spec = { variables: { age: { mean: 47, sd: 16 } } };
194
+
195
+ // What is wrong with the specification, and what does it do?
196
+ const report = check({ schemas, spec, records: 2000 });
197
+ console.log(renderReportText(report)); // or renderReportHtml(report)
198
+
199
+ // Simulate.
200
+ const simulator = createSimulator({ schemas, spec, seed: 7 });
201
+ const records = simulator.records(1000); // an array of objects
202
+ const csv = await simulator.encode('csv', { records: 1000 }); // the bytes of a file
203
+ for (const batch of simulator.batches(1_000_000)) { /* 1,000 records at a time */ }
204
+ ```
205
+
206
+ `schemasim/node` adds reading schema packages from disk and writing files:
207
+
208
+ ```js
209
+ import { loadSchemas, loadSpec, simulateToFile, simulateToParts } from 'schemasim/node';
210
+
211
+ const schemas = await loadSchemas('schemas/');
212
+ const spec = await loadSpec('study.spec.json');
213
+ await simulateToFile({ schemas, spec, records: 50_000, output: 'study.parquet' });
214
+ await simulateToParts({ schemas, spec, records: 20_000_000, output: 'study.parquet', parts: 8 });
215
+ ```
216
+
217
+ `loadSchemas` takes what the command line takes: an index schema file, or a folder with the schema files anywhere in it. `loadSchemaPackage` also tells you which tables the folder describes and which files it passed over. In a browser, `readSchemaPackage` does the same sorting for the files of a folder that somebody dropped on your page.
218
+
219
+ In a page without a build step, import the single-file browser build from a CDN, pinned to a release so that it does not change under you:
220
+
221
+ ```html
222
+ <script type="module">
223
+ import { createSimulator } from 'https://cdn.jsdelivr.net/npm/schemasim@0.1.0/dist/schemasim.browser.js';
224
+ </script>
225
+ ```
226
+
227
+ A bundler finds the same file as `schemasim/browser`.
228
+
229
+ Other exports: `describe` and `renderDescriptionText` (what `schemasim describe` prints), `specTemplate` (what `schemasim init` writes), `createTableWriter` and `encodeTable` (the output formats on their own), `SchemaSet`, and `SchemaSimError` with a stable `code` and the list of `issues`. Types ship with the package, and the [API and command-line reference](docs/api.md) lists every function and option.
230
+
231
+ ## What the schema needs to look like
232
+
233
+ - JSON Schema draft 2020-12, with the table as `"type": "array"` whose `items` describe one record. **One index schema per dataset**; it may refer to any number of other files with `$ref`. A folder that describes several tables has one index schema for each, and `root` says which table to simulate.
234
+ - Coded variables as `enum`, `const`, or `oneOf`/`anyOf` of `const` with a `title` per level. Numbers with `minimum`, `maximum`, `multipleOf`. Text with `pattern`, `format`, `minLength`, `maxLength`.
235
+ - Rules as `if`/`then`/`else`, `allOf`, `anyOf`, `oneOf`, `not`, `dependentRequired`, `dependentSchemas`, at the record level or inside nested values. `additionalProperties` and `unevaluatedProperties` are honoured.
236
+ - Nested values as `type: object` (a group, or a lookup with `additionalProperties`/`patternProperties`) and `type: array` (lists of values or of entries, with `minItems`, `maxItems`, `uniqueItems`, `contains`).
237
+
238
+ Schemas written by the [schemify](https://github.com/jeyabbalas/skills) skill are the main target, and schemasim reads their annotations: `x-value-kind: "sentinel"` (a special code), `x-role` (`primary key`, `entity key`, `time key`: unique identifiers, numbered entries, rising dates), `x-unit`, `x-universe` and `x-variable-group` (shown in reports). Plain schemas without annotations work too: special codes are then recognised from their labels ("Not applicable", "Refused") and from conventional codes, `schemasim describe` shows how each one was read, and the `kinds` section of a specification corrects a wrong guess.
239
+
240
+ Text is generated from `pattern` for the regular expressions that identifiers and dates use in practice. A constraint that schemasim cannot generate from is reported, not ignored.
241
+
242
+ One thing to know about `multipleOf` with decimals: schemasim evaluates it in exact decimal arithmetic, so 171.7 is a multiple of 0.1. Validators that divide in floating point reject about a third of such values (Ajv does unless its `multipleOfPrecision` option is set), for real data as much as for simulated data. Stating the precision in the description and leaving `multipleOf` to whole numbers avoids the problem; the number of decimals written is then set by `decimals` in the specification.
243
+
244
+ ## What simulated data are for
245
+
246
+ Good uses: building and testing a pipeline before the real data arrive, exercising validation and harmonisation code against every skip pattern and special code, teaching, demonstrating a method on data that anyone may see, sizing storage and compute, and checking that an analysis plan recovers an effect of the size you expect.
247
+
248
+ Not a use: conclusions about the world. The data contain the associations you specified and no others. Variables you did not connect are independent, however strongly they go together in reality.
249
+
250
+ ## Documentation
251
+
252
+ - [Guide](docs/guide.md): the ideas, with epidemiological examples. Skip patterns and special codes, conditional distributions, models and calibration, time to event, longitudinal values, missing-data mechanisms.
253
+ - [Specification reference](docs/specification.md): every key, every distribution, every message.
254
+ - [API and command-line reference](docs/api.md): the functions, their options, the report, the output formats, the commands.
255
+ - [Examples](examples): three schemas with worked specifications.
256
+ - [`schemas/spec.schema.json`](schemas/spec.schema.json): the JSON Schema of the specification format. Point your editor at it with `"$schema": "https://jeyabbalas.github.io/schemasim/spec.schema.json"` to get completion and checks as you type.
257
+
258
+ ## Development
259
+
260
+ ```sh
261
+ npm install # also builds
262
+ npm test # vitest
263
+ npm run check # typecheck, build, test
264
+ npm run site # build the demo into site/dist
265
+ ```
266
+
267
+ The only runtime dependencies are [hyparquet-writer](https://github.com/hyparam/hyparquet-writer) (Parquet) and [fflate](https://github.com/101arrowz/fflate) (the zip container of Excel files). The JSON Schema validator, the statistical distributions, the formula language and the writers for the other formats are part of the library and have no dependencies.
268
+
269
+ ## License
270
+
271
+ MIT
@@ -0,0 +1,228 @@
1
+ import { SchemaSimError, Simulator, fileExtension, isFormat, FORMATS, formatFromPath, XLSX_MAX_RECORDS } from './chunk-RSJ2MVTI.js';
2
+ import { mkdirSync, createWriteStream, existsSync } from 'fs';
3
+ import { rm, readFile, stat } from 'fs/promises';
4
+ import { dirname, extname, join, basename } from 'path';
5
+ import { availableParallelism } from 'os';
6
+ import { fileURLToPath } from 'url';
7
+ import { Worker } from 'worker_threads';
8
+
9
+ function createFileSink(path) {
10
+ mkdirSync(dirname(path), { recursive: true });
11
+ const stream = createWriteStream(path);
12
+ let failure;
13
+ let opened = false;
14
+ stream.once("open", () => {
15
+ opened = true;
16
+ });
17
+ stream.on("error", (error) => {
18
+ failure ??= error;
19
+ });
20
+ return {
21
+ write(chunk) {
22
+ if (failure) throw failure;
23
+ if (stream.write(chunk)) return;
24
+ return new Promise((resolve, reject) => {
25
+ const settle = () => {
26
+ stream.off("drain", settle);
27
+ stream.off("error", settle);
28
+ if (failure) reject(failure);
29
+ else resolve();
30
+ };
31
+ stream.once("drain", settle);
32
+ stream.once("error", settle);
33
+ });
34
+ },
35
+ close() {
36
+ return new Promise((resolve, reject) => {
37
+ const settle = () => {
38
+ if (failure) reject(failure);
39
+ else resolve();
40
+ };
41
+ if (stream.closed) {
42
+ settle();
43
+ return;
44
+ }
45
+ stream.once("close", settle);
46
+ stream.end();
47
+ });
48
+ },
49
+ async discard() {
50
+ await new Promise((resolve) => {
51
+ if (stream.closed) {
52
+ resolve();
53
+ return;
54
+ }
55
+ stream.once("close", () => resolve());
56
+ stream.destroy();
57
+ });
58
+ if (opened) await rm(path, { force: true }).catch(() => void 0);
59
+ }
60
+ };
61
+ }
62
+ async function loadSpec(path) {
63
+ let text;
64
+ try {
65
+ text = await readFile(path, "utf8");
66
+ } catch (error) {
67
+ throw new SchemaSimError("io", `Cannot read the specification ${path}: ${error.message}`);
68
+ }
69
+ let value;
70
+ try {
71
+ value = JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
72
+ } catch (error) {
73
+ throw new SchemaSimError("spec", `${path} is not valid JSON: ${error.message}`);
74
+ }
75
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
76
+ throw new SchemaSimError("spec", `${path} must hold a JSON object (the specification).`);
77
+ }
78
+ return value;
79
+ }
80
+ function formatOf(output, format) {
81
+ if (format !== void 0 && !isFormat(format)) {
82
+ throw new SchemaSimError("usage", `Unknown format ${JSON.stringify(format)}. Formats: ${FORMATS.join(", ")}.`);
83
+ }
84
+ const chosen = format ?? formatFromPath(output);
85
+ if (!chosen) {
86
+ throw new SchemaSimError("usage", `Cannot tell the format of ${output} from its name. Use one of .json, .ndjson, .csv, .tsv, .xlsx, .parquet, or name the format.`);
87
+ }
88
+ return chosen;
89
+ }
90
+ async function writeWith(simulator, options, format) {
91
+ const count = options.records ?? simulator.defaultRecords;
92
+ const start = options.start ?? 0;
93
+ simulator.checkCount(count, start, options.total);
94
+ const started = performance.now();
95
+ const before = simulator.diagnostics.retried;
96
+ const writeOptions = { ...options.writer, records: count, start };
97
+ if (options.total !== void 0) writeOptions.total = options.total;
98
+ if (options.onProgress) writeOptions.onProgress = options.onProgress;
99
+ if (format === "xlsx" && count > XLSX_MAX_RECORDS) {
100
+ throw new SchemaSimError("usage", `Excel sheets hold at most ${XLSX_MAX_RECORDS.toLocaleString("en-US")} records and ${count.toLocaleString("en-US")} were asked for; use Parquet or CSV for larger datasets.`);
101
+ }
102
+ let written;
103
+ let sink;
104
+ try {
105
+ sink = createFileSink(options.output);
106
+ written = await simulator.write(format, sink, writeOptions);
107
+ } catch (error) {
108
+ await sink?.discard();
109
+ if (error instanceof SchemaSimError) throw error;
110
+ const code = error.code;
111
+ if (code !== void 0 && /^E[A-Z]+$/.test(code)) throw new SchemaSimError("io", `Cannot write ${options.output}: ${error.message}`);
112
+ if (error instanceof RangeError) throw new SchemaSimError("usage", error.message, void 0, { cause: error });
113
+ throw error;
114
+ }
115
+ const info = await stat(options.output);
116
+ return {
117
+ path: options.output,
118
+ format,
119
+ records: written,
120
+ start,
121
+ bytes: info.size,
122
+ milliseconds: performance.now() - started,
123
+ retried: simulator.diagnostics.retried - before,
124
+ issues: simulator.issues
125
+ };
126
+ }
127
+ async function simulateToFile(options) {
128
+ const { output, format, records, start, onProgress, writer, ...rest } = options;
129
+ const chosen = formatOf(output, format);
130
+ const simulator = new Simulator(rest);
131
+ const pass = { output };
132
+ if (records !== void 0) pass.records = records;
133
+ if (start !== void 0) pass.start = start;
134
+ if (onProgress) pass.onProgress = onProgress;
135
+ if (writer) pass.writer = writer;
136
+ return writeWith(simulator, pass, chosen);
137
+ }
138
+ function partPaths(output, parts, format) {
139
+ const extension = extname(output) || (format ? fileExtension(format) : "");
140
+ const stem = join(dirname(output), basename(output, extname(output)));
141
+ const width = Math.max(4, String(parts).length);
142
+ const pad = (n) => String(n).padStart(width, "0");
143
+ return Array.from({ length: parts }, (_, i) => `${stem}.part-${pad(i + 1)}-of-${pad(parts)}${extension}`);
144
+ }
145
+ async function runPart(job, onProgress) {
146
+ const simulator = new Simulator(job.options);
147
+ const pass = { output: job.output, records: job.records, start: job.start };
148
+ if (job.total !== void 0) pass.total = job.total;
149
+ if (job.writer) pass.writer = job.writer;
150
+ if (onProgress) pass.onProgress = (written) => onProgress(written);
151
+ return writeWith(simulator, pass, job.format);
152
+ }
153
+ function workerScript() {
154
+ try {
155
+ const here = fileURLToPath(import.meta.url);
156
+ if (!here.endsWith(".js")) return void 0;
157
+ const candidate = join(dirname(here), "worker.js");
158
+ return existsSync(candidate) ? candidate : void 0;
159
+ } catch {
160
+ return void 0;
161
+ }
162
+ }
163
+ async function simulateToParts(options) {
164
+ const { output, format, records, start = 0, onProgress, writer, parts, workers, ...rest } = options;
165
+ if (!Number.isInteger(parts) || parts < 1) throw new SchemaSimError("usage", "The number of parts must be a whole number, one or more.");
166
+ const chosen = formatOf(output, format);
167
+ const probe = new Simulator(rest);
168
+ const total = records ?? probe.defaultRecords;
169
+ probe.checkCount(total, start);
170
+ if (parts > Math.max(total, 1)) throw new SchemaSimError("usage", `${total} records cannot be split into ${parts} parts.`);
171
+ const paths = partPaths(output, parts, chosen);
172
+ const jobs = [];
173
+ const size = Math.floor(total / parts);
174
+ const extra = total - size * parts;
175
+ let next = start;
176
+ for (let i = 0; i < parts; i++) {
177
+ const count = size + (i < extra ? 1 : 0);
178
+ const job = { options: rest, output: paths[i], format: chosen, records: count, start: next, total: start + total };
179
+ if (writer) job.writer = writer;
180
+ jobs.push(job);
181
+ next += count;
182
+ }
183
+ const progress = new Array(parts).fill(0);
184
+ const report = (part, written) => {
185
+ progress[part] = written;
186
+ if (onProgress) onProgress(progress.reduce((sum, n) => sum + n, 0), total);
187
+ };
188
+ const results = new Array(parts);
189
+ const script = workerScript();
190
+ const lanes = Math.max(1, Math.min(workers ?? availableParallelism(), parts));
191
+ let cursor = 0;
192
+ const lane = async () => {
193
+ for (; ; ) {
194
+ const part = cursor++;
195
+ if (part >= parts) return;
196
+ const job = jobs[part];
197
+ if (!script || lanes === 1) {
198
+ results[part] = await runPart(job, (written) => report(part, written));
199
+ continue;
200
+ }
201
+ results[part] = await new Promise((resolve, reject) => {
202
+ const worker = new Worker(script, { workerData: job });
203
+ let settled = false;
204
+ worker.on("message", (message) => {
205
+ if (message.type === "progress") report(part, message.written);
206
+ else if (message.type === "done") {
207
+ settled = true;
208
+ resolve(message.result);
209
+ } else {
210
+ settled = true;
211
+ reject(message.code === "unknown" ? new Error(message.message) : new SchemaSimError(message.code, message.message));
212
+ }
213
+ });
214
+ worker.on("error", (error) => {
215
+ settled = true;
216
+ reject(error);
217
+ });
218
+ worker.on("exit", (code) => {
219
+ if (!settled) reject(new Error(`A worker stopped unexpectedly (exit code ${code}) while writing ${job.output}.`));
220
+ });
221
+ });
222
+ }
223
+ };
224
+ await Promise.all(Array.from({ length: lanes }, lane));
225
+ return results;
226
+ }
227
+
228
+ export { createFileSink, loadSpec, partPaths, runPart, simulateToFile, simulateToParts };