@happyvertical/smrt-app-runtime 0.43.9

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/dist/index.js ADDED
@@ -0,0 +1,936 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, createHmac, randomBytes } from "node:crypto";
3
+ import { constants, link, lstat, mkdir, open, readdir, realpath, rmdir, unlink } from "node:fs/promises";
4
+ import { homedir, platform } from "node:os";
5
+ import { isAbsolute, parse, relative, resolve, sep } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { Worker } from "node:worker_threads";
8
+ import { resolveApplicationRuntime } from "@happyvertical/smrt-config";
9
+ import { TaskRunner } from "@happyvertical/smrt-jobs";
10
+ import { Person, ProfileTypeCollection } from "@happyvertical/smrt-profiles";
11
+ import { withSystemContext } from "@happyvertical/smrt-tenancy";
12
+ import { DEFAULT_ROLE_SLUGS, MembershipCollection, MembershipStatus, RoleCollection, SessionCollection, SessionService, TenantService, UserCollection, UserStatus } from "@happyvertical/smrt-users";
13
+ import { getDatabase } from "@happyvertical/sql";
14
+ //#region src/index.ts
15
+ var DEFAULT_BIND_HOST = "127.0.0.1";
16
+ var DEFAULT_BOOTSTRAP_TTL_SECONDS = 600;
17
+ var MAX_BOOTSTRAP_TTL_SECONDS = 900;
18
+ var DEFAULT_SESSION_TTL_SECONDS = 10080 * 60;
19
+ var BOOTSTRAP_TABLE = "_smrt_local_owner_bootstrap";
20
+ var SECRET_FILE_NAME = "application.secret";
21
+ var DATABASE_FILE_NAME = "application.sqlite";
22
+ var ROOT_MARKER_PREFIX = ".smrt-local-runtime-";
23
+ var PREFLIGHT_RETRY_LIMIT = 4;
24
+ var INITIALIZATION_LOCK_TIMEOUT_MS = 12e4;
25
+ var INITIALIZATION_LOCK_WORKER = `
26
+ const { parentPort, workerData } = require('node:worker_threads');
27
+ let database;
28
+ let transaction;
29
+ (async () => {
30
+ try {
31
+ const { getDatabase } = await import(workerData.sqlModuleUrl);
32
+ database = await getDatabase({
33
+ type: 'sqlite',
34
+ url: workerData.path,
35
+ secureFile: {
36
+ driver: 'node:sqlite',
37
+ custody: 'trusted-parent',
38
+ root: workerData.custodyRoot,
39
+ },
40
+ transactionQueueTimeout: workerData.timeout,
41
+ });
42
+ if (!database.beginTransaction) {
43
+ throw new Error('Secure SQLite does not expose beginTransaction().');
44
+ }
45
+ await database.query('PRAGMA busy_timeout = ' + workerData.timeout);
46
+ transaction = await database.beginTransaction();
47
+ parentPort.postMessage({ type: 'acquired' });
48
+ } catch (error) {
49
+ try { await database?.close?.(); } catch {}
50
+ parentPort.postMessage({ type: 'error', message: String(error) });
51
+ parentPort.close();
52
+ return;
53
+ }
54
+ parentPort.once('message', async (message) => {
55
+ if (message?.type !== 'release') return;
56
+ let releaseError;
57
+ try { await transaction.rollback(); } catch (error) { releaseError = String(error); }
58
+ try { await database.close?.(); } catch (error) { releaseError ??= String(error); }
59
+ parentPort.postMessage({ type: 'released', error: releaseError });
60
+ parentPort.close();
61
+ });
62
+ })().catch((error) => {
63
+ parentPort.postMessage({ type: 'error', message: String(error) });
64
+ parentPort.close();
65
+ });
66
+ `;
67
+ var execFileAsync = promisify(execFile);
68
+ var LocalRuntimeError = class extends Error {
69
+ constructor(code, message) {
70
+ super(message);
71
+ this.code = code;
72
+ this.name = "LocalRuntimeError";
73
+ }
74
+ code;
75
+ };
76
+ function resolveLocalRuntimePaths(options) {
77
+ const appId = normalizeAppId(options.appId);
78
+ const runtimePlatform = options.platform ?? platform();
79
+ const runtimeHome = options.homeDirectory ?? homedir();
80
+ const defaultRoot = defaultApplicationDataRoot(runtimePlatform, runtimeHome, options.env ?? process.env);
81
+ const root = resolve(options.dataDirectory ?? resolve(defaultRoot, appId));
82
+ const sourceRoot = resolve(options.sourceRoot ?? process.cwd());
83
+ if (sameFilesystemPath(root, runtimeHome, runtimePlatform) || sameFilesystemPath(root, parse(root).root, runtimePlatform) || isInside(sourceRoot, root, runtimePlatform) || isInside(root, sourceRoot, runtimePlatform)) throw new LocalRuntimeError("invalid_configuration", "Local application data must be a dedicated directory that does not overlap the source tree.");
84
+ return Object.freeze({
85
+ root,
86
+ database: resolve(root, DATABASE_FILE_NAME),
87
+ assets: resolve(root, "assets"),
88
+ secrets: resolve(root, "secrets"),
89
+ applicationSecret: resolve(root, "secrets", SECRET_FILE_NAME)
90
+ });
91
+ }
92
+ async function initializeLocalApplicationRuntime(options) {
93
+ const bindHost = normalizeLoopbackHost(options.bindHost ?? DEFAULT_BIND_HOST);
94
+ const bootstrapTtlSeconds = validateBootstrapTtl(options.bootstrapTtlSeconds ?? DEFAULT_BOOTSTRAP_TTL_SECONDS);
95
+ const sessionTtlSeconds = validateSessionTtl(options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS);
96
+ const resolvedRuntime = resolveApplicationRuntime({
97
+ profile: "local",
98
+ providers: options.providers
99
+ });
100
+ const paths = resolveLocalRuntimePaths(options);
101
+ const sourceRoot = resolve(options.sourceRoot ?? process.cwd());
102
+ const appId = normalizeAppId(options.appId);
103
+ await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);
104
+ const initializationLock = await acquireInitializationLock(paths.root);
105
+ let db;
106
+ let initialization;
107
+ let initializationFailure;
108
+ let initializationFailed = false;
109
+ try {
110
+ await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);
111
+ const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);
112
+ db = acquired.db;
113
+ const { canonicalSourceRoot } = acquired;
114
+ await prepareLocalFilesystem(paths, canonicalSourceRoot);
115
+ await tuneLocalSqlite(db);
116
+ await options.prepareDatabase?.(db);
117
+ await ensureBootstrapTable(db);
118
+ const runtime = new InitializedLocalApplicationRuntime({
119
+ db,
120
+ paths,
121
+ bindHost,
122
+ resolvedRuntime,
123
+ bootstrapTtlSeconds,
124
+ sessionTtlSeconds,
125
+ backgroundJobs: options.backgroundJobs === true,
126
+ paidCapabilities: options.paidCapabilities === true,
127
+ now: options.now ?? (() => /* @__PURE__ */ new Date()),
128
+ canonicalSourceRoot
129
+ });
130
+ initialization = {
131
+ runtime,
132
+ bootstrap: await runtime.ensureBootstrapInvitation(),
133
+ diagnostics: await runtime.diagnostics()
134
+ };
135
+ } catch (error) {
136
+ initializationFailed = true;
137
+ initializationFailure = db ? await closeDatabaseAfterFailure(db, error) : error;
138
+ db = void 0;
139
+ }
140
+ try {
141
+ await initializationLock.release();
142
+ } catch (releaseError) {
143
+ if (initializationFailed) initializationFailure = preservePrimaryFailure(initializationFailure, releaseError, "initializationLockReleaseError", "Local runtime initialization and initialization-lock release both failed.");
144
+ else if (db) {
145
+ initializationFailed = true;
146
+ initializationFailure = await closeDatabaseAfterFailure(db, releaseError);
147
+ db = void 0;
148
+ } else {
149
+ initializationFailed = true;
150
+ initializationFailure = releaseError;
151
+ }
152
+ }
153
+ if (initializationFailed) throw initializationFailure;
154
+ if (!initialization) throw new Error("Local runtime initialization completed without a result.");
155
+ return initialization;
156
+ }
157
+ var InitializedLocalApplicationRuntime = class {
158
+ db;
159
+ paths;
160
+ bindHost;
161
+ resolvedRuntime;
162
+ backgroundJobsEnabled;
163
+ paidCapabilitiesEnabled;
164
+ bootstrapTtlSeconds;
165
+ sessionTtlSeconds;
166
+ now;
167
+ canonicalSourceRoot;
168
+ constructor(state) {
169
+ this.db = state.db;
170
+ this.paths = state.paths;
171
+ this.bindHost = state.bindHost;
172
+ this.resolvedRuntime = state.resolvedRuntime;
173
+ this.bootstrapTtlSeconds = state.bootstrapTtlSeconds;
174
+ this.sessionTtlSeconds = state.sessionTtlSeconds;
175
+ this.backgroundJobsEnabled = state.backgroundJobs;
176
+ this.paidCapabilitiesEnabled = state.paidCapabilities;
177
+ this.now = state.now;
178
+ this.canonicalSourceRoot = state.canonicalSourceRoot;
179
+ }
180
+ /**
181
+ * Issue the first short-lived owner invitation when none is active.
182
+ * Repeated startup never rotates an unexpired token or duplicates an owner.
183
+ */
184
+ async ensureBootstrapInvitation() {
185
+ if (await findExistingOwner(this.db)) return null;
186
+ const current = await readBootstrapRow(this.db);
187
+ if (current?.consumed_at != null) return null;
188
+ const now = this.now();
189
+ const currentExpiry = parseStoredDate(current?.expires_at);
190
+ if (current && current.consumed_at == null && currentExpiry !== null && currentExpiry.getTime() > now.getTime()) return null;
191
+ return this.issueBootstrapInvitation(false);
192
+ }
193
+ /** Explicit recovery when an installer lost the one-time plaintext token. */
194
+ async rotateBootstrapInvitation() {
195
+ if (await findExistingOwner(this.db)) throw new LocalRuntimeError("bootstrap_claimed", "The local owner has already been claimed.");
196
+ if ((await readBootstrapRow(this.db))?.consumed_at != null) throw new LocalRuntimeError("bootstrap_claimed", "The local owner bootstrap invitation has already been consumed.");
197
+ const invitation = await this.issueBootstrapInvitation(true);
198
+ if (!invitation) {
199
+ if ((await readBootstrapRow(this.db))?.consumed_at != null) throw new LocalRuntimeError("bootstrap_claimed", "The local owner bootstrap invitation has already been consumed.");
200
+ throw new LocalRuntimeError("bootstrap_unavailable", "A local owner bootstrap invitation could not be issued.");
201
+ }
202
+ return invitation;
203
+ }
204
+ /**
205
+ * Consume a bootstrap token and atomically create normal identity/RBAC/session
206
+ * records. The token transition and every record write share one transaction.
207
+ */
208
+ async claimOwner(input) {
209
+ validateOwnerInput(input);
210
+ if (await findExistingOwner(this.db)) throw new LocalRuntimeError("bootstrap_claimed", "The local owner has already been claimed.");
211
+ if (typeof this.db.transaction !== "function") throw new LocalRuntimeError("bootstrap_unavailable", "Owner bootstrap requires a database adapter with transaction support.");
212
+ const tokenHash = await this.hashBootstrapToken(input.token);
213
+ const now = this.now();
214
+ const nowIso = now.toISOString();
215
+ return this.db.transaction(async (tx) => {
216
+ if ((await tx.query(`UPDATE ${BOOTSTRAP_TABLE}
217
+ SET consumed_at = ?
218
+ WHERE slot = 1
219
+ AND token_hash = ?
220
+ AND consumed_at IS NULL
221
+ AND expires_at > ?
222
+ RETURNING expires_at`, nowIso, tokenHash, nowIso)).rows.length === 0) await throwBootstrapClaimFailure(tx, now);
223
+ if (await findExistingOwner(tx)) throw new LocalRuntimeError("bootstrap_claimed", "The local owner has already been claimed.");
224
+ return createLocalOwnerRecords(tx, input, this.sessionTtlSeconds);
225
+ });
226
+ }
227
+ /** Restore the normal server-side session created by owner bootstrap. */
228
+ async restoreSession(sessionId) {
229
+ const service = new SessionService({ db: this.db });
230
+ await service.initialize();
231
+ return service.loadSessionContext(sessionId);
232
+ }
233
+ /**
234
+ * Create an in-process persisted-job runner. Background work is default-off
235
+ * and must be explicitly enabled by runtime configuration.
236
+ */
237
+ async createEmbeddedJobRunner(config = {}) {
238
+ if (!this.backgroundJobsEnabled) throw new LocalRuntimeError("capability_disabled", "Background jobs are disabled; enable them explicitly for this local application.");
239
+ if (this.resolvedRuntime.providers.jobs.topology !== "embedded") throw new LocalRuntimeError("invalid_configuration", "An embedded runner requires the local embedded job topology.");
240
+ const runner = new TaskRunner({
241
+ concurrency: 1,
242
+ retention: false,
243
+ ...config
244
+ });
245
+ await runner.initialize(this.db);
246
+ return runner;
247
+ }
248
+ /** Return a deterministic snapshot that never reads secret file contents. */
249
+ async diagnostics() {
250
+ const owner = await findExistingOwner(this.db);
251
+ const bootstrap = await readBootstrapRow(this.db);
252
+ const now = this.now();
253
+ const expiresAt = parseStoredDate(bootstrap?.expires_at);
254
+ let status = "unavailable";
255
+ if (owner || bootstrap?.consumed_at != null) status = "claimed";
256
+ else if (expiresAt && expiresAt.getTime() > now.getTime()) status = "available";
257
+ else if (expiresAt) status = "expired";
258
+ return Object.freeze({
259
+ schemaVersion: 1,
260
+ runtime: this.resolvedRuntime,
261
+ bind: Object.freeze({
262
+ host: this.bindHost,
263
+ loopback: true
264
+ }),
265
+ paths: this.paths,
266
+ storage: Object.freeze({
267
+ database: "sqlite-file",
268
+ assets: "user-owned-directory",
269
+ secrets: "mode-0600-local-file"
270
+ }),
271
+ bootstrap: Object.freeze({
272
+ status,
273
+ expiresAt: expiresAt?.toISOString() ?? null,
274
+ tokenValuesIncluded: false,
275
+ tokenHashesIncluded: false
276
+ }),
277
+ tenancy: Object.freeze({
278
+ mode: "real-default-tenant",
279
+ ui: "hidden"
280
+ }),
281
+ jobs: Object.freeze({
282
+ topology: this.resolvedRuntime.providers.jobs.topology,
283
+ backgroundEnabled: this.backgroundJobsEnabled
284
+ }),
285
+ paidCapabilitiesEnabled: this.paidCapabilitiesEnabled,
286
+ secretValuesIncluded: false
287
+ });
288
+ }
289
+ async issueBootstrapInvitation(replaceActive) {
290
+ const token = randomBytes(32).toString("base64url");
291
+ const tokenHash = await this.hashBootstrapToken(token);
292
+ const now = this.now();
293
+ const expiresAt = new Date(now.getTime() + this.bootstrapTtlSeconds * 1e3);
294
+ if ((await this.db.query(`INSERT INTO ${BOOTSTRAP_TABLE}
295
+ (slot, token_hash, expires_at, consumed_at, created_at)
296
+ VALUES (1, ?, ?, NULL, ?)
297
+ ON CONFLICT(slot) DO UPDATE SET
298
+ token_hash = excluded.token_hash,
299
+ expires_at = excluded.expires_at,
300
+ consumed_at = NULL,
301
+ created_at = excluded.created_at
302
+ WHERE ${BOOTSTRAP_TABLE}.consumed_at IS NULL
303
+ AND (? = 1 OR ${BOOTSTRAP_TABLE}.expires_at <= ?)
304
+ RETURNING token_hash`, tokenHash, expiresAt.toISOString(), now.toISOString(), replaceActive ? 1 : 0, now.toISOString())).rows[0]?.token_hash !== tokenHash) return null;
305
+ return Object.freeze({
306
+ token,
307
+ expiresAt: expiresAt.toISOString()
308
+ });
309
+ }
310
+ async hashBootstrapToken(token) {
311
+ return createHmac("sha256", (await validateApplicationSecret(this.paths.applicationSecret, this.canonicalSourceRoot)).trim()).update(token).digest("hex");
312
+ }
313
+ };
314
+ async function createLocalOwnerRecords(db, input, sessionTtlSeconds) {
315
+ const profileTypes = await ProfileTypeCollection.create({ db });
316
+ const person = new Person({
317
+ db,
318
+ typeId: requireId((await withSystemContext(() => profileTypes.getOrCreateGlobalBySlug("person", {
319
+ name: "Person",
320
+ description: "An individual person"
321
+ }))).id, "Person profile type"),
322
+ tenantId: null,
323
+ name: input.name.trim(),
324
+ email: input.email.trim()
325
+ });
326
+ await person.initialize();
327
+ await person.save();
328
+ const user = await (await UserCollection.create({ db })).create({
329
+ profileId: requireId(person.id, "Person"),
330
+ email: input.email.trim(),
331
+ status: UserStatus.ACTIVE,
332
+ lastLoginAt: /* @__PURE__ */ new Date()
333
+ });
334
+ await user.save();
335
+ const tenantService = new TenantService({ db }, {
336
+ mode: "required",
337
+ maxTenants: 1,
338
+ defaultName: input.tenantName?.trim() || "My Workspace"
339
+ });
340
+ await tenantService.initialize();
341
+ const { tenant, membership } = await tenantService.createTenantWithOwnership(requireId(user.id, "User"), input.tenantName?.trim() || "My Workspace", { slug: "default" });
342
+ const session = await (await SessionCollection.create({ db })).createSession({
343
+ userId: requireId(user.id, "User"),
344
+ tenantId: requireId(tenant.id, "Tenant"),
345
+ ttl: sessionTtlSeconds,
346
+ userAgent: input.userAgent,
347
+ ipAddress: input.ipAddress,
348
+ data: { localOwner: true }
349
+ });
350
+ return Object.freeze({
351
+ profileId: requireId(person.id, "Person"),
352
+ userId: requireId(user.id, "User"),
353
+ tenantId: requireId(tenant.id, "Tenant"),
354
+ membershipId: requireId(membership.id, "Membership"),
355
+ sessionId: requireId(session.id, "Session")
356
+ });
357
+ }
358
+ async function findExistingOwner(db) {
359
+ const ownerRole = await (await RoleCollection.create({ db })).findSystemRoleBySlug(DEFAULT_ROLE_SLUGS.OWNER);
360
+ if (!ownerRole?.id) return null;
361
+ const active = (await (await MembershipCollection.create({ db })).findByRole(ownerRole.id)).find((membership) => membership.status === MembershipStatus.ACTIVE && typeof membership.userId === "string" && typeof membership.tenantId === "string");
362
+ return active ? {
363
+ userId: active.userId,
364
+ tenantId: active.tenantId
365
+ } : null;
366
+ }
367
+ async function throwBootstrapClaimFailure(db, now) {
368
+ const row = await readBootstrapRow(db);
369
+ if (!row) throw new LocalRuntimeError("bootstrap_unavailable", "No local owner bootstrap invitation is available.");
370
+ if (row.consumed_at != null) throw new LocalRuntimeError("bootstrap_claimed", "The local owner bootstrap invitation has already been consumed.");
371
+ const expiresAt = parseStoredDate(row.expires_at);
372
+ if (!expiresAt || expiresAt.getTime() <= now.getTime()) throw new LocalRuntimeError("bootstrap_expired", "The local owner bootstrap invitation has expired.");
373
+ throw new LocalRuntimeError("bootstrap_invalid", "The local owner bootstrap token is invalid.");
374
+ }
375
+ async function readBootstrapRow(db) {
376
+ return (await db.query(`SELECT expires_at, consumed_at
377
+ FROM ${BOOTSTRAP_TABLE}
378
+ WHERE slot = 1
379
+ LIMIT 1`)).rows[0] ?? null;
380
+ }
381
+ async function ensureBootstrapTable(db) {
382
+ await db.query(`CREATE TABLE IF NOT EXISTS ${BOOTSTRAP_TABLE} (
383
+ slot INTEGER PRIMARY KEY CHECK (slot = 1),
384
+ token_hash TEXT NOT NULL,
385
+ expires_at TEXT NOT NULL,
386
+ consumed_at TEXT NULL,
387
+ created_at TEXT NOT NULL
388
+ )`);
389
+ }
390
+ async function tuneLocalSqlite(db) {
391
+ await db.query("PRAGMA foreign_keys = ON");
392
+ await db.query("PRAGMA journal_mode = WAL");
393
+ await db.query("PRAGMA synchronous = FULL");
394
+ await db.query("PRAGMA busy_timeout = 5000");
395
+ }
396
+ async function preflightLocalApplicationRoot(root, sourceRoot, appId) {
397
+ for (let attempt = 0; attempt < PREFLIGHT_RETRY_LIMIT; attempt += 1) try {
398
+ await preflightLocalApplicationRootOnce(root, sourceRoot, appId);
399
+ return;
400
+ } catch (error) {
401
+ if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;
402
+ if (attempt === PREFLIGHT_RETRY_LIMIT - 1) throw unsafeFilesystemEntry("Local application data changed repeatedly during read-only preflight.", error);
403
+ await new Promise((resolveRetry) => setImmediate(resolveRetry));
404
+ }
405
+ }
406
+ async function preflightLocalApplicationRootOnce(root, sourceRoot, appId) {
407
+ requireNoFollowSupport();
408
+ const canonicalSourceRoot = await realpath(sourceRoot);
409
+ const currentUid = process.getuid?.();
410
+ if (currentUid === void 0) throw unsafeFilesystemEntry("Local runtime storage requires a numeric current-user identity.");
411
+ if (isInside(canonicalSourceRoot, root) || isInside(root, canonicalSourceRoot)) throw unsafeFilesystemEntry("Local application data must remain outside the canonical source tree.");
412
+ let rootExists = true;
413
+ for (const component of absolutePathComponents(root)) {
414
+ let details;
415
+ try {
416
+ details = await lstat(component);
417
+ } catch (error) {
418
+ if (!isMissingFile(error)) throw error;
419
+ rootExists = false;
420
+ break;
421
+ }
422
+ if (details.isSymbolicLink() || !details.isDirectory()) throw unsafeFilesystemEntry(`Local runtime path component must be a real directory: ${component}`);
423
+ await assertCanonicalEntry(component, canonicalSourceRoot);
424
+ const sharedStickyRoot = details.uid === 0 && (details.mode & 512) !== 0;
425
+ if (details.uid !== currentUid && details.uid !== 0 || (details.mode & 18) !== 0 && !sharedStickyRoot) throw unsafeFilesystemEntry(`Local runtime path ancestry does not have trusted-parent custody: ${component}`);
426
+ await assertNoPermissiveDarwinAcl(component);
427
+ }
428
+ if (!rootExists) return;
429
+ const rootDetails = await lstat(root);
430
+ if (rootDetails.uid !== currentUid || (rootDetails.mode & 511) !== 448) throw unsafeFilesystemEntry(`Existing local application data root must already be owned by the current user with mode 0700: ${root}`);
431
+ await preflightDedicatedRoot(root, canonicalSourceRoot, appId);
432
+ }
433
+ async function preflightDedicatedRoot(root, canonicalSourceRoot, appId) {
434
+ const finalMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}`);
435
+ const pendingMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}.pending`);
436
+ const entries = await readdir(root);
437
+ const finalMarkerName = finalMarker.slice(root.length + 1);
438
+ const pendingMarkerName = pendingMarker.slice(root.length + 1);
439
+ const hasFinalMarker = entries.includes(finalMarkerName);
440
+ const hasPendingMarker = entries.includes(pendingMarkerName);
441
+ if (hasFinalMarker) {
442
+ await validateRootMarker(finalMarker, canonicalSourceRoot);
443
+ if (hasPendingMarker) await validateRootMarker(pendingMarker, canonicalSourceRoot);
444
+ return;
445
+ }
446
+ if (hasPendingMarker) {
447
+ await validateRootMarker(pendingMarker, canonicalSourceRoot);
448
+ const permittedInterruptedEntries = /* @__PURE__ */ new Set([
449
+ pendingMarkerName,
450
+ DATABASE_FILE_NAME,
451
+ `${DATABASE_FILE_NAME}-shm`,
452
+ `${DATABASE_FILE_NAME}-wal`
453
+ ]);
454
+ if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) throw unsafeFilesystemEntry("Interrupted local application root contains unexpected artifacts.");
455
+ return;
456
+ }
457
+ if (entries.length > 0) throw unsafeFilesystemEntry("Existing local application data root is populated but has no valid ownership marker.");
458
+ }
459
+ async function assertNoPermissiveDarwinAcl(path) {
460
+ if (platform() !== "darwin") return;
461
+ let listing;
462
+ try {
463
+ listing = (await execFileAsync("/bin/ls", [
464
+ "-lde",
465
+ "--",
466
+ path
467
+ ], {
468
+ encoding: "utf8",
469
+ env: {
470
+ ...process.env,
471
+ LC_ALL: "C"
472
+ }
473
+ })).stdout;
474
+ } catch (error) {
475
+ throw unsafeFilesystemEntry(`Local runtime could not inspect macOS access controls: ${path}`, error);
476
+ }
477
+ for (const line of listing.split("\n")) {
478
+ if (!/^\s*\d+:/.test(line)) continue;
479
+ if (line.match(/^\s*\d+:\s+.+\s+(allow|deny)\s+\S.*$/)?.[1] !== "deny") throw unsafeFilesystemEntry(`Local runtime path contains a permissive macOS access control list: ${path}`);
480
+ }
481
+ }
482
+ async function acquireLocalDatabase(paths, sourceRoot, appId) {
483
+ requireNoFollowSupport();
484
+ const canonicalSourceRoot = await realpath(sourceRoot);
485
+ const createdDirectories = await ensureSafeDirectoryTree(paths.root, canonicalSourceRoot, true);
486
+ const prepared = await prepareDedicatedRoot(paths.root, canonicalSourceRoot, appId, createdDirectories);
487
+ let db;
488
+ try {
489
+ db = await getDatabase({
490
+ type: "sqlite",
491
+ url: paths.database,
492
+ secureFile: {
493
+ driver: "node:sqlite",
494
+ custody: "trusted-parent",
495
+ root: paths.root
496
+ }
497
+ });
498
+ } catch (error) {
499
+ if (prepared.pendingMarkerCreatedByAttempt) {
500
+ await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);
501
+ await removeCreatedDirectories(createdDirectories);
502
+ }
503
+ throw error;
504
+ }
505
+ try {
506
+ await publishRootMarker(prepared.finalMarker, canonicalSourceRoot);
507
+ await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);
508
+ } catch (error) {
509
+ throw await closeDatabaseAfterFailure(db, error);
510
+ }
511
+ return {
512
+ canonicalSourceRoot,
513
+ db
514
+ };
515
+ }
516
+ async function closeDatabaseAfterFailure(db, primaryFailure) {
517
+ try {
518
+ await db.close?.();
519
+ } catch (cleanupFailure) {
520
+ return preservePrimaryFailure(primaryFailure, cleanupFailure, "databaseCleanupError", "Local runtime initialization and database cleanup both failed.");
521
+ }
522
+ return primaryFailure;
523
+ }
524
+ function preservePrimaryFailure(primaryFailure, secondaryFailure, secondaryProperty, aggregateMessage) {
525
+ if (primaryFailure instanceof Error) {
526
+ try {
527
+ Object.defineProperty(primaryFailure, secondaryProperty, {
528
+ value: secondaryFailure,
529
+ configurable: true
530
+ });
531
+ } catch {}
532
+ return primaryFailure;
533
+ }
534
+ return new AggregateError([primaryFailure, secondaryFailure], aggregateMessage);
535
+ }
536
+ async function prepareLocalFilesystem(paths, canonicalSourceRoot) {
537
+ await ensureSafeDirectoryTree(paths.assets, canonicalSourceRoot);
538
+ await ensureSafeDirectoryTree(paths.secrets, canonicalSourceRoot);
539
+ await ensureApplicationSecret(paths.applicationSecret, canonicalSourceRoot);
540
+ }
541
+ async function prepareDedicatedRoot(path, canonicalSourceRoot, appId, createdDirectories) {
542
+ const finalMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}`);
543
+ const pendingMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}.pending`);
544
+ const entries = await readdir(path);
545
+ const hasFinalMarker = entries.includes(finalMarker.slice(path.length + 1));
546
+ const hasPendingMarker = entries.includes(pendingMarker.slice(path.length + 1));
547
+ if (hasFinalMarker) {
548
+ await validateRootMarker(finalMarker, canonicalSourceRoot);
549
+ if (hasPendingMarker) await validateRootMarker(pendingMarker, canonicalSourceRoot);
550
+ return {
551
+ createdDirectories,
552
+ pendingMarker: hasPendingMarker ? pendingMarker : null,
553
+ pendingMarkerCreatedByAttempt: false,
554
+ finalMarker
555
+ };
556
+ }
557
+ if (hasPendingMarker) {
558
+ await validateRootMarker(pendingMarker, canonicalSourceRoot);
559
+ const permittedInterruptedEntries = /* @__PURE__ */ new Set([
560
+ pendingMarker.slice(path.length + 1),
561
+ DATABASE_FILE_NAME,
562
+ `${DATABASE_FILE_NAME}-shm`,
563
+ `${DATABASE_FILE_NAME}-wal`
564
+ ]);
565
+ if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) throw unsafeFilesystemEntry("Interrupted local application root contains unexpected artifacts.");
566
+ return {
567
+ createdDirectories,
568
+ pendingMarker,
569
+ pendingMarkerCreatedByAttempt: false,
570
+ finalMarker
571
+ };
572
+ }
573
+ if (entries.length > 0) throw unsafeFilesystemEntry("Existing local application data root is populated but has no valid ownership marker.");
574
+ return {
575
+ createdDirectories,
576
+ pendingMarker,
577
+ pendingMarkerCreatedByAttempt: await publishRootMarker(pendingMarker, canonicalSourceRoot),
578
+ finalMarker
579
+ };
580
+ }
581
+ async function acquireInitializationLock(root) {
582
+ const currentUid = process.getuid?.();
583
+ if (currentUid === void 0) throw unsafeFilesystemEntry("Local runtime initialization locks require a numeric current-user identity.");
584
+ const lockRoot = resolve(await realpath("/tmp"), `.smrt-${currentUid}`);
585
+ try {
586
+ await mkdir(lockRoot, { mode: 448 });
587
+ } catch (error) {
588
+ if (!isFileAlreadyExists(error)) throw error;
589
+ }
590
+ const lockRootDetails = await lstat(lockRoot);
591
+ if (!lockRootDetails.isDirectory() || lockRootDetails.isSymbolicLink() || lockRootDetails.uid !== currentUid || (lockRootDetails.mode & 511) !== 448) throw unsafeFilesystemEntry(`Local runtime lock directory must be current-user-owned with mode 0700: ${lockRoot}`);
592
+ const custodyRoot = resolve(lockRoot, createHash("sha256").update(normalizeFilesystemIdentity(root)).digest("hex").slice(0, 32));
593
+ try {
594
+ await mkdir(custodyRoot, { mode: 448 });
595
+ } catch (error) {
596
+ if (!isFileAlreadyExists(error)) throw error;
597
+ }
598
+ return acquireInitializationDatabaseLease(resolve(custodyRoot, "initialization.sqlite"), custodyRoot);
599
+ }
600
+ async function acquireInitializationDatabaseLease(path, custodyRoot) {
601
+ const worker = new Worker(INITIALIZATION_LOCK_WORKER, {
602
+ eval: true,
603
+ workerData: {
604
+ path,
605
+ custodyRoot,
606
+ timeout: INITIALIZATION_LOCK_TIMEOUT_MS,
607
+ sqlModuleUrl: import.meta.resolve("@happyvertical/sql")
608
+ }
609
+ });
610
+ const acquisitionFailure = (cause) => {
611
+ const failure = new LocalRuntimeError("invalid_configuration", "Could not acquire the local runtime initialization lease within two minutes.");
612
+ Object.defineProperty(failure, "cause", { value: cause });
613
+ return failure;
614
+ };
615
+ let workerError;
616
+ const exited = new Promise((_resolve, reject) => {
617
+ worker.once("error", (error) => {
618
+ workerError = error;
619
+ });
620
+ worker.once("exit", (code) => {
621
+ reject(acquisitionFailure(workerError ?? /* @__PURE__ */ new Error(`Initialization lock worker exited ${code}.`)));
622
+ });
623
+ });
624
+ const acquired = new Promise((resolvePromise, reject) => {
625
+ const onMessage = (message) => {
626
+ if (message.type === "acquired") {
627
+ worker.off("message", onMessage);
628
+ resolvePromise();
629
+ } else if (message.type === "error") {
630
+ worker.off("message", onMessage);
631
+ reject(acquisitionFailure(new Error(message.message)));
632
+ }
633
+ };
634
+ worker.on("message", onMessage);
635
+ });
636
+ await Promise.race([acquired, exited]);
637
+ let released = false;
638
+ return { release: async () => {
639
+ if (released) return;
640
+ released = true;
641
+ const releaseCompleted = new Promise((resolvePromise, reject) => {
642
+ const onMessage = (message) => {
643
+ if (message.type !== "released") return;
644
+ worker.off("message", onMessage);
645
+ if (message.error) reject(new Error(message.error));
646
+ else resolvePromise();
647
+ };
648
+ worker.on("message", onMessage);
649
+ worker.postMessage({ type: "release" });
650
+ });
651
+ try {
652
+ await Promise.race([releaseCompleted, exited]);
653
+ } finally {
654
+ await worker.terminate();
655
+ }
656
+ } };
657
+ }
658
+ async function ensureSafeDirectoryTree(path, canonicalSourceRoot, dedicatedRoot = false) {
659
+ const components = absolutePathComponents(path);
660
+ const createdDirectories = [];
661
+ for (const component of components) {
662
+ let created = false;
663
+ try {
664
+ const details = await lstat(component);
665
+ if (details.isSymbolicLink() || !details.isDirectory()) throw unsafeFilesystemEntry(`Local runtime path component must be a real directory: ${component}`);
666
+ } catch (error) {
667
+ if (!isMissingFile(error)) throw error;
668
+ try {
669
+ await mkdir(component, { mode: 448 });
670
+ created = true;
671
+ createdDirectories.push(component);
672
+ } catch (mkdirError) {
673
+ if (!isFileAlreadyExists(mkdirError)) throw mkdirError;
674
+ }
675
+ }
676
+ const directory = await openSafeDirectory(component, canonicalSourceRoot);
677
+ try {
678
+ await assertCanonicalEntry(component, canonicalSourceRoot);
679
+ if (component === path && dedicatedRoot && !created) await assertExistingDedicatedRoot(directory, component, canonicalSourceRoot);
680
+ if (created || component === path && !dedicatedRoot) await directory.chmod(448);
681
+ } finally {
682
+ await directory.close();
683
+ }
684
+ }
685
+ await validateExistingPathChain(path, canonicalSourceRoot, "directory");
686
+ return createdDirectories;
687
+ }
688
+ async function assertExistingDedicatedRoot(directory, path, canonicalSourceRoot) {
689
+ const canonical = await realpath(path);
690
+ if (isInside(canonicalSourceRoot, canonical) || isInside(canonical, canonicalSourceRoot)) throw unsafeFilesystemEntry("Local application data must be a dedicated directory that does not overlap the canonical source tree.");
691
+ const details = await directory.stat();
692
+ const currentUid = process.getuid?.();
693
+ if (currentUid === void 0 || details.uid !== currentUid || (details.mode & 511) !== 448) throw unsafeFilesystemEntry(`Existing local application data root must already be owned by the current user with mode 0700: ${path}`);
694
+ }
695
+ async function publishRootMarker(path, canonicalSourceRoot) {
696
+ let marker;
697
+ let created = false;
698
+ try {
699
+ marker = await openSafeFile(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384, "Local application root marker", canonicalSourceRoot);
700
+ created = true;
701
+ await marker.sync();
702
+ } catch (error) {
703
+ if (!isFileAlreadyExists(error)) throw error;
704
+ } finally {
705
+ await marker?.close();
706
+ }
707
+ await validateRootMarker(path, canonicalSourceRoot);
708
+ await syncDirectory(resolve(path, ".."), canonicalSourceRoot);
709
+ return created;
710
+ }
711
+ async function validateRootMarker(path, canonicalSourceRoot) {
712
+ await validateExistingPathChain(path, canonicalSourceRoot, "file");
713
+ const marker = await openSafeFile(path, constants.O_RDONLY, 384, "Local application root marker", canonicalSourceRoot);
714
+ try {
715
+ const details = await marker.stat();
716
+ const currentUid = process.getuid?.();
717
+ if (currentUid === void 0 || details.uid !== currentUid || (details.mode & 511) !== 384 || details.size !== 0) throw unsafeFilesystemEntry(`Local application root marker must be an empty current-user-owned mode-0600 file: ${path}`);
718
+ } finally {
719
+ await marker.close();
720
+ }
721
+ }
722
+ async function removeMarkerIfPresent(path, canonicalSourceRoot) {
723
+ if (path === null) return;
724
+ try {
725
+ await validateRootMarker(path, canonicalSourceRoot);
726
+ await unlink(path);
727
+ await syncDirectory(resolve(path, ".."), canonicalSourceRoot);
728
+ } catch (error) {
729
+ if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;
730
+ }
731
+ }
732
+ async function removeCreatedDirectories(paths) {
733
+ for (const path of paths.toReversed()) try {
734
+ await rmdir(path);
735
+ } catch (error) {
736
+ if (!isMissingFile(error) && !isDirectoryNotEmpty(error)) throw error;
737
+ }
738
+ }
739
+ async function ensureApplicationSecret(path, canonicalSourceRoot) {
740
+ const directoryPath = resolve(path, "..");
741
+ const temporaryPath = resolve(directoryPath, `.${SECRET_FILE_NAME}.tmp-${randomBytes(16).toString("hex")}`);
742
+ let temporary;
743
+ let failure;
744
+ try {
745
+ temporary = await openSafeFile(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384, "Temporary application secret", canonicalSourceRoot);
746
+ await temporary.writeFile(`${randomBytes(32).toString("base64url")}
747
+ `, "utf8");
748
+ await temporary.sync();
749
+ await temporary.close();
750
+ temporary = void 0;
751
+ try {
752
+ await link(temporaryPath, path);
753
+ } catch (error) {
754
+ if (!isFileAlreadyExists(error)) throw error;
755
+ }
756
+ await validateApplicationSecret(path, canonicalSourceRoot);
757
+ await syncDirectory(directoryPath, canonicalSourceRoot);
758
+ } catch (error) {
759
+ failure = error;
760
+ }
761
+ try {
762
+ await temporary?.close();
763
+ } catch (error) {
764
+ failure ??= error;
765
+ }
766
+ try {
767
+ await unlink(temporaryPath);
768
+ } catch (error) {
769
+ if (!isMissingFile(error)) failure ??= error;
770
+ }
771
+ if (failure !== void 0) throw failure;
772
+ await removeStaleSecretTemps(directoryPath);
773
+ }
774
+ async function validateApplicationSecret(path, canonicalSourceRoot) {
775
+ await validateExistingPathChain(path, canonicalSourceRoot, "file");
776
+ const file = await openSafeFile(path, constants.O_RDONLY, 384, "Application secret", canonicalSourceRoot);
777
+ try {
778
+ const details = await file.stat();
779
+ const currentUid = process.getuid?.();
780
+ const secret = await file.readFile("utf8");
781
+ await validateExistingPathChain(path, canonicalSourceRoot, "file");
782
+ if (currentUid === void 0 || details.uid !== currentUid || (details.mode & 511) !== 384 || details.size !== 44 || !/^[A-Za-z0-9_-]{43}\n$/.test(secret)) throw unsafeFilesystemEntry("Application secret must be a complete current-user-owned mode-0600 value in the expected format.");
783
+ return secret;
784
+ } finally {
785
+ await file.close();
786
+ }
787
+ }
788
+ async function syncDirectory(path, canonicalSourceRoot) {
789
+ const directory = await openSafeDirectory(path, canonicalSourceRoot);
790
+ try {
791
+ await directory.sync();
792
+ } finally {
793
+ await directory.close();
794
+ }
795
+ }
796
+ async function removeStaleSecretTemps(directoryPath) {
797
+ const prefix = `.${SECRET_FILE_NAME}.tmp-`;
798
+ for (const entry of await readdir(directoryPath)) {
799
+ if (!entry.startsWith(prefix)) continue;
800
+ try {
801
+ await unlink(resolve(directoryPath, entry));
802
+ } catch (error) {
803
+ if (!isMissingFile(error)) throw error;
804
+ }
805
+ }
806
+ }
807
+ async function openSafeDirectory(path, canonicalSourceRoot) {
808
+ let directory;
809
+ try {
810
+ directory = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
811
+ await validateOpenHandlePath(directory, path, "directory", canonicalSourceRoot);
812
+ return directory;
813
+ } catch (error) {
814
+ await directory?.close();
815
+ if (error instanceof LocalRuntimeError) throw error;
816
+ throw unsafeFilesystemEntry(`Could not safely open local runtime directory: ${path}`, error);
817
+ }
818
+ }
819
+ async function openSafeFile(path, flags, mode, label, canonicalSourceRoot) {
820
+ let file;
821
+ try {
822
+ file = await open(path, flags | constants.O_NOFOLLOW, mode);
823
+ await validateOpenHandlePath(file, path, "file", canonicalSourceRoot);
824
+ return file;
825
+ } catch (error) {
826
+ await file?.close();
827
+ if (error instanceof LocalRuntimeError || isFileAlreadyExists(error)) throw error;
828
+ throw unsafeFilesystemEntry(`${label} could not be opened without following symbolic links.`, error);
829
+ }
830
+ }
831
+ async function validateOpenHandlePath(handle, path, expectedType, canonicalSourceRoot) {
832
+ const opened = await handle.stat();
833
+ const current = await lstat(path);
834
+ const expectedDirectory = expectedType === "directory";
835
+ if (current.isSymbolicLink() || (expectedDirectory ? !opened.isDirectory() : !opened.isFile()) || (expectedDirectory ? !current.isDirectory() : !current.isFile()) || opened.dev !== current.dev || opened.ino !== current.ino) throw unsafeFilesystemEntry(`Local runtime ${expectedType} changed while it was being opened: ${path}`);
836
+ await validateExistingPathChain(path, canonicalSourceRoot, expectedType);
837
+ const afterValidation = await lstat(path);
838
+ if (afterValidation.isSymbolicLink() || opened.dev !== afterValidation.dev || opened.ino !== afterValidation.ino) throw unsafeFilesystemEntry(`Local runtime ${expectedType} changed during validation: ${path}`);
839
+ }
840
+ async function validateExistingPathChain(path, canonicalSourceRoot, leafType) {
841
+ const components = absolutePathComponents(path);
842
+ for (const [index, component] of components.entries()) {
843
+ const details = await lstat(component);
844
+ const expectedFile = index === components.length - 1 && leafType === "file";
845
+ if (details.isSymbolicLink() || (expectedFile ? !details.isFile() : !details.isDirectory())) throw unsafeFilesystemEntry(`Local runtime path contains an unsafe component: ${component}`);
846
+ await assertCanonicalEntry(component, canonicalSourceRoot);
847
+ }
848
+ }
849
+ async function assertCanonicalEntry(path, canonicalSourceRoot) {
850
+ const canonical = await realpath(path);
851
+ if (!sameFilesystemPath(canonical, path)) throw unsafeFilesystemEntry(`Local runtime path must not be redirected: ${path}`);
852
+ if (isInside(canonicalSourceRoot, canonical)) throw unsafeFilesystemEntry("Local application data must remain outside the canonical source tree.");
853
+ }
854
+ function absolutePathComponents(path) {
855
+ const absolute = resolve(path);
856
+ const root = parse(absolute).root;
857
+ const parts = absolute.slice(root.length).split(sep).filter(Boolean);
858
+ const components = [root];
859
+ for (const part of parts) components.push(resolve(components.at(-1), part));
860
+ return components;
861
+ }
862
+ function requireNoFollowSupport() {
863
+ if (typeof constants.O_NOFOLLOW !== "number" || constants.O_NOFOLLOW === 0 || typeof constants.O_DIRECTORY !== "number" || constants.O_DIRECTORY === 0) throw unsafeFilesystemEntry("This platform cannot safely initialize local storage without no-follow filesystem support.");
864
+ }
865
+ function sameFilesystemPath(left, right, runtimePlatform = platform()) {
866
+ return normalizeFilesystemIdentity(left, runtimePlatform) === normalizeFilesystemIdentity(right, runtimePlatform);
867
+ }
868
+ function usesCaseInsensitivePathGuards(runtimePlatform) {
869
+ return runtimePlatform === "win32" || runtimePlatform === "darwin";
870
+ }
871
+ function normalizeFilesystemIdentity(value, runtimePlatform = platform()) {
872
+ const normalized = resolve(value);
873
+ return usesCaseInsensitivePathGuards(runtimePlatform) ? normalized.toLowerCase() : normalized;
874
+ }
875
+ function unsafeFilesystemEntry(message, cause) {
876
+ const error = new LocalRuntimeError("invalid_configuration", message);
877
+ if (cause !== void 0) Object.defineProperty(error, "cause", { value: cause });
878
+ return error;
879
+ }
880
+ function validateBootstrapTtl(value) {
881
+ if (!Number.isInteger(value) || value < 1 || value > MAX_BOOTSTRAP_TTL_SECONDS) throw new LocalRuntimeError("invalid_configuration", `Owner bootstrap TTL must be an integer from 1 to ${MAX_BOOTSTRAP_TTL_SECONDS} seconds.`);
882
+ return value;
883
+ }
884
+ function validateSessionTtl(value) {
885
+ if (!Number.isInteger(value) || value < 1) throw new LocalRuntimeError("invalid_configuration", "Session TTL must be a whole number of seconds greater than or equal to 1.");
886
+ return value;
887
+ }
888
+ function validateOwnerInput(input) {
889
+ if (!input.token || !input.name.trim() || !input.email.trim()) throw new LocalRuntimeError("bootstrap_invalid", "Owner bootstrap requires a token, name, and email address.");
890
+ }
891
+ function normalizeLoopbackHost(value) {
892
+ const host = value.trim().toLowerCase().replace(/^\[|\]$/g, "");
893
+ if (host === "::1") return host;
894
+ const octets = host.split(".");
895
+ if (octets.length === 4 && octets.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255) && Number(octets[0]) === 127) return host;
896
+ throw new LocalRuntimeError("unsafe_public_exposure", "Owner bootstrap is restricted to a loopback IP literal. Use ::1 or 127.0.0.0/8.");
897
+ }
898
+ function normalizeAppId(value) {
899
+ const appId = value.trim().toLowerCase();
900
+ if (!/^[a-z0-9][a-z0-9.-]{0,62}$/.test(appId)) throw new LocalRuntimeError("invalid_configuration", "appId must contain only lowercase letters, digits, dots, or hyphens.");
901
+ return appId;
902
+ }
903
+ function defaultApplicationDataRoot(runtimePlatform, runtimeHome, env) {
904
+ if (runtimePlatform === "darwin") return resolve(runtimeHome, "Library", "Application Support");
905
+ if (runtimePlatform === "win32") return resolve(env.LOCALAPPDATA ?? env.APPDATA ?? runtimeHome);
906
+ return resolve(env.XDG_DATA_HOME ?? resolve(runtimeHome, ".local", "share"));
907
+ }
908
+ function isInside(parent, child, runtimePlatform = platform()) {
909
+ const path = relative(normalizeFilesystemIdentity(parent, runtimePlatform), normalizeFilesystemIdentity(child, runtimePlatform));
910
+ return path === "" || !path.startsWith("..") && !isAbsolute(path);
911
+ }
912
+ function parseStoredDate(value) {
913
+ if (!(typeof value === "string" || value instanceof Date)) return null;
914
+ const date = value instanceof Date ? value : new Date(value);
915
+ return Number.isNaN(date.getTime()) ? null : date;
916
+ }
917
+ function requireId(value, label) {
918
+ if (typeof value !== "string" || value.length === 0) throw new Error(`${label} was not persisted with an id.`);
919
+ return value;
920
+ }
921
+ function isMissingFile(error) {
922
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
923
+ }
924
+ function hasMissingFileCause(error) {
925
+ return typeof error === "object" && error !== null && "cause" in error && isMissingFile(error.cause);
926
+ }
927
+ function isFileAlreadyExists(error) {
928
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
929
+ }
930
+ function isDirectoryNotEmpty(error) {
931
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOTEMPTY";
932
+ }
933
+ //#endregion
934
+ export { LocalRuntimeError, initializeLocalApplicationRuntime, resolveLocalRuntimePaths };
935
+
936
+ //# sourceMappingURL=index.js.map