@larvit/fejkdata 0.0.0 → 0.9.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Timewave
4
+ Copyright (c) 2026 Larv IT AB
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,286 @@
1
+ # fejkdata
2
+
3
+ Fake data for tests. Related values match, like a postcode and its city. National ids pass
4
+ validation where possible.
5
+
6
+ ```sh
7
+ npm install @larvit/fejkdata
8
+ ```
9
+
10
+ It runs in Node 22.3 or later, in Bun, in Deno and in a browser. It is an ES module with
11
+ TypeScript types.
12
+
13
+ ```js
14
+ import { load } from "@larvit/fejkdata";
15
+
16
+ const fejkdata = await load();
17
+ console.log(fejkdata.render("{/sv_SE.person}", { seed: 1, today: "2026-01-15" }));
18
+ ```
19
+
20
+ ```text
21
+ Felix Östberg
22
+ ```
23
+
24
+ `render` returns what the [fejkdata CLI](https://github.com/larvit/fejkdata#cli) prints
25
+ for the same template, seed and day. The package is fejkdata built to WebAssembly, with all
26
+ its data. It doesn't fetch anything else when it runs, and it doesn't depend on any other
27
+ package. The [README](https://github.com/larvit/fejkdata#readme) documents templates and the
28
+ shipped data.
29
+
30
+ ## Size and speed
31
+
32
+ An install downloads 19 MB and unpacks to 69 MB, nearly all of it the data. Install the
33
+ package as a dev dependency, `npm install --save-dev @larvit/fejkdata`, and keep it out of a
34
+ page's bundle.
35
+
36
+ `load` reads and compiles the WebAssembly, which takes about 0.3 seconds in Node. Every call
37
+ of `load` shares that one compile. In a browser it fetches `fejkdata.wasm` from beside `index.js`.
38
+ Serve `index.js`, `wasm_exec.js` and `fejkdata.wasm` from one folder, the last as
39
+ `application/wasm`.
40
+
41
+ A test runner that starts a worker per test file loads the 69 MB WebAssembly again in each
42
+ worker. That takes about 0.3 seconds a worker.
43
+
44
+ Each call of `render`, `fake`, `records` or `paths` loads the data it reads again, which takes
45
+ about 0.1 seconds before its first row. With `files`, each call also loads every file you
46
+ gave, read or not: about 0.65 seconds for a 0.47 MB file. Keep the files small.
47
+ Ask for many rows with `repeat`, not with many calls. One call returns at most 512 MB of
48
+ text. `records` counts 32 bytes for each cell on top of its text.
49
+
50
+ ## Text
51
+
52
+ `load()` gives an object with four functions: `render`, `fake`, `records` and `paths`. None
53
+ of them keeps any state between calls.
54
+
55
+ `render(template, { seed, today, repeat, format })` returns a string.
56
+
57
+ - `template` is a string. It holds a format string or JSON text. Pass an object through
58
+ `JSON.stringify` first.
59
+ - `seed` is a whole number from 0 to 2^64 - 1. The same seed and day give the same text. Write a
60
+ seed above 2^53 - 1 as a bigint, such as `9007199254740993n`.
61
+ - `today` is a string like `"2026-01-15"`, or a `Date`, whose UTC day is read. Ages and
62
+ dates count from this day.
63
+ - `repeat` is how many times to render the template. It defaults to 1.
64
+ - `format` is `"text"` unless you ask for records. A record is one render of a JSON
65
+ template, with a column for each of its fields. Records come as `"csv"`, `"json"`,
66
+ `"ndjson"`, `"pgcopy"`, `"sql"` or `"tsv"`.
67
+
68
+ You must pass `seed` and `today`. A render never reads the clock or the system's randomness.
69
+
70
+ ```js
71
+ import { load } from "@larvit/fejkdata";
72
+
73
+ const fejkdata = await load();
74
+ const person = { format: "{/sv_SE.person as p}", first: "{p.first}", last: "{p.last}" };
75
+ const rows = fejkdata.render(JSON.stringify(person), { seed: 1, today: "2026-01-15", repeat: 1000, format: "csv" });
76
+ console.log(rows.split("\n").slice(0, 3).join(" | "));
77
+ ```
78
+
79
+ ```text
80
+ first,last | Vinston,Larsson | Felix,Lind
81
+ ```
82
+
83
+ ## One value
84
+
85
+ `fake(path, { seed, today })` draws one value of a path. It refuses a template, so
86
+ `sv_SE.person as p` and `sv_SE.first-name where length 3` are errors.
87
+
88
+ Some paths are not where you might guess. A postcode and a city are parts of an address:
89
+
90
+ ```js
91
+ import { load } from "@larvit/fejkdata";
92
+
93
+ const fejkdata = await load();
94
+ const day = { seed: 1, today: "2026-01-15" };
95
+ for (const path of ["sv_SE.address.postal-code", "sv_SE.address.locality", "en_US.address.postal-code", "en_US.address.region", "sv_SE.person.first"]) {
96
+ console.log(path, fejkdata.fake(path, day));
97
+ }
98
+ console.log(fejkdata.paths().includes("sv_SE.postcode"));
99
+ ```
100
+
101
+ ```text
102
+ sv_SE.address.postal-code 854 01
103
+ sv_SE.address.locality Sundsvall
104
+ en_US.address.postal-code 29414
105
+ en_US.address.region SC
106
+ sv_SE.person.first Vinston
107
+ false
108
+ ```
109
+
110
+ Each call draws afresh, so two calls give parts of two addresses. For a postcode and a city
111
+ that match, draw the whole address with `records("{/sv_SE.address}", …)`, as
112
+ [Rows as objects](#rows-as-objects) shows.
113
+
114
+ ## Every path
115
+
116
+ `paths()` returns every path the loaded data holds, as `fejkdata --list` prints them.
117
+
118
+ ```js
119
+ import { load } from "@larvit/fejkdata";
120
+
121
+ const fejkdata = await load();
122
+ console.log(fejkdata.paths().filter((path) => path.startsWith("sv_SE.address.")).join(" "));
123
+ ```
124
+
125
+ ```text
126
+ sv_SE.address.locality sv_SE.address.municipality sv_SE.address.postal-code sv_SE.address.region sv_SE.address.street sv_SE.address.street-number
127
+ ```
128
+
129
+ ## Template or path
130
+
131
+ `isTemplate(text)` tells whether a string is a template or a path. A string holding a brace
132
+ is a template, and so is a JSON string or array. Use it to choose between `render` and
133
+ `fake` for a string a user gave. It needs no `load`.
134
+
135
+ ```js
136
+ import { isTemplate } from "@larvit/fejkdata";
137
+
138
+ for (const text of ["sv_SE.person", "{/sv_SE.person}", "Hej {/sv_SE.first-name}", '["a", "b"]']) {
139
+ console.log(text, isTemplate(text));
140
+ }
141
+ ```
142
+
143
+ ```text
144
+ sv_SE.person false
145
+ {/sv_SE.person} true
146
+ Hej {/sv_SE.first-name} true
147
+ ["a", "b"] true
148
+ ```
149
+
150
+ ## Rows as objects
151
+
152
+ `records(template, { seed, today, repeat })` draws rows of a record template. The template
153
+ is JSON text or an object. A lone reference such as `"{/sv_SE.address}"` is allowed too,
154
+ and draws that path's record. Each row is an object with a key per column, in the template's
155
+ order. JavaScript puts a key that is a whole number, such as `"2"`, before the others.
156
+
157
+ A column's `datatype` sets its type in a row:
158
+
159
+ - An `integer` column is a `bigint`, so it stays exact above 2^53.
160
+ - A `number` column is a number, and a `boolean` column a boolean.
161
+ - A null is `null`.
162
+ - Any other column is a string.
163
+
164
+ A field that reads one reference, such as `"{/src.age}"`, takes the type of what it reads.
165
+ Give it a `datatype` to fix its type.
166
+
167
+ ```js
168
+ import { load } from "@larvit/fejkdata";
169
+
170
+ const fejkdata = await load();
171
+ const template = {
172
+ format: "{/sv_SE.person as p}",
173
+ id: { format: "{seq()}", datatype: "integer" },
174
+ name: "{p.first} {p.last}",
175
+ member: { format: "{m}", m: ["true", "false"], datatype: "boolean" },
176
+ };
177
+ for (const row of fejkdata.records(template, { seed: 1, today: "2026-01-15", repeat: 2 })) {
178
+ console.log(typeof row.id, row.id, row.name, typeof row.member, row.member);
179
+ }
180
+ ```
181
+
182
+ ```text
183
+ bigint 1n Kenneth Lind boolean true
184
+ bigint 2n Ann-Charlott Wiklander boolean true
185
+ ```
186
+
187
+ In TypeScript, a row's type follows the template's fields where the template is written
188
+ `as const`. A template held in a plain variable types every column `string | number | bigint |
189
+ boolean | null`.
190
+
191
+ A lone reference gives a row with a key per field of the record it reads:
192
+
193
+ ```js
194
+ import { load } from "@larvit/fejkdata";
195
+
196
+ const fejkdata = await load();
197
+ const [address] = fejkdata.records("{/sv_SE.address}", { seed: 1, today: "2026-01-15" });
198
+ console.log(Object.keys(address).join(" "));
199
+ console.log(address["postal-code"], address.locality);
200
+ ```
201
+
202
+ ```text
203
+ street street-number postal-code locality municipality region
204
+ 475 32 Öckerö
205
+ ```
206
+
207
+ `JSON.stringify` and the snapshots of Node's test runner throw on a `bigint`. Turn it into a
208
+ string first, such as with `String(row.id)`.
209
+
210
+ ## Your own data
211
+
212
+ `load({ data, files })` takes two options. Each call gives a new object.
213
+
214
+ - `data` names the shipped modules to load, such as `["sv_SE"]`. Each module loads the
215
+ modules it reads too. `sv_SE` reads `geo.SE` for its addresses. Without `data`, every shipped
216
+ module loads. A name that is not a shipped module throws, and the error lists the shipped
217
+ modules.
218
+ - `files` maps a file name, such as `mydata/team.json`, to its text or bytes. A template
219
+ reads that file as `{/mydata.team}`. The files lie over the shipped data, so a file at
220
+ `sv_SE/color.json` replaces the shipped `sv_SE.color`. A file that doesn't load makes
221
+ `load` throw, with the kind `"load"`.
222
+
223
+ ```js
224
+ import { load } from "@larvit/fejkdata";
225
+
226
+ const fejkdata = await load({ data: ["sv_SE"], files: { "mydata/team.json": '["Red", "Blue"]' } });
227
+ console.log(fejkdata.render("{/sv_SE.first-name} plays for {/mydata.team}", { seed: 1, today: "2026-01-15" }));
228
+ console.log(fejkdata.paths().includes("en_US.person"));
229
+ ```
230
+
231
+ ```text
232
+ Vinston plays for Red
233
+ false
234
+ ```
235
+
236
+ ## Shipped paths
237
+
238
+ The TypeScript type `ShippedPath` is every path of the shipped data, such as
239
+ `"sv_SE.first-name"`. An editor completes a string of that type. A template reads the
240
+ path as `{/sv_SE.first-name}`.
241
+
242
+ ## Errors
243
+
244
+ `load` and each function it gives throw a `FejkdataError` when fejkdata refuses the
245
+ template, an argument or the data. Its message says what is wrong, in the CLI's words. Its
246
+ `kind` says where the error arose:
247
+
248
+ - `"misuse"`: a mistake in the template, an argument or `load`'s options.
249
+ - `"load"`: the data doesn't load, or the template reads a module `data` left out.
250
+ - `"limit"`: the output passes 512 MB.
251
+ - `"other"`: anything else.
252
+
253
+ A test reads `kind`, not `exitCode`. `exitCode` is 2 for misuse, and for a
254
+ template that reads a module the `data` option left out. It is 1 for anything
255
+ else. `render` gives 1 for those two as well where only a format finds the
256
+ mistake, as the CLI does.
257
+
258
+ A test doesn't check `instanceof FejkdataError` either. A test runner or bundler may load two
259
+ copies of the package, and then `instanceof` fails.
260
+
261
+ A template that is neither a string nor, for `records`, an object throws a `TypeError`. So
262
+ does a call without the second argument.
263
+
264
+ ```js
265
+ import { load } from "@larvit/fejkdata";
266
+
267
+ const fejkdata = await load();
268
+ try {
269
+ fejkdata.render("{/sv_SE.persn}", { seed: 1, today: "2026-01-15" });
270
+ } catch (error) {
271
+ if (error.name !== "FejkdataError") {
272
+ throw error;
273
+ }
274
+ console.log(error.kind, error.exitCode, error.message);
275
+ }
276
+ ```
277
+
278
+ ```text
279
+ misuse 2 fejkdata: template: reference {/sv_SE.persn}: no entry "persn"
280
+ ```
281
+
282
+ ## Globals
283
+
284
+ The package loads through `wasm_exec.js`, the loader Go ships for its WebAssembly. It sets
285
+ `globalThis.Go`. Where the runtime has no `fs`, `process` or `path` global, it sets a stub
286
+ for each.
@@ -0,0 +1,11 @@
1
+ WordNet Release 3.0
2
+
3
+ This software and database is being provided to you, the LICENSEE, by Princeton University under the following license. By obtaining, using and/or copying this software and database, you agree that you have read, understood, and will comply with these terms and conditions.:
4
+
5
+ Permission to use, copy, modify and distribute this software and database and its documentation for any purpose and without fee or royalty is hereby granted, provided that you agree to comply with the following copyright notice and statements, including the disclaimer, and that the same appear on ALL copies of the software, database and documentation, including modifications that you make for internal use or for distribution.
6
+
7
+ WordNet 3.0 Copyright 2006 by Princeton University. All rights reserved.
8
+
9
+ THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
10
+
11
+ The name of Princeton University or Princeton may not be used in advertising or publicity pertaining to distribution of the software and/or database. Title to copyright in this software, database and any associated documentation shall at all times remain with Princeton University and LICENSEE agrees to preserve same.
package/fejkdata.wasm ADDED
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/fejkdata.wasm
3
+ size: 69201702 bytes
4
+ sha256: 378b935cf363d2c360061c82fa6768e6466f89a5ed0a48d84f2f04f6c8aadc61
package/index.d.ts ADDED
@@ -0,0 +1,102 @@
1
+ import type { ShippedPath } from "./shipped-paths.js";
2
+ export type { ShippedPath };
3
+
4
+ export interface RenderOptions {
5
+ /** A whole number from 0 to 2^64 - 1. A number above 2^53 - 1 is written as a bigint. The same seed and day give the same text. */
6
+ seed: number | bigint;
7
+ /** The day ages and dates count from: a string such as "2026-01-15", or a Date, whose UTC day is read. */
8
+ today: string | Date;
9
+ /** How many times to render the template. It defaults to 1. */
10
+ repeat?: number;
11
+ /** "text" unless you ask for records: one per render of a JSON template, with a column for each field. */
12
+ format?: "text" | "csv" | "json" | "ndjson" | "pgcopy" | "sql" | "tsv";
13
+ }
14
+
15
+ /** The options of fake: a seed and a day, as render takes them. */
16
+ export interface FakeOptions {
17
+ /** A whole number from 0 to 2^64 - 1. A number above 2^53 - 1 is written as a bigint. */
18
+ seed: number | bigint;
19
+ /** The day ages and dates count from: a string such as "2026-01-15", or a Date, whose UTC day is read. */
20
+ today: string | Date;
21
+ }
22
+
23
+ /** The options of records: a seed, a day and how many rows to draw. */
24
+ export interface RecordsOptions {
25
+ /** A whole number from 0 to 2^64 - 1. A number above 2^53 - 1 is written as a bigint. */
26
+ seed: number | bigint;
27
+ /** The day ages and dates count from: a string such as "2026-01-15", or a Date, whose UTC day is read. */
28
+ today: string | Date;
29
+ /** How many rows to draw. It defaults to 1. */
30
+ repeat?: number;
31
+ }
32
+
33
+ /** A column's value in a row: a bigint for an integer column, a number, a boolean, null, or else a string. */
34
+ export type ColumnValue = string | number | bigint | boolean | null;
35
+
36
+ /** What load reads. */
37
+ export interface LoadOptions {
38
+ /** The shipped modules to load, such as ["sv_SE", "misc"], each with the modules it reads. Every module loads without it. */
39
+ data?: readonly string[];
40
+ /** Your own data files, by path, such as "mydata/users.json", laid over the shipped data. */
41
+ files?: Readonly<Record<string, string | Uint8Array>>;
42
+ }
43
+
44
+ type OptionKey = "datatype" | "format" | "hidden" | "repeat" | "separator" | "weight";
45
+
46
+ type LoneReference<S extends string> = S extends `{${infer Inner}}`
47
+ ? Inner extends `${string}${"{" | "}" | " " | "|" | "(" | ","}${string}` ? false : true
48
+ : false;
49
+
50
+ type TextColumn<S> = S extends string ? string extends S ? ColumnValue : LoneReference<S> extends true ? ColumnValue : string : ColumnValue;
51
+
52
+ type ByDatatype = { integer: bigint; number: number; boolean: boolean; string: string };
53
+
54
+ type ColumnOf<F> = F extends null ? null
55
+ : F extends readonly (infer Item)[] ? ColumnOf<Item>
56
+ : F extends { datatype: infer D extends keyof ByDatatype } ? ByDatatype[D]
57
+ : F extends { format: infer S } ? TextColumn<S>
58
+ : F extends string ? TextColumn<F>
59
+ : F extends number | boolean ? string
60
+ : ColumnValue;
61
+
62
+ /** A row of records drawn from the object template T: a key per field that writes a column. */
63
+ export type RecordRow<T> = { -readonly [K in Exclude<keyof T, OptionKey> & string]: ColumnOf<T[K]> };
64
+
65
+ export interface Fejkdata {
66
+ /**
67
+ * Renders template as `fejkdata --seed … --today … --repeat … --format …` does, and returns what it prints.
68
+ * Throws a FejkdataError when fejkdata refuses the template or an argument.
69
+ */
70
+ render(template: string, options: RenderOptions): string;
71
+ /** Draws one value of a path, such as "sv_SE.address.postal-code". A template is refused. */
72
+ fake(path: ShippedPath | (string & {}), options: FakeOptions): string;
73
+ /**
74
+ * Draws rows from a record template, given as JSON text or an object. A row is an object with a key per column, in the template's order, save that JavaScript puts a key that is a whole number, such as "2", first.
75
+ * An integer column is a bigint, a number column a number, a boolean column a boolean, and any other a string. A null is null.
76
+ */
77
+ records(template: string, options: RecordsOptions): Record<string, ColumnValue>[];
78
+ records<const T extends { readonly [key: string]: unknown }>(template: T, options: RecordsOptions): RecordRow<T>[];
79
+ /** Every path the loaded data holds, as `fejkdata --list` prints them. */
80
+ paths(): string[];
81
+ }
82
+
83
+ /** Where a FejkdataError arose: a mistake in a template or an argument, the data failing to load, a limit passed, or anything else. */
84
+ export type FejkdataErrorKind = "misuse" | "load" | "limit" | "other";
85
+
86
+ /** Thrown when fejkdata refuses a template, an argument or the data. The message says what is wrong, in the CLI's words. */
87
+ export class FejkdataError extends Error {
88
+ /**
89
+ * Read kind to tell a mistake, not exitCode. exitCode is 2 for misuse, and for a template that reads a module the data option left out.
90
+ * It is 1 for anything else. render gives 1 for those two as well where only a format finds the mistake, as the CLI does.
91
+ */
92
+ readonly exitCode: number;
93
+ /** Where the error arose. */
94
+ readonly kind: FejkdataErrorKind;
95
+ constructor(message: string, exitCode: number, kind: FejkdataErrorKind);
96
+ }
97
+
98
+ /** Loads the WebAssembly, compiled once however often it is called. With no options it gives the same object each time. */
99
+ export function load(options?: LoadOptions): Promise<Fejkdata>;
100
+
101
+ /** Whether text is a template rather than a path, by the rule fejkdata's CLI reads an argument by. */
102
+ export function isTemplate(text: string): boolean;
package/index.js ADDED
@@ -0,0 +1,155 @@
1
+ import "./wasm_exec.js";
2
+
3
+ export class FejkdataError extends Error {
4
+ constructor(message, exitCode, kind) {
5
+ super(message);
6
+ this.name = "FejkdataError";
7
+ this.exitCode = exitCode;
8
+ this.kind = kind;
9
+ }
10
+ }
11
+
12
+ let starting;
13
+ let shipped;
14
+
15
+ export function load(options) {
16
+ if (options === undefined) {
17
+ shipped ??= open({}).catch((error) => {
18
+ shipped = undefined;
19
+ throw error;
20
+ });
21
+ return shipped;
22
+ }
23
+ return open(options);
24
+ }
25
+
26
+ export function isTemplate(text) {
27
+ if (typeof text !== "string") {
28
+ throw new TypeError("fejkdata: isTemplate reads a string");
29
+ }
30
+ if (text.includes("{")) {
31
+ return true;
32
+ }
33
+ if (!/^\s*["[]/.test(text)) {
34
+ return false;
35
+ }
36
+ try {
37
+ JSON.parse(text);
38
+ return true;
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ async function open(options) {
45
+ if (typeof options !== "object" || options === null) {
46
+ throw new TypeError('fejkdata: load takes an object, such as { data: ["sv_SE"] }');
47
+ }
48
+ const { data, files = {} } = options;
49
+ if (data !== undefined && !(Array.isArray(data) && data.every((name) => typeof name === "string"))) {
50
+ throw new TypeError('fejkdata: data is an array of module names, such as ["sv_SE"]');
51
+ }
52
+ if (typeof files !== "object" || files === null) {
53
+ throw new TypeError('fejkdata: files is an object of file names and their text, such as { "mydata/team.json": "[]" }');
54
+ }
55
+ const names = data === undefined ? null : [...data];
56
+ const pairs = Object.entries(files).map(([path, body]) => [path, bytes(path, body)]);
57
+ const bridge = await started();
58
+ const opened = (call) => (...args) => bridge[call](names, pairs, ...args);
59
+ answer(opened("check")());
60
+ return {
61
+ render: (template, options) => render(opened("render"), template, options),
62
+ fake: (path, options) => fake(opened("fake"), path, options),
63
+ records: (template, options) => records(opened("records"), template, options),
64
+ paths: () => answer(opened("paths")()).paths,
65
+ };
66
+ }
67
+
68
+ function bytes(path, body) {
69
+ if (typeof body === "string") {
70
+ return new TextEncoder().encode(body);
71
+ }
72
+ if (body instanceof Uint8Array) {
73
+ return new Uint8Array(body);
74
+ }
75
+ throw new TypeError(`fejkdata: files["${path}"] is a string or a Uint8Array`);
76
+ }
77
+
78
+ function started() {
79
+ starting ??= start().catch((error) => {
80
+ starting = undefined;
81
+ throw error;
82
+ });
83
+ return starting;
84
+ }
85
+
86
+ async function start() {
87
+ const go = new globalThis.Go();
88
+ const instance = await WebAssembly.instantiate(await compiled(new URL("./fejkdata.wasm", import.meta.url)), go.importObject);
89
+ return new Promise((resolve, reject) => {
90
+ // The Go program can reach only globals, so it hands its functions over through this one.
91
+ globalThis.__fejkdataRun = resolve;
92
+ go.run(instance).then(() => reject(new Error("fejkdata: the WebAssembly program stopped while loading")), reject);
93
+ }).finally(() => delete globalThis.__fejkdataRun);
94
+ }
95
+
96
+ // Node's fetch refuses a file: URL, so a runtime with Node's fs reads a file on disk. A browser fetches.
97
+ async function compiled(url) {
98
+ const fs = url.protocol === "file:" && globalThis.process?.getBuiltinModule?.("node:fs/promises");
99
+ return fs ? WebAssembly.compile(await fs.readFile(url)) : WebAssembly.compileStreaming(fetch(url));
100
+ }
101
+
102
+ function drawArguments(seed, today) {
103
+ if (typeof seed === "number" && !Number.isSafeInteger(seed)) {
104
+ throw new FejkdataError(`fejkdata: seed ${seed} is not a whole number from 0 to ${Number.MAX_SAFE_INTEGER}; write a seed above ${Number.MAX_SAFE_INTEGER} as a bigint, such as 9007199254740993n`, 2, "misuse");
105
+ }
106
+ const day = today instanceof Date && !Number.isNaN(today.getTime()) ? today.toISOString().slice(0, 10) : String(today);
107
+ return [String(seed), day];
108
+ }
109
+
110
+ function drawOptions(options) {
111
+ if (typeof options !== "object" || options === null) {
112
+ throw new TypeError('fejkdata: the options are missing; pass { seed, today } last, such as { seed: 1, today: "2026-01-01" }');
113
+ }
114
+ return options;
115
+ }
116
+
117
+ function render(run, template, options) {
118
+ const { seed, today, repeat = 1, format = "text" } = drawOptions(options);
119
+ if (typeof template !== "string") {
120
+ throw new TypeError("fejkdata: a template is a string; pass an object through JSON.stringify first");
121
+ }
122
+ return answer(run(...drawArguments(seed, today), String(repeat), String(format), template)).stdout;
123
+ }
124
+
125
+ function fake(run, path, options) {
126
+ const { seed, today } = drawOptions(options);
127
+ if (typeof path !== "string") {
128
+ throw new TypeError("fejkdata: a path is a string, such as \"sv_SE.address.postal-code\"");
129
+ }
130
+ return answer(run(...drawArguments(seed, today), path)).value;
131
+ }
132
+
133
+ const READ = { integer: BigInt, number: Number, boolean: (text) => text === "true", string: String };
134
+
135
+ function records(run, template, options) {
136
+ const { seed, today, repeat = 1 } = drawOptions(options);
137
+ const text = typeof template === "object" && template !== null ? JSON.stringify(template) : template;
138
+ if (typeof text !== "string") {
139
+ throw new TypeError("fejkdata: a record template is JSON text or an object");
140
+ }
141
+ const { names, types, values } = answer(run(...drawArguments(seed, today), String(repeat), text));
142
+ const reads = types.map((type) => READ[type]);
143
+ const rows = [];
144
+ for (let i = 0; i < values.length; i += names.length) {
145
+ rows.push(Object.fromEntries(names.map((name, j) => [name, values[i + j] === null ? null : reads[j](values[i + j])])));
146
+ }
147
+ return rows;
148
+ }
149
+
150
+ function answer(done) {
151
+ if (done.error) {
152
+ throw new FejkdataError(done.error, done.exitCode, done.kind);
153
+ }
154
+ return done;
155
+ }
package/package.json CHANGED
@@ -1 +1,50 @@
1
- {"name":"@larvit/fejkdata","version":"0.0.0","description":"Placeholder. The first real version is 0.9.0.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/larvit/fejkdata.git"}}
1
+ {
2
+ "name": "@larvit/fejkdata",
3
+ "version": "0.9.0",
4
+ "description": "Fake data for tests. Related values match, like a postcode and its city. National ids pass validation where possible.",
5
+ "keywords": [
6
+ "fake",
7
+ "faker",
8
+ "test data",
9
+ "fixtures",
10
+ "seed",
11
+ "csv",
12
+ "sql"
13
+ ],
14
+ "homepage": "https://fejkdata.dev",
15
+ "bugs": "https://github.com/larvit/fejkdata/issues",
16
+ "author": "Larv IT AB",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/larvit/fejkdata.git",
20
+ "directory": "npm-package"
21
+ },
22
+ "license": "MIT AND LicenseRef-fejkdata-data-licenses",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./index.d.ts",
27
+ "default": "./index.js"
28
+ }
29
+ },
30
+ "types": "./index.d.ts",
31
+ "files": [
32
+ "DATA-LICENSES.md",
33
+ "LICENSE",
34
+ "WORDNET-LICENSE.txt",
35
+ "fejkdata.wasm",
36
+ "index.d.ts",
37
+ "index.js",
38
+ "shipped-paths.d.ts",
39
+ "wasm_exec.js"
40
+ ],
41
+ "sideEffects": [
42
+ "./wasm_exec.js"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "engines": {
48
+ "node": ">=22.3.0"
49
+ }
50
+ }