@operad-io/engine 0.0.0-stage → 0.0.1

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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/config.schema.json +188 -0
  3. package/keys.schema.json +12 -0
  4. package/package.json +22 -4
  5. package/src/config/config.ts +627 -0
  6. package/src/config/index.ts +1 -0
  7. package/src/flow/define-flow.ts +57 -0
  8. package/src/flow/index.ts +5 -0
  9. package/src/flow/load.ts +41 -0
  10. package/src/flow/types.ts +107 -0
  11. package/src/flow/validate.ts +296 -0
  12. package/src/http/address.ts +142 -0
  13. package/src/http/index.ts +25 -0
  14. package/src/http/link.ts +20 -0
  15. package/src/http/server.ts +920 -0
  16. package/src/http/token.ts +85 -0
  17. package/src/index.ts +16 -0
  18. package/src/kernel/decide.ts +689 -0
  19. package/src/kernel/index.ts +3 -0
  20. package/src/kernel/state.ts +275 -0
  21. package/src/kernel/types.ts +366 -0
  22. package/src/log/errors.ts +77 -0
  23. package/src/log/facts.ts +50 -0
  24. package/src/log/index.ts +6 -0
  25. package/src/log/json-value.ts +67 -0
  26. package/src/log/open-log.ts +17 -0
  27. package/src/log/schema.ts +5 -0
  28. package/src/log/secret.ts +30 -0
  29. package/src/log/sqlite.ts +1011 -0
  30. package/src/log/types.ts +230 -0
  31. package/src/loop/code-watch.ts +486 -0
  32. package/src/loop/index.ts +3 -0
  33. package/src/loop/older-code.ts +58 -0
  34. package/src/loop/serve.ts +483 -0
  35. package/src/markdown.ts +451 -0
  36. package/src/notify/index.ts +10 -0
  37. package/src/notify/notify.ts +256 -0
  38. package/src/platform/file-lock.ts +385 -0
  39. package/src/platform/index.ts +13 -0
  40. package/src/platform/load.ts +18 -0
  41. package/src/platform/process-group.ts +635 -0
  42. package/src/platform/process-watch.ts +152 -0
  43. package/src/platform/sqlite-open.ts +104 -0
  44. package/src/platform/step-reap.ts +668 -0
  45. package/src/platform/watch.ts +158 -0
  46. package/src/platform/worker-reports.ts +34 -0
  47. package/src/plugin/action-schema.ts +550 -0
  48. package/src/plugin/declared-flows.ts +74 -0
  49. package/src/plugin/define-plugin.ts +12 -0
  50. package/src/plugin/errors.ts +73 -0
  51. package/src/plugin/filters.ts +46 -0
  52. package/src/plugin/harness.ts +50 -0
  53. package/src/plugin/home.ts +13 -0
  54. package/src/plugin/index.ts +65 -0
  55. package/src/plugin/install.ts +268 -0
  56. package/src/plugin/keys.ts +63 -0
  57. package/src/plugin/load.ts +256 -0
  58. package/src/plugin/logger.ts +30 -0
  59. package/src/plugin/object-facts.ts +132 -0
  60. package/src/plugin/open-store.ts +32 -0
  61. package/src/plugin/paging.ts +133 -0
  62. package/src/plugin/registry.ts +1783 -0
  63. package/src/plugin/secrets.ts +141 -0
  64. package/src/plugin/semver.ts +110 -0
  65. package/src/plugin/settings.ts +64 -0
  66. package/src/plugin/sqlite-store.ts +756 -0
  67. package/src/plugin/store.ts +318 -0
  68. package/src/plugin/types.ts +1236 -0
  69. package/src/plugin/usage.ts +157 -0
  70. package/src/plugin/validate.ts +1028 -0
  71. package/src/runner/answer.ts +156 -0
  72. package/src/runner/ask.ts +483 -0
  73. package/src/runner/cancel.ts +51 -0
  74. package/src/runner/errors.ts +20 -0
  75. package/src/runner/grants.ts +92 -0
  76. package/src/runner/index.ts +33 -0
  77. package/src/runner/limits.ts +403 -0
  78. package/src/runner/lock.ts +140 -0
  79. package/src/runner/runner.ts +1175 -0
  80. package/src/runner/service.ts +184 -0
  81. package/src/runner/step-worker.ts +303 -0
  82. package/src/testing/clock.ts +67 -0
  83. package/src/testing/index.ts +90 -0
  84. package/src/testing/types.ts +116 -0
  85. package/src/testing/world.ts +369 -0
  86. package/src/trigger/cron.ts +193 -0
  87. package/src/trigger/index.ts +32 -0
  88. package/src/trigger/kernel.ts +1212 -0
  89. package/src/trigger/rules.ts +300 -0
  90. package/src/trigger/store.ts +233 -0
  91. package/src/trigger/types.ts +156 -0
  92. package/src/util.ts +50 -0
  93. package/src/views/history.ts +634 -0
  94. package/src/views/index.ts +7 -0
  95. package/src/views/pending.ts +209 -0
  96. package/src/views/presentation.ts +2551 -0
  97. package/src/views/running.ts +255 -0
  98. package/src/views/settings.ts +452 -0
  99. package/src/views/types.ts +72 -0
  100. package/src/views/uploads.ts +228 -0
  101. package/triggers.schema.json +48 -0
  102. package/README.md +0 -3
@@ -0,0 +1,256 @@
1
+ import { access } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { readConfig, type PluginConfigEntry } from "../config/config.ts";
6
+ import { messageOf, PluginError } from "./errors.ts";
7
+ import { defaultOperadHome } from "./home.ts";
8
+ import { installedPackageFile, runningFromWorkspace } from "./install.ts";
9
+ import { keysPathFor, readKeysFile } from "./keys.ts";
10
+ import { PluginRegistry } from "./registry.ts";
11
+ import type { PluginRegistryOptions } from "./registry.ts";
12
+
13
+ /** Options for loading the registry from the operad home. */
14
+ export interface LoadPluginRegistryOptions extends PluginRegistryOptions {
15
+ /** Defaults to `<home>/config.json`. */
16
+ readonly configPath?: string | undefined;
17
+ /** Defaults to `<home>/keys.json`. */
18
+ readonly keysPath?: string | undefined;
19
+ /**
20
+ * Plugins whose package the distribution installs into the home when a person
21
+ * enables them. A missing one is reported with the command that installs it.
22
+ * Empty by default: the engine names no plugin.
23
+ */
24
+ readonly installOnEnable?: readonly string[] | undefined;
25
+ }
26
+
27
+ let loadCount = 0;
28
+
29
+ /**
30
+ * A plugin listed as a path is resolved against the operad home; anything else
31
+ * is a module name. `file:` URLs pass through unchanged.
32
+ */
33
+ function resolvePluginSpecifier(specifier: string, baseDir: string): string {
34
+ if (specifier.startsWith("file:")) return specifier;
35
+ if (
36
+ specifier.startsWith(".") ||
37
+ specifier.startsWith("/") ||
38
+ specifier.startsWith("~")
39
+ ) {
40
+ const path = specifier.startsWith("~")
41
+ ? join(homedir(), specifier.slice(1))
42
+ : specifier;
43
+ return pathToFileURL(resolve(baseDir, path)).href;
44
+ }
45
+ return specifier;
46
+ }
47
+
48
+ /** Imports a module file with a fresh instance, as a reload expects. */
49
+ async function importPluginFile(file: string): Promise<Record<string, unknown>> {
50
+ loadCount += 1;
51
+ const url = new URL(pathToFileURL(file).href);
52
+ url.searchParams.set("operad-plugin-load", String(loadCount));
53
+ return (await import(url.href)) as Record<string, unknown>;
54
+ }
55
+
56
+ /**
57
+ * Imports a plugin module and returns its default export. The module name is
58
+ * named in every import error. A path gets a fresh module instance so a later
59
+ * reload does not reuse the old value.
60
+ *
61
+ * `installed` is the package's file in the home's Bun project (decision 11).
62
+ * The workspace link is tried first, so a checkout keeps loading its own code;
63
+ * when there is no such link, the home package is imported by path.
64
+ */
65
+ export async function loadPlugin(
66
+ specifier: string,
67
+ baseDir: string,
68
+ installed?: string | undefined,
69
+ ): Promise<unknown> {
70
+ const resolved = resolvePluginSpecifier(specifier, baseDir);
71
+ const isFile = resolved.startsWith("file:");
72
+ let url = resolved;
73
+ if (isFile) {
74
+ loadCount += 1;
75
+ const parsed = new URL(resolved);
76
+ parsed.searchParams.set("operad-plugin-load", String(loadCount));
77
+ url = parsed.href;
78
+ }
79
+
80
+ let module: Record<string, unknown>;
81
+ try {
82
+ module = (await import(url)) as Record<string, unknown>;
83
+ } catch (error) {
84
+ if (installed === undefined) {
85
+ throw new PluginError(
86
+ `plugin "${specifier}": import failed: ${messageOf(error)}`,
87
+ { cause: error },
88
+ );
89
+ }
90
+ try {
91
+ module = await importPluginFile(installed);
92
+ } catch (installedError) {
93
+ throw new PluginError(
94
+ `plugin "${specifier}": import failed: ${messageOf(error)}; the package in the home also failed: ${messageOf(installedError)}`,
95
+ { cause: installedError },
96
+ );
97
+ }
98
+ }
99
+
100
+ if (module.default === undefined) {
101
+ throw new PluginError(`plugin "${specifier}": no default export`);
102
+ }
103
+ return module.default;
104
+ }
105
+
106
+ /** One configured plugin and the definition it resolved to, if any. */
107
+ export interface ConfiguredPlugin {
108
+ readonly entry: PluginConfigEntry;
109
+ readonly definition?: unknown;
110
+ readonly error?: string | undefined;
111
+ }
112
+
113
+ /** What reading the plugins list produced, before the registry validates them. */
114
+ export interface ConfiguredPlugins {
115
+ readonly entries: readonly PluginConfigEntry[];
116
+ /** The entries that loaded, in config order. */
117
+ readonly loaded: readonly DefinitelyLoadedPlugin[];
118
+ /** The names that are switched off in the config. */
119
+ readonly disabled: readonly string[];
120
+ /** Everything that did not load, one line each. */
121
+ readonly errors: readonly string[];
122
+ }
123
+
124
+ export interface DefinitelyLoadedPlugin {
125
+ readonly entry: PluginConfigEntry;
126
+ readonly definition: unknown;
127
+ }
128
+
129
+ function definitionName(value: unknown): string | undefined {
130
+ if (
131
+ typeof value === "object" &&
132
+ value !== null &&
133
+ "name" in value &&
134
+ typeof (value as { name?: unknown }).name === "string"
135
+ ) {
136
+ return (value as { name: string }).name;
137
+ }
138
+ return undefined;
139
+ }
140
+
141
+ function isMissingFileError(error: unknown): boolean {
142
+ return (
143
+ typeof error === "object" &&
144
+ error !== null &&
145
+ "code" in error &&
146
+ (error as { code?: unknown }).code === "ENOENT"
147
+ );
148
+ }
149
+
150
+ /**
151
+ * False only when the config file does not exist. Any other access error means
152
+ * the file may exist but cannot be read, so `readConfig` gets to report it
153
+ * instead of the load quietly returning an empty configuration.
154
+ */
155
+ async function configFileExists(path: string): Promise<boolean> {
156
+ try {
157
+ await access(path);
158
+ return true;
159
+ } catch (error) {
160
+ return !isMissingFileError(error);
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Imports every enabled plugin in the config. A module that fails to import is
166
+ * reported and skipped, so one broken plugin does not keep the rest from
167
+ * loading. Disabled entries are returned by name and never imported.
168
+ */
169
+ export async function loadConfiguredPlugins(
170
+ options: LoadPluginRegistryOptions = {},
171
+ ): Promise<ConfiguredPlugins> {
172
+ const home = options.home ?? defaultOperadHome();
173
+ const configFile = options.configPath ?? join(home, "config.json");
174
+ if (!(await configFileExists(configFile))) {
175
+ return { entries: [], loaded: [], disabled: [], errors: [] };
176
+ }
177
+ const config = await readConfig(home, configFile);
178
+ const loaded: DefinitelyLoadedPlugin[] = [];
179
+ const disabled: string[] = [];
180
+ const errors: string[] = [];
181
+
182
+ for (const entry of config.plugins) {
183
+ if (!entry.enabled) {
184
+ if (entry.name !== undefined) disabled.push(entry.name);
185
+ continue;
186
+ }
187
+ const installed = installedPackageFile(home, entry.module);
188
+ // Outside a workspace checkout the home project is the copy to run, even
189
+ // when another install of the same package happens to resolve.
190
+ const source = installed !== undefined && !runningFromWorkspace() ? installed : entry.module;
191
+ let definition: unknown;
192
+ try {
193
+ definition = await loadPlugin(source, home, installed);
194
+ } catch (error) {
195
+ if (
196
+ entry.name !== undefined &&
197
+ (options.installOnEnable ?? []).includes(entry.name) &&
198
+ installed === undefined &&
199
+ !runningFromWorkspace()
200
+ ) {
201
+ errors.push(
202
+ `plugin "${entry.name}": not installed; run \`operad plugin enable ${entry.name}\` to install it`,
203
+ );
204
+ } else {
205
+ errors.push(messageOf(error));
206
+ }
207
+ continue;
208
+ }
209
+ if (entry.name !== undefined) {
210
+ const declared = definitionName(definition);
211
+ if (declared !== undefined && declared !== entry.name && entry.module !== entry.name) {
212
+ errors.push(
213
+ `plugin "${entry.name}": unknown plugin; the module "${entry.module}" provides "${declared}"`,
214
+ );
215
+ continue;
216
+ }
217
+ }
218
+ loaded.push({ entry, definition });
219
+ }
220
+
221
+ return { entries: config.plugins, loaded, disabled, errors };
222
+ }
223
+
224
+ /**
225
+ * Loads the plugins listed in `$OPERAD_HOME/config.json` (default
226
+ * `~/.operad/config.json`) and validates them together.
227
+ */
228
+ export async function loadPluginRegistry(
229
+ options: LoadPluginRegistryOptions = {},
230
+ ): Promise<PluginRegistry> {
231
+ const home = options.home ?? defaultOperadHome();
232
+ const onLog = options.onLog ?? ((message: string) => console.error(message));
233
+ const config = await loadConfiguredPlugins({ ...options, home, onLog });
234
+
235
+ for (const error of config.errors) onLog(error);
236
+
237
+ const definitions: unknown[] = [];
238
+ const sources: string[] = [];
239
+ const settings: Record<string, unknown> = {};
240
+ for (const { entry, definition } of config.loaded) {
241
+ definitions.push(definition);
242
+ sources.push(entry.module);
243
+ const name = definitionName(definition) ?? entry.name;
244
+ if (name !== undefined) settings[name] = entry.settings;
245
+ }
246
+
247
+ const keys = await readKeysFile(options.keysPath ?? keysPathFor(home));
248
+ return new PluginRegistry(definitions, {
249
+ ...options,
250
+ home,
251
+ keys: options.keys ?? keys,
252
+ sources,
253
+ settings: options.settings ?? settings,
254
+ disabled: options.disabled ?? config.disabled,
255
+ });
256
+ }
@@ -0,0 +1,30 @@
1
+ import { appendFile, mkdir } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import type { PluginLogger } from "./types.ts";
4
+
5
+ /** Keeps a name usable as one path segment. */
6
+ function segment(value: string): string {
7
+ const cleaned = value.replace(/[^A-Za-z0-9._-]/g, "_");
8
+ return cleaned.length === 0 || cleaned === "." || cleaned === ".."
9
+ ? "_"
10
+ : cleaned;
11
+ }
12
+
13
+ /**
14
+ * A logger for one step, action, command or tick. It appends to a file under
15
+ * `<store>/logs` and returns that path so the plugin can put it in a fact.
16
+ */
17
+ export function createPluginLogger(
18
+ storeRoot: string,
19
+ ...segments: readonly string[]
20
+ ): PluginLogger {
21
+ const path = `${join(storeRoot, "logs", ...segments.map(segment))}.log`;
22
+ return {
23
+ path,
24
+ async write(text: string): Promise<string> {
25
+ await mkdir(dirname(path), { recursive: true });
26
+ await appendFile(path, text.endsWith("\n") ? text : `${text}\n`, "utf8");
27
+ return path;
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Object facts hold changes, not full snapshots. A `put` writes only the
3
+ * top-level fields whose value changed and the names of the fields it removed;
4
+ * the object table keeps the whole current value. A fact written before this
5
+ * rule is still read: its type equals the object's type and its data is the
6
+ * whole object.
7
+ */
8
+
9
+ import { isRecord } from "../util.ts";
10
+ import type { ObjectData, ObjectRef, PluginFact } from "./types.ts";
11
+
12
+ /** The fact type a `put` writes; it cannot be mistaken for an old snapshot. */
13
+ export const OBJECT_CHANGE_FACT = "object.changed";
14
+
15
+ /** What a change fact holds. */
16
+ export type ObjectChange = ObjectData & {
17
+ readonly changed: ObjectData;
18
+ readonly removed: readonly string[];
19
+ };
20
+
21
+ /** One object fact and the object's whole value after it. */
22
+ export interface ObjectFactVersion {
23
+ readonly fact: PluginFact;
24
+ readonly data: ObjectData;
25
+ }
26
+
27
+ function sameValue(left: unknown, right: unknown): boolean {
28
+ if (Object.is(left, right)) return true;
29
+ if (Array.isArray(left) || Array.isArray(right)) {
30
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
31
+ return false;
32
+ }
33
+ return left.every((value, index) => sameValue(value, right[index]));
34
+ }
35
+ if (isRecord(left) && isRecord(right)) {
36
+ const leftKeys = Object.keys(left);
37
+ if (leftKeys.length !== Object.keys(right).length) return false;
38
+ return leftKeys.every(
39
+ (key) => Object.hasOwn(right, key) && sameValue(left[key], right[key]),
40
+ );
41
+ }
42
+ return false;
43
+ }
44
+
45
+ /**
46
+ * The change from `previous` to `data`, or undefined when nothing top-level
47
+ * changed. Values compare deeply; an array or object equal in content is not a
48
+ * change.
49
+ */
50
+ export function diffObject(
51
+ previous: ObjectData,
52
+ data: ObjectData,
53
+ ): ObjectChange | undefined {
54
+ const changed: Record<string, unknown> = {};
55
+ for (const [name, value] of Object.entries(data)) {
56
+ if (!Object.hasOwn(previous, name) || !sameValue(previous[name], value)) {
57
+ changed[name] = value;
58
+ }
59
+ }
60
+ const removed = Object.keys(previous)
61
+ .filter((name) => !Object.hasOwn(data, name))
62
+ .sort();
63
+ if (Object.keys(changed).length === 0 && removed.length === 0) return undefined;
64
+ return { changed, removed };
65
+ }
66
+
67
+ /** The whole object after applying one change. */
68
+ export function applyObjectChange(
69
+ previous: ObjectData,
70
+ change: ObjectChange,
71
+ ): ObjectData {
72
+ const value: Record<string, unknown> = { ...previous };
73
+ for (const name of change.removed) delete value[name];
74
+ for (const [name, field] of Object.entries(change.changed)) value[name] = field;
75
+ return value;
76
+ }
77
+
78
+ /** The change a change fact's data holds; undefined when it is not that shape. */
79
+ export function objectChangeOf(data: ObjectData): ObjectChange | undefined {
80
+ const changed = data.changed;
81
+ const removed = data.removed;
82
+ if (!isRecord(changed) || !Array.isArray(removed)) return undefined;
83
+ if (!removed.every((name) => typeof name === "string")) return undefined;
84
+ return { changed, removed };
85
+ }
86
+
87
+ /** A fact that belongs to an object. */
88
+ export type ObjectFact = PluginFact & { readonly object: ObjectRef };
89
+
90
+ /** Whether a fact records a version of its object, in either shape. */
91
+ export function isObjectFact(fact: PluginFact): fact is ObjectFact {
92
+ if (fact.object === undefined) return false;
93
+ return fact.type === OBJECT_CHANGE_FACT || fact.type === fact.object.type;
94
+ }
95
+
96
+ /**
97
+ * The object's whole value after `fact`, or undefined when the fact is not an
98
+ * object version (an appended fact) or its change cannot be read.
99
+ */
100
+ export function objectValueAfter(
101
+ fact: PluginFact,
102
+ previous: ObjectData,
103
+ ): ObjectData | undefined {
104
+ if (fact.object === undefined) return undefined;
105
+ if (fact.type === OBJECT_CHANGE_FACT) {
106
+ const change = objectChangeOf(fact.data);
107
+ return change === undefined ? undefined : applyObjectChange(previous, change);
108
+ }
109
+ // A fact written before `put` recorded changes only: data is the whole object.
110
+ if (fact.type === fact.object.type) return { ...fact.data };
111
+ return undefined;
112
+ }
113
+
114
+ /**
115
+ * Yields the object's whole value after each version fact of one object, in
116
+ * order. `start` is the value before the first fact (usually empty); appended
117
+ * facts are skipped and leave it alone. The generator returns the final value,
118
+ * so a reader paging the facts can carry it to the next page.
119
+ */
120
+ export function* foldObjectFacts(
121
+ facts: Iterable<PluginFact>,
122
+ start: ObjectData = {},
123
+ ): Generator<ObjectFactVersion, ObjectData> {
124
+ let current: ObjectData = { ...start };
125
+ for (const fact of facts) {
126
+ const next = objectValueAfter(fact, current);
127
+ if (next === undefined) continue;
128
+ current = next;
129
+ yield { fact, data: current };
130
+ }
131
+ return current;
132
+ }
@@ -0,0 +1,32 @@
1
+ /** Opening the plugin store a configured home uses. */
2
+
3
+ import { join } from "node:path";
4
+ import type { SubscriptionWatchOptions } from "../platform/index.ts";
5
+ import { SqlitePluginStore } from "./sqlite-store.ts";
6
+ import type { PluginStore } from "./types.ts";
7
+
8
+ export type PluginStoreBackend = "sqlite";
9
+
10
+ export interface OpenPluginStoreOptions extends SubscriptionWatchOptions {
11
+ readonly backend: PluginStoreBackend;
12
+ /** The home's store directory. */
13
+ readonly root: string;
14
+ readonly clock?: (() => number) | undefined;
15
+ }
16
+
17
+ /**
18
+ * Opens the object store for a home. It writes `<root>/plugins.sqlite`; the
19
+ * format is not user-visible.
20
+ */
21
+ export function openPluginStore(options: OpenPluginStoreOptions): PluginStore {
22
+ return new SqlitePluginStore({
23
+ root: options.root,
24
+ file: join(options.root, "plugins.sqlite"),
25
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
26
+ ...(options.follow === undefined ? {} : { follow: options.follow }),
27
+ ...(options.readonly === undefined ? {} : { readonly: options.readonly }),
28
+ ...(options.readOnly === undefined ? {} : { readOnly: options.readOnly }),
29
+ ...(options.oneShot === undefined ? {} : { oneShot: options.oneShot }),
30
+ ...(options.repeat === undefined ? {} : { repeat: options.repeat }),
31
+ });
32
+ }
@@ -0,0 +1,133 @@
1
+ /** Shared paging, cursor and `where` rules for the object stores. */
2
+
3
+ import type { ObjectData } from "./types.ts";
4
+ import { isRecord } from "../util.ts";
5
+
6
+ /** The number of objects or facts one page holds when the caller names none. */
7
+ export const DEFAULT_PAGE_LIMIT = 100;
8
+
9
+ /** The largest page any caller may ask for. */
10
+ export const MAX_PAGE_LIMIT = 1000;
11
+
12
+ /** A cursor is not one this store made for this call. */
13
+ export class CursorError extends Error {
14
+ constructor(message: string) {
15
+ super(message);
16
+ this.name = "CursorError";
17
+ }
18
+ }
19
+
20
+ /** A `where` filter names a field the object type did not declare. */
21
+ export class WhereError extends Error {
22
+ constructor(message: string) {
23
+ super(message);
24
+ this.name = "WhereError";
25
+ }
26
+ }
27
+
28
+ function isJsonScalar(value: unknown): boolean {
29
+ return (
30
+ value === null ||
31
+ typeof value === "string" ||
32
+ typeof value === "number" ||
33
+ typeof value === "boolean"
34
+ );
35
+ }
36
+
37
+ /** The limit a page uses: 100 by default, no more than 1000. */
38
+ export function pageLimit(value: number | undefined, field = "limit"): number {
39
+ if (value === undefined) return DEFAULT_PAGE_LIMIT;
40
+ if (!Number.isInteger(value) || value < 1) {
41
+ throw new Error(`${field}: must be a positive integer`);
42
+ }
43
+ return Math.min(value, MAX_PAGE_LIMIT);
44
+ }
45
+
46
+ /** A stable text form of a JSON value, used to compare filter values. */
47
+ export function canonical(value: unknown): string {
48
+ if (Array.isArray(value)) {
49
+ return `[${value.map((item) => canonical(item)).join(",")}]`;
50
+ }
51
+ if (isRecord(value)) {
52
+ const keys = Object.keys(value).sort();
53
+ return `{${keys
54
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
55
+ .join(",")}}`;
56
+ }
57
+ if (value === undefined) return "undefined";
58
+ return JSON.stringify(value) ?? "null";
59
+ }
60
+
61
+ /** The fingerprint a list cursor carries, so a filter cannot be swapped. */
62
+ export function whereFingerprint(where: Readonly<Record<string, unknown>>): string {
63
+ return canonical(where);
64
+ }
65
+
66
+ /** Refuses a filter on a field the type did not declare in `index`. */
67
+ export function assertWhere(
68
+ index: readonly string[],
69
+ where: Readonly<Record<string, unknown>> | undefined,
70
+ label: string,
71
+ ): void {
72
+ if (where === undefined) return;
73
+ if (!isRecord(where)) {
74
+ throw new WhereError(`${label}: where: must be an object of field: value filters`);
75
+ }
76
+ const allowed = new Set(index);
77
+ for (const [field, value] of Object.entries(where)) {
78
+ if (!allowed.has(field)) {
79
+ const fields =
80
+ index.length === 0
81
+ ? "this type declares no index"
82
+ : `indexed fields are ${index.map((item) => `"${item}"`).join(", ")}`;
83
+ throw new WhereError(
84
+ `${label}: where: field "${field}" is not indexed; ${fields}`,
85
+ );
86
+ }
87
+ if (!isJsonScalar(value)) {
88
+ throw new WhereError(
89
+ `${label}: where.${field}: must be a string, number, boolean or null`,
90
+ );
91
+ }
92
+ }
93
+ }
94
+
95
+ /** True when every filter field equals the object's field. */
96
+ export function matchesWhere(
97
+ data: ObjectData,
98
+ where: Readonly<Record<string, unknown>> | undefined,
99
+ ): boolean {
100
+ if (where === undefined) return true;
101
+ for (const [field, value] of Object.entries(where)) {
102
+ if (canonical(data[field]) !== canonical(value)) return false;
103
+ }
104
+ return true;
105
+ }
106
+
107
+ /** Encodes an opaque cursor that a client only passes back. */
108
+ export function encodeCursor(payload: Readonly<Record<string, unknown>>): string {
109
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
110
+ }
111
+
112
+ /** Decodes a cursor and names the call when it is not one this store made. */
113
+ export function decodeCursor(
114
+ cursor: string,
115
+ label: string,
116
+ ): Record<string, unknown> {
117
+ let text: string;
118
+ try {
119
+ text = Buffer.from(cursor, "base64url").toString("utf8");
120
+ } catch {
121
+ throw new CursorError(`${label}: invalid cursor`);
122
+ }
123
+ let value: unknown;
124
+ try {
125
+ value = JSON.parse(text);
126
+ } catch {
127
+ throw new CursorError(`${label}: invalid cursor`);
128
+ }
129
+ if (!isRecord(value)) {
130
+ throw new CursorError(`${label}: invalid cursor`);
131
+ }
132
+ return value;
133
+ }