@bitcobblers/wod-wiki-tools 0.37.2137 → 0.37.2140

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 (58) hide show
  1. package/dist/bin/wod.cjs +224 -231
  2. package/dist/bin/wod.cjs.map +1 -1
  3. package/dist/bin/wod.mjs +4 -4
  4. package/dist/{chunk-NATJMTAW.mjs → chunk-IEW74LUO.mjs} +109 -187
  5. package/dist/chunk-IEW74LUO.mjs.map +1 -0
  6. package/dist/{chunk-CYKNTEGY.mjs → chunk-IWT7U3WX.mjs} +8 -3
  7. package/dist/chunk-IWT7U3WX.mjs.map +1 -0
  8. package/dist/{chunk-MA6BBTWC.mjs → chunk-RWNL6APX.mjs} +3 -3
  9. package/dist/{chunk-MA6BBTWC.mjs.map → chunk-RWNL6APX.mjs.map} +1 -1
  10. package/dist/{chunk-GBBJBDLS.mjs → chunk-UNJ6OZVO.mjs} +116 -42
  11. package/dist/chunk-UNJ6OZVO.mjs.map +1 -0
  12. package/dist/{chunk-SQAI6B4P.mjs → chunk-YO256WSO.mjs} +3 -3
  13. package/dist/chunk-YO256WSO.mjs.map +1 -0
  14. package/dist/compiler-E6HYL477.mjs +9 -0
  15. package/dist/{compiler-B77PITYH.mjs.map → compiler-E6HYL477.mjs.map} +1 -1
  16. package/dist/index.cjs +224 -231
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.mjs +5 -5
  19. package/dist/{scaffoldCatalog-LQOUCJ4X.mjs → scaffoldCatalog-TLYSPOQK.mjs} +3 -3
  20. package/dist/{scaffoldCatalog-LQOUCJ4X.mjs.map → scaffoldCatalog-TLYSPOQK.mjs.map} +1 -1
  21. package/dist/{server-JXECWS4A.mjs → server-2DVBA35J.mjs} +4 -4
  22. package/dist/{server-JXECWS4A.mjs.map → server-2DVBA35J.mjs.map} +1 -1
  23. package/dist/web/playground/assets/main-BUcjhK2w.css +2 -0
  24. package/dist/web/playground/assets/main-CT3-Winw.js +194 -0
  25. package/dist/web/playground/assets/{statementBuilderFlow-BL8OKlcb.js → statementBuilderFlow-CtxxN_h0.js} +2 -2
  26. package/dist/web/playground/assets/{vendor-CTANVdPW.js → vendor-DaJxNU_W.js} +19 -19
  27. package/dist/web/playground/assets/{vendor-codemirror-BlXDdJID.js → vendor-codemirror-BtDM22HA.js} +8 -8
  28. package/dist/web/playground/index.html +4 -4
  29. package/dist/web/playground/seed/core/chunks/canvas.3c75c4cb.json +1 -0
  30. package/dist/web/playground/seed/core/chunks/efforts.1422c1a6.json +1 -0
  31. package/dist/web/playground/seed/core/chunks/equipment.c4fb1d64.json +1 -0
  32. package/dist/web/playground/seed/core/chunks/{template.e5e0e82d.json → template.0120276c.json} +1 -1
  33. package/dist/web/playground/seed/core/manifest.json +24 -10
  34. package/dist/web/playground/seed/core/report.html +15 -13
  35. package/dist/web/server/assets/main-BUcjhK2w.css +2 -0
  36. package/dist/web/server/assets/main-C5jPewkG.js +193 -0
  37. package/dist/web/server/assets/{statementBuilderFlow-xqsK_3T8.js → statementBuilderFlow-Df5Scxwh.js} +2 -2
  38. package/dist/web/server/assets/{vendor-CTANVdPW.js → vendor-DaJxNU_W.js} +19 -19
  39. package/dist/web/server/assets/{vendor-codemirror-BlXDdJID.js → vendor-codemirror-BtDM22HA.js} +8 -8
  40. package/dist/web/server/index.html +4 -4
  41. package/dist/web/server/seed/core/chunks/canvas.3c75c4cb.json +1 -0
  42. package/dist/web/server/seed/core/chunks/efforts.1422c1a6.json +1 -0
  43. package/dist/web/server/seed/core/chunks/equipment.c4fb1d64.json +1 -0
  44. package/dist/web/server/seed/core/chunks/{template.e5e0e82d.json → template.0120276c.json} +1 -1
  45. package/dist/web/server/seed/core/manifest.json +24 -10
  46. package/dist/web/server/seed/core/report.html +15 -13
  47. package/package.json +6 -6
  48. package/dist/chunk-CYKNTEGY.mjs.map +0 -1
  49. package/dist/chunk-GBBJBDLS.mjs.map +0 -1
  50. package/dist/chunk-NATJMTAW.mjs.map +0 -1
  51. package/dist/chunk-SQAI6B4P.mjs.map +0 -1
  52. package/dist/compiler-B77PITYH.mjs +0 -9
  53. package/dist/web/playground/assets/main-CFDrblxn.css +0 -2
  54. package/dist/web/playground/assets/main-OGIV1avF.js +0 -188
  55. package/dist/web/playground/seed/core/chunks/canvas.a2e32d8c.json +0 -1
  56. package/dist/web/server/assets/main-BdUrlkaF.js +0 -187
  57. package/dist/web/server/assets/main-CFDrblxn.css +0 -2
  58. package/dist/web/server/seed/core/chunks/canvas.a2e32d8c.json +0 -1
@@ -242,12 +242,17 @@ async function getEffortBySlug(db, slug) {
242
242
  const efforts = await allRows(sql, db, "efforts");
243
243
  return efforts.find((e) => e.slug === slug);
244
244
  }
245
+ async function getEquipmentBySlug(db, slug) {
246
+ const sql = await loadSql();
247
+ const equipment = await allRows(sql, db, "equipment");
248
+ return equipment.find((e) => e.slug === slug);
249
+ }
245
250
  async function listTagsByType(db, type) {
246
251
  const sql = await loadSql();
247
252
  const tags = await allRows(sql, db, "tags");
248
253
  return tags.filter((t) => t.type === type);
249
254
  }
250
255
 
251
- export { CLI_UUID_NAMESPACE, getEffortBySlug, getNoteBundle, getSessionBundle, listTagsByType, loadSql, nodeCrypto, nodeFs, nodePath, openCliDb, randomId, sqliteBlockStore, sqliteEffortStore, sqliteEventStore, sqliteIndexStore, sqliteNoteStore, stableNoteId, uuid5 };
252
- //# sourceMappingURL=chunk-CYKNTEGY.mjs.map
253
- //# sourceMappingURL=chunk-CYKNTEGY.mjs.map
256
+ export { CLI_UUID_NAMESPACE, getEffortBySlug, getEquipmentBySlug, getNoteBundle, getSessionBundle, listTagsByType, loadSql, nodeCrypto, nodeFs, nodePath, openCliDb, randomId, sqliteBlockStore, sqliteEffortStore, sqliteEventStore, sqliteIndexStore, sqliteNoteStore, stableNoteId, uuid5 };
257
+ //# sourceMappingURL=chunk-IWT7U3WX.mjs.map
258
+ //# sourceMappingURL=chunk-IWT7U3WX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../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AsB,eAAA,CAAgB,IAAc,IAAA,EAA4D;AAC9G,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,EAAQ;AAC1B,EAAA,MAAM,OAAA,GAAW,MAAM,OAAA,CAAQ,GAAA,EAAK,IAAI,SAAS,CAAA;AACjD,EAAA,OAAO,QAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,IAAI,CAAA;AAC5C;AAGA,eAAsB,kBAAA,CAAmB,IAAc,IAAA,EAA4D;AACjH,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,EAAQ;AAC1B,EAAA,MAAM,SAAA,GAAa,MAAM,OAAA,CAAQ,GAAA,EAAK,IAAI,WAAW,CAAA;AACrD,EAAA,OAAO,UAAU,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,IAAI,CAAA;AAC9C;AAGA,eAAsB,cAAA,CAAe,IAAc,IAAA,EAA4E;AAC7H,EAAA,MAAM,GAAA,GAAM,MAAM,OAAA,EAAQ;AAC1B,EAAA,MAAM,IAAA,GAAQ,MAAM,OAAA,CAAQ,GAAA,EAAK,IAAI,MAAM,CAAA;AAC3C,EAAA,OAAO,KAAK,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,SAAS,IAAI,CAAA;AAC3C","file":"chunk-IWT7U3WX.mjs","sourcesContent":["/**\n * Local SQLite seam for the `wod` CLI.\n *\n * Opens a libsql `file:` database, initializes the shared storage schema\n * (KV store tables + domain projections), and adapts the rows into the WQL\n * store interfaces — the same shape the playground builds over IndexedDB.\n *\n * Everything heavy is loaded lazily (`@libsql/client`,\n * `@bitcobblers/wod-wiki-storage/sql`, node `fs`/`crypto`) so browser\n * bundles that import the engine index never pull native drivers; the\n * dynamic specifiers stay external in the CLI bundle.\n */\n\nimport type { EventRecord } from '@bitcobblers/wod-wiki-core';\nimport type { IStorage, KeyDTO, Note, Session } from '@bitcobblers/wod-wiki-storage';\nimport type { RangeDTO, StoreDef } from '@bitcobblers/wod-wiki-storage';\nimport type {\n Database,\n LibsqlClient,\n SqlConnection,\n} from '@bitcobblers/wod-wiki-storage/sql';\nimport type { CliDatabaseConfig } from './config';\nimport type {\n BlockQueryStore,\n EventStore,\n EffortQueryStore,\n NoteQueryStore,\n WqlDomainReadResult,\n} from '@bitcobblers/wod-wiki-wql';\nimport { bundledEfforts } from '@bitcobblers/wod-wiki-lang';\n\n/** Structural CJS require — avoids the deprecated NodeJS namespace type. */\ntype CjsRequire = (id: string) => unknown;\n\n/** Minimal node builtin surfaces the CLI uses (kept out of browser bundles). */\nexport interface PathShim { resolve(...parts: string[]): string; join(...parts: string[]): string; dirname(p: string): string; basename(p: string): string }\nexport interface FsShim {\n mkdirSync(p: string, opts: { recursive: boolean }): void;\n existsSync(p: string): boolean;\n unlinkSync(p: string): void;\n readFileSync(p: string, encoding: string): string;\n writeFileSync(p: string, data: string, encoding: string): void;\n}\nexport interface HashShim { update(data: string): HashShim; digest(): Uint8Array }\nexport interface CryptoShim {\n createHash(algorithm: string): HashShim;\n randomUUID(): string;\n}\nexport const nodePath = (): PathShim => nodeRequire()('node:path') as PathShim;\nexport const nodeFs = (): FsShim => nodeRequire()('node:fs') as FsShim;\nexport const nodeCrypto = (): CryptoShim => nodeRequire()('node:crypto') as CryptoShim;\n\n/** Lazy CJS require — keeps node builtins out of browser bundles. */\nfunction nodeRequire(): CjsRequire {\n const g = globalThis as { process?: { versions?: Record<string, string> }; Bun?: unknown; require?: CjsRequire };\n if (typeof g.process?.versions?.node === 'undefined' && typeof g.Bun === 'undefined') {\n throw new Error('SQLite operations are only supported in Node / Bun environments');\n }\n const req = g.require ?? (typeof require === 'function' ? require : undefined);\n if (!req) throw new Error('SQLite operations require a CJS require shim (missing tsup banner?)');\n return req;\n}\n\n/** The storage/sql surface the CLI uses — structural mirror so the lazy import types check. */\nexport interface SqlApi {\n libsqlDatabase(client: LibsqlClient): Database;\n SqlStorage: new (db: Database) => IStorage;\n initializeStore(db: Database): Promise<void>;\n initializeDomain(db: Database): Promise<void>;\n verifyReadiness(db: Database): Promise<void>;\n storeDefinition(name: string): StoreDef;\n listRows(conn: SqlConnection, def: StoreDef, range?: RangeDTO, count?: number, indexName?: string): Promise<unknown[]>;\n getRow(conn: SqlConnection, def: StoreDef, key: KeyDTO): Promise<unknown | undefined>;\n getRows(conn: SqlConnection, def: StoreDef, keys: KeyDTO[]): Promise<(unknown | undefined)[]>;\n putRow(conn: SqlConnection, def: StoreDef, value: unknown): Promise<unknown>;\n deleteRows(conn: SqlConnection, def: StoreDef, keyOrRange: unknown): Promise<void>;\n refreshDomain(conn: SqlConnection, ops: unknown[]): Promise<unknown>;\n handleDomainQuery(db: Database, body: unknown): Promise<unknown>;\n}\n\nlet sqlModulePromise: Promise<SqlApi> | undefined;\n\n/** Lazily import the storage SQL subpath (kept external in the CLI bundle). */\nexport function loadSql(): Promise<SqlApi> {\n sqlModulePromise ??= import(/* @vite-ignore */ '@bitcobblers/wod-wiki-storage/sql') as Promise<SqlApi>;\n return sqlModulePromise;\n}\n\nexport interface CliDb {\n db: Database;\n storage: IStorage;\n /** Absolute path of the underlying .sqlite file — or the sanitized display\n * label (URL without credentials) for remote backends. */\n path: string;\n close(): Promise<void>;\n}\n\n/**\n * Resolve the effective database path: explicit flag wins, then\n * WOD_WIKI_DB, then ./wodwiki.db in the current working directory.\n */\nexport function resolveDbPath(dbPath?: string): string {\n const chosen = dbPath ?? process.env.WOD_WIKI_DB ?? './wodwiki.db';\n return nodePath().resolve(process.cwd(), chosen);\n}\n\n/**\n * Open the CLI database: a legacy local sqlite path (internal callers,\n * created/initialized as before) or a resolved backend config from ./config.\n *\n * opts.initialize (default true): run the schema + projection\n * initialization. false → verify the schema/projection guards only: a\n * missing local sqlite file is NOT created and yields an actionable\n * `wod init` error; remote targets are only probed, never created.\n *\n * opts.create (explicit init requests only, postgres): when the configured\n * PostgreSQL database is missing, openDatabase creates it through the admin\n * \"postgres\" database before initializing. Turso has no management API —\n * its hosted target must already exist.\n */\nexport async function openCliDb(\n target?: string | CliDatabaseConfig,\n opts?: { initialize?: boolean; create?: boolean },\n): Promise<CliDb> {\n if (target === undefined || typeof target === 'string') {\n return openSqliteDb(resolveDbPath(target), opts);\n }\n switch (target.kind) {\n case 'sqlite':\n return openSqliteDb(target.path, opts);\n case 'turso':\n return openRemoteDb(\n { DB_DRIVER: 'turso', DATABASE_URL: target.url, LIBSQL_AUTH_TOKEN: target.authToken },\n target.label,\n opts,\n );\n case 'postgres':\n return openRemoteDb({ DB_DRIVER: 'postgres', DATABASE_URL: target.url }, target.label, opts);\n }\n}\n\nasync function openSqliteDb(resolved: string, opts?: { initialize?: boolean; create?: boolean }): Promise<CliDb> {\n const [{ createClient }, sql] = await Promise.all([\n import(/* @vite-ignore */ '@libsql/client') as Promise<{ createClient: (config: { url: string }) => LibsqlClient }>,\n loadSql(),\n ]);\n const initialize = opts?.initialize ?? true;\n if (!initialize && !nodeFs().existsSync(resolved)) {\n throw new Error(`[wod] no database at ${resolved} — run \\`wod init\\` to create and initialize it`);\n }\n if (initialize) nodeFs().mkdirSync(nodePath().dirname(resolved), { recursive: true });\n const db = sql.libsqlDatabase(createClient({ url: `file:${resolved}` }));\n try {\n if (initialize) {\n await sql.initializeStore(db);\n await sql.initializeDomain(db);\n } else {\n // Guards only — no schema creation on an existing file either.\n await sql.verifyReadiness(db).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`${message} — run \\`wod init\\` to initialize it`, { cause: error });\n });\n }\n return { db, storage: new sql.SqlStorage(db), path: resolved, close: () => db.close() };\n } catch (error) {\n await db.close();\n throw error;\n }\n}\n\n/** Open a postgres/turso/remote-sqlite backend through the extracted server\n * adapter (dynamic on purpose: node-only subpath kept out of browser\n * bundles and external in the CLI bundle). Never falls back locally. */\nasync function openRemoteDb(\n env: Record<string, string | undefined>,\n label: string,\n opts?: { initialize?: boolean; create?: boolean },\n): Promise<CliDb> {\n const [{ openDatabase }, sql] = await Promise.all([\n import(/* @vite-ignore */ '@bitcobblers/wod-wiki-storage/sql/node') as Promise<{\n openDatabase: (env?: Record<string, string | undefined>, opts?: { create?: boolean }) => Promise<Database>;\n }>,\n loadSql(),\n ]);\n let db: Database | undefined;\n try {\n db = await openDatabase(env, { create: opts?.create });\n if (opts?.initialize === false) {\n await sql.verifyReadiness(db);\n } else {\n await sql.initializeStore(db);\n await sql.initializeDomain(db);\n }\n } catch (error) {\n await db?.close().catch(() => {});\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n `[wod] ${label}: ${message}${opts?.initialize === false ? ' — run `wod init` to initialize it' : ''}`,\n { cause: error },\n );\n }\n return { db, storage: new sql.SqlStorage(db), path: label, close: () => db.close() };\n}\n\n// ---------------------------------------------------------------------------\n// Identity helpers\n// ---------------------------------------------------------------------------\n\n/** RFC-4122 byte munging + formatting over a 16-byte digest slice. */\nexport function formatV5Digest(digest: Uint8Array): string {\n const bytes = digest.slice(0, 16);\n bytes[6] = (bytes[6] & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC-4122 variant\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0'));\n return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`;\n}\n\n/** RFC-4122 v5 (SHA-1) name-based UUID — deterministic seed/note identity. */\nexport function uuid5(namespace: string, name: string): string {\n return formatV5Digest(nodeCrypto().createHash('sha1').update(namespace).update(name).digest());\n}\n\n/** Local namespace for wod-CLI derived identities (not shared with seed ids). */\nexport const CLI_UUID_NAMESPACE = 'c0ffee00-8b1a-4e2c-9d3f-5a6b7c8d9e0f';\n\n/**\n * Stable note identity for a parsed/run source: the same file always maps\n * to the same note, so re-parsing updates instead of duplicating. Stdin\n * sources content-address (no stable path exists).\n */\nexport function stableNoteId(sourceLabel: string, content: string): string {\n if (sourceLabel && sourceLabel !== '-') {\n return uuid5(CLI_UUID_NAMESPACE, `wod-cli:${nodePath().resolve(process.cwd(), sourceLabel)}`);\n }\n return uuid5(CLI_UUID_NAMESPACE, `wod-cli:stdin:${content.length}:${content.slice(0, 256)}`);\n}\n\nexport function randomId(): string {\n return nodeCrypto().randomUUID();\n}\n\n// ---------------------------------------------------------------------------\n// WQL store adapters over the sqlite rows\n// ---------------------------------------------------------------------------\n\nasync function allRows(sql: SqlApi, db: Database, store: string): Promise<unknown[]> {\n return sql.listRows(db, sql.storeDefinition(store));\n}\n\nasync function rowsByIndex(sql: SqlApi, db: Database, store: string, index: string, only: string): Promise<unknown[]> {\n return sql.listRows(db, sql.storeDefinition(store), { only }, undefined, index);\n}\n\n/** EventStore over the `events` table — whole-table reads, keyed writes. */\nexport function sqliteEventStore(db: Database): EventStore {\n const all = async (): Promise<EventRecord[]> => (await allRows(await loadSql(), db, 'events')) as EventRecord[];\n return {\n getEventsByTimeRange: async (start, end) => (await all()).filter((r) => r.timestamp >= start && r.timestamp <= end),\n getEventsByResult: async (resultId) => (await all()).filter((r) => r.resultId === resultId),\n getEventsForNote: async (noteId) => (await all()).filter((r) => r.noteId === noteId),\n getEventsByContent: async (blockContentId) => (await all()).filter((r) => r.blockContentId === blockContentId),\n scanAll: all,\n appendEvents: async (appended) => {\n const sql = await loadSql();\n await db.transaction(async (tx) => {\n const eventsDef = sql.storeDefinition('events');\n for (const row of appended) await sql.putRow(tx, eventsDef, row);\n });\n },\n finalizeSummaries: async (resultId, finals) => {\n const sql = await loadSql();\n await db.transaction(async (tx) => {\n const eventsDef = sql.storeDefinition('events');\n const existing = ((await sql.listRows(tx, eventsDef)) as EventRecord[]).filter(\n (r) => r.resultId === resultId && r.grain === 'summary' && r.origin !== 'user',\n );\n for (const row of existing) await sql.deleteRows(tx, eventsDef, row.id);\n for (const row of finals) await sql.putRow(tx, eventsDef, row);\n });\n },\n deleteEvents: async (ids) => {\n const sql = await loadSql();\n await db.transaction(async (tx) => {\n const eventsDef = sql.storeDefinition('events');\n for (const id of ids) await sql.deleteRows(tx, eventsDef, id);\n });\n },\n };\n}\n\ninterface StoredTag { id: string; label: string; type?: string }\ninterface StoredNoteTag { id: string; noteId: string; tagId: string }\n\n/** NoteQueryStore over the notes/tags/note_tags rows + domain projection reads. */\nexport function sqliteNoteStore(db: Database): NoteQueryStore {\n return {\n getAllNotes: async () => (await allRows(await loadSql(), db, 'notes')) as never,\n getNotesByIds: async (noteIds) => {\n const sql = await loadSql();\n const rows = await sql.getRows(db, sql.storeDefinition('notes'), [...noteIds]) as Array<Note | undefined>;\n return rows.filter((row): row is Note => row !== undefined);\n },\n getNoteIdsForTag: async (label) => {\n const sql = await loadSql();\n const tags = ((await allRows(sql, db, 'tags')) as StoredTag[]).filter((t) => t.label === label);\n const ids: Record<string, true> = {};\n for (const tag of tags) {\n for (const row of await rowsByIndex(sql, db, 'note_tags', 'by-tag', tag.id)) {\n ids[(row as StoredNoteTag).noteId] = true;\n }\n }\n return new Set(Object.keys(ids));\n },\n getNoteTagLabels: async (noteId) => {\n const sql = await loadSql();\n const tagRows = (await allRows(sql, db, 'tags')) as StoredTag[];\n const labelById: Record<string, string> = {};\n for (const t of tagRows) labelById[t.id] = t.label;\n const links = (await rowsByIndex(sql, db, 'note_tags', 'by-note', noteId)) as StoredNoteTag[];\n return links.map((l) => labelById[l.tagId]).filter((l): l is string => typeof l === 'string');\n },\n queryDomain: async (request) => {\n // WQL's domain wire is a structural mirror of the storage DomainQuery.\n const result = await (await loadSql()).handleDomainQuery(db, request as never);\n return result as WqlDomainReadResult;\n },\n };\n}\n\n/** BlockQueryStore over the block_index rows + domain projection reads. */\nexport function sqliteBlockStore(db: Database): BlockQueryStore {\n return {\n getAllBlocks: async () => (await allRows(await loadSql(), db, 'block_index')) as never,\n queryDomain: async (request) => {\n const result = await (await loadSql()).handleDomainQuery(db, { ...request, plan: 'blocks' } as never);\n return result as WqlDomainReadResult;\n },\n };\n}\n\ninterface Slugged { slug: string }\n\n/**\n * EffortQueryStore: rows the seed wrote into the `efforts` registry win by\n * slug; the lang-bundled registry fills the rest (same fallback the\n * playground's RegistryEffortStore performs).\n */\nexport function sqliteEffortStore(db: Database): EffortQueryStore {\n return {\n getAllEfforts: async () => {\n const stored = (await allRows(await loadSql(), db, 'efforts')) as Slugged[];\n const bySlug: Record<string, unknown> = {};\n for (const effort of stored) bySlug[effort.slug] = effort;\n for (const effort of bundledEfforts as unknown as Slugged[]) {\n bySlug[effort.slug] ??= effort;\n }\n return Object.values(bySlug) as never;\n },\n };\n}\n\n/** Generic by-index reader over a store table — the QueryService seam shape. */\nexport interface IndexStore { getAllFromIndex(index: string, key: string): Promise<unknown[]> }\n\n/** Indexed reads over `block_efforts` / `tags` / `note_tags` rows. */\nexport function sqliteIndexStore(db: Database, store: 'block_efforts' | 'tags' | 'note_tags'): IndexStore {\n return {\n getAllFromIndex: async (index, key) => rowsByIndex(await loadSql(), db, store, index, key),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Download bundles (exchange feedstock)\n// ---------------------------------------------------------------------------\n\nexport interface NoteBundle {\n note: Note | undefined;\n}\n\nexport interface SessionBundle {\n session: Session;\n events: EventRecord[];\n}\n\n/** Fetch the whole authored Note. */\nexport async function getNoteBundle(db: Database, noteId: string): Promise<NoteBundle> {\n const sql = await loadSql();\n const note = await sql.getRow(db, sql.storeDefinition('notes'), noteId) as Note | undefined;\n return { note };\n}\n\n/** Fetch a session + its event/summary rows. */\nexport async function getSessionBundle(db: Database, resultId: string): Promise<SessionBundle | undefined> {\n const sql = await loadSql();\n const session = await sql.getRow(db, sql.storeDefinition('sessions'), resultId) as Session | undefined;\n if (!session) return undefined;\n const events = await sql.listRows(db, sql.storeDefinition('events'), { only: resultId }, undefined, 'by-result-grain') as EventRecord[];\n return { session, events };\n}\n\n/** Fetch one effort registry row by slug. */\nexport async function getEffortBySlug(db: Database, slug: string): Promise<Record<string, unknown> | undefined> {\n const sql = await loadSql();\n const efforts = (await allRows(sql, db, 'efforts')) as Array<{ slug: string } & Record<string, unknown>>;\n return efforts.find((e) => e.slug === slug);\n}\n\n/** Fetch one equipment registry row by slug. */\nexport async function getEquipmentBySlug(db: Database, slug: string): Promise<Record<string, unknown> | undefined> {\n const sql = await loadSql();\n const equipment = (await allRows(sql, db, 'equipment')) as Array<{ slug: string } & Record<string, unknown>>;\n return equipment.find((e) => e.slug === slug);\n}\n\n/** Fetch tag rows of one type (e.g. 'equipment'). */\nexport async function listTagsByType(db: Database, type: string): Promise<Array<{ id: string; label: string; type?: string }>> {\n const sql = await loadSql();\n const tags = (await allRows(sql, db, 'tags')) as Array<{ id: string; label: string; type?: string }>;\n return tags.filter((t) => t.type === type);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module';
2
- import { openCliDb, nodePath, nodeFs } from './chunk-CYKNTEGY.mjs';
2
+ import { openCliDb, nodePath, nodeFs } from './chunk-IWT7U3WX.mjs';
3
3
  import { createHandler } from './chunk-V23POHG2.mjs';
4
4
  import http from 'http';
5
5
  import { Readable } from 'stream';
@@ -161,5 +161,5 @@ async function runCliServer(mode, options, writeOut) {
161
161
  }
162
162
 
163
163
  export { runCliServer };
164
- //# sourceMappingURL=chunk-MA6BBTWC.mjs.map
165
- //# sourceMappingURL=chunk-MA6BBTWC.mjs.map
164
+ //# sourceMappingURL=chunk-RWNL6APX.mjs.map
165
+ //# sourceMappingURL=chunk-RWNL6APX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli/server.ts"],"names":["dist"],"mappings":";;;;;;;;;AA4CA,SAAS,aAAA,GAAmB;AAC1B,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI,MAAA;AACJ,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAW,CAAC,KAAK,GAAA,KAAQ;AAC3C,IAAA,OAAA,GAAU,GAAA;AACV,IAAA,MAAA,GAAS,GAAA;AAAA,EACX,CAAC,CAAA;AACD,EAAA,OAAO,EAAE,OAAA,EAAS,OAAA,EAAS,MAAA,EAAO;AACpC;AAEA,SAAS,eAAA,CACP,O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AAA,CAAG,KAAA,EAAM;AACvB,IAAA,MAAM,CAAA;AAAA,EACR;AAEA,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,MAAM,WAAW,YAA2B;AAC1C,IAAA,IAAI,OAAA,EAAS,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA;AAC3B,IAAA,OAAA,GAAU,IAAA;AACV,IAAA,IAAI;AACF,MAAA,MAAM,OAAO,IAAA,EAAK;AAAA,IACpB,CAAA,SAAE;AACA,MAAA,IAAI,EAAA,EAAI,MAAM,EAAA,CAAG,KAAA,EAAM;AACvB,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF,CAAA;AACA,EAAA,OAAA,CAAQ,EAAA,CAAG,UAAU,MAAM;AAAE,IAAA,KAAK,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAC/C,EAAA,OAAA,CAAQ,EAAA,CAAG,WAAW,MAAM;AAAE,IAAA,KAAK,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAGhD,EAAA,MAAM,IAAI,QAAe,MAAM;AAAA,EAAC,CAAC,CAAA;AACnC","file":"chunk-MA6BBTWC.mjs","sourcesContent":["/**\n * server.ts — `wod server` (alias `serve`) / `wod playground` (Bun-only front\n * door).\n *\n * Serves the packaged engine stack: the shared fetch handler shipped in this\n * package (the same code the Docker image serves) plus the frontend build\n * packaged under the engine's dist/web/ — no repository checkout, no runtime\n * build.\n *\n * server probes the configured database first (never creates schema —\n * that's `wod init`), then serves API + SPA.\n * playground serves the browser-storage SPA build and never opens a database\n * (every /api request answers 404).\n *\n * Retains the event loop until SIGINT/SIGTERM; shutdown drains in-flight\n * requests before closing the database.\n */\n\nimport http from 'node:http';\nimport { Readable } from 'node:stream';\nimport { openCliDb, nodeFs, nodePath } from './db';\nimport type { CliDatabaseConfig } from './config';\nimport type { CliDb } from './db';\nimport { createHandler } from '../server/app';\ntype WriteOut = (text: string) => void;\n\nexport type CliServerMode = 'server' | 'playground';\n\nexport interface CliServerOptions {\n /** Resolved database configuration. REQUIRED for 'server'; ignored — never\n * opened or validated — for 'playground'. */\n database?: CliDatabaseConfig;\n host?: string;\n port?: string;\n /** Explicit dist directory (flag or PLAYGROUND_DIST); must already exist. */\n dist?: string;\n /** Merged CLI environment (process env + .env). */\n env: Record<string, string | undefined>;\n}\n\ninterface HttpServerLike {\n stop(): Promise<void>;\n}\n\nfunction withResolvers<T>() {\n let resolve!: (value: T | PromiseLike<T>) => void;\n let reject!: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nfunction startHttpServer(\n handler: (request: Request) => Promise<Response>,\n host: string,\n port: number,\n): Promise<HttpServerLike> {\n const b = (globalThis as { Bun?: { serve(opts: { port: number; hostname: string; fetch: (req: Request) => Promise<Response> }): { stop(): Promise<void> } } }).Bun;\n if (b?.serve) {\n const s = b.serve({ port, hostname: host, fetch: handler });\n return Promise.resolve({ stop: () => s.stop() });\n }\n\n // ponytail: node:http adapter streams Web Request/Response in pure Node (v18+) without express/fastify dependencies\n const { promise, resolve, reject } = withResolvers<HttpServerLike>();\n const server = http.createServer(async (req, res) => {\n try {\n const url = new URL(req.url || '/', `http://${req.headers.host || `${host}:${port}`}`);\n const hasBody = req.method !== 'GET' && req.method !== 'HEAD';\n const webReq = new Request(url, {\n method: req.method,\n headers: req.headers as Record<string, string>,\n body: hasBody ? (Readable.toWeb(req) as unknown as BodyInit) : null,\n ...(hasBody ? { duplex: 'half' } : {}),\n } as RequestInit);\n const webRes = await handler(webReq);\n res.writeHead(webRes.status, Object.fromEntries(webRes.headers.entries()));\n if (webRes.body) {\n Readable.fromWeb(webRes.body as any).pipe(res);\n } else {\n res.end();\n }\n } catch {\n res.statusCode = 500;\n res.end('internal server error');\n }\n });\n\n server.once('error', reject);\n server.listen(port, host, () => {\n resolve({\n stop: () => {\n const close = withResolvers<void>();\n server.close(() => close.resolve());\n return close.promise;\n },\n });\n });\n return promise;\n}\n\n/**\n * This module's directory, robust across shipped layouts: ESM via\n * import.meta.url (works under node and Bun; esbuild shims it in CJS too) and\n * Bun's import.meta.dir. ESM code splitting may relocate this module to a\n * chunk at dist/ root, so never assume dist/cli.\n */\nfunction moduleDir(): string {\n const p = nodePath();\n const meta: { dir?: unknown; url?: unknown } = import.meta; // Bun adds `dir`; the TS lib knows neither.\n if (typeof meta.dir === 'string') return p.resolve(meta.dir);\n if (typeof meta.url === 'string' && meta.url.startsWith('file:')) {\n return p.resolve(p.dirname(decodeURIComponent(new URL('.', meta.url).pathname)));\n }\n throw new Error('wod server/playground: cannot determine the installed engine module directory');\n}\n\n/**\n * The installed engine package root: nearest enclosing package.json belonging\n * to this package, walking up from the executing module (dist/cli, a split\n * chunk at dist/ root, dist/bin, or src/cli in a checkout).\n */\nfunction engineRoot(): string {\n const p = nodePath();\n const fs = nodeFs();\n for (let dir = moduleDir(); ; dir = p.dirname(dir)) {\n try {\n if (JSON.parse(fs.readFileSync(p.resolve(dir, 'package.json'), 'utf8')).name === '@bitcobblers/wod-wiki-tools') return dir;\n } catch { /* no manifest here — keep walking */ }\n const parent = p.dirname(dir);\n if (parent === dir) break;\n }\n throw new Error('wod server/playground: cannot locate the installed @bitcobblers/wod-wiki-tools package');\n}\n\n/**\n * Resolve the frontend dist directory. The packaged default lives inside the\n * installed engine module (dist/web/server or dist/web/playground); an\n * explicit --dist/PLAYGROUND_DIST is cwd-relative and must already contain a\n * built SPA (index.html). Nothing is built at runtime.\n */\nfunction resolveDist(mode: CliServerMode, options: CliServerOptions): string {\n const p = nodePath();\n const explicit = options.dist?.trim() || options.env.PLAYGROUND_DIST?.trim() || undefined;\n if (explicit) {\n const dist = p.resolve(explicit); // cwd-relative override\n if (!nodeFs().existsSync(p.resolve(dist, 'index.html'))) {\n throw new Error(\n `wod ${mode}: no built frontend (index.html) at ${dist} — --dist/PLAYGROUND_DIST must `\n + 'point at an already-built directory (the CLI never builds frontends at runtime)',\n );\n }\n return dist;\n }\n const dist = p.resolve(engineRoot(), 'dist', 'web', mode === 'playground' ? 'playground' : 'server');\n if (!nodeFs().existsSync(p.resolve(dist, 'index.html'))) {\n throw new Error(\n `wod ${mode}: packaged frontend missing — expected ${dist}/index.html. `\n + 'Reinstall @bitcobblers/wod-wiki-tools (bun add @bitcobblers/wod-wiki-tools), '\n + 'or rebuild the release assets from a checkout (bun run build:cli) and reinstall the package.',\n );\n }\n return dist;\n}\n\n/** Validate bind address first: flag > HOST/PORT env > loopback:3000. */\nfunction resolveBind(mode: CliServerMode, options: CliServerOptions): { host: string; port: number } {\n const host = options.host?.trim() || options.env.HOST?.trim() || '127.0.0.1';\n const rawPort = options.port?.trim() || options.env.PORT?.trim() || '3000';\n const port = Number(rawPort);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`wod ${mode}: invalid port ${JSON.stringify(rawPort)} (need integer 1..65535)`);\n }\n return { host, port };\n}\n\n/**\n * Start the shared server for `wod server` / `wod playground`. Throws on any\n * startup failure; on success it never returns until SIGINT/SIGTERM (drain,\n * close database, exit 0).\n */\nexport async function runCliServer(\n mode: CliServerMode,\n options: CliServerOptions,\n writeOut: WriteOut,\n): Promise<void> {\n const { host, port } = resolveBind(mode, options); // Validate bind before opening anything.\n\n // Server probes the database BEFORE binding a socket: a missing/uninitialized\n // database refuses with `wod init` guidance.\n let db: CliDb | undefined;\n let dbLabel = 'no database';\n if (mode === 'server') {\n const database = options.database; // hoisted so the guard's narrowing sticks\n if (!database) {\n throw new Error('wod server: no database configuration resolved — this is a runner bug (expected resolveDatabaseConfig output)');\n }\n try {\n db = await openCliDb(database, { initialize: false });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`wod server: database not ready — run \\`wod init\\` first. ${message}`, { cause: e });\n }\n dbLabel = db.path;\n }\n\n let server: HttpServerLike;\n try {\n const dist = resolveDist(mode, options);\n // Bundled server handler\n const handler = createHandler(db?.db ?? null, { playgroundDist: dist });\n // Playground: no database exists to close — createHandler(null) answers\n server = await startHttpServer(handler, host, port);\n if (mode === 'server') {\n writeOut(`wod server: http://${host}:${port} — ${dbLabel} · dist ${dist}`);\n } else {\n writeOut(`wod playground: http://${host}:${port} — in-browser storage (no database) · dist ${dist}`);\n }\n } catch (e) {\n if (db) await db.close(); // never leak the probe connection when startup fails\n throw e;\n }\n\n let closing = false;\n const shutdown = async (): Promise<void> => {\n if (closing) process.exit(0); // second signal forces the exit\n closing = true;\n try {\n await server.stop();\n } finally {\n if (db) await db.close();\n process.exit(0);\n }\n };\n process.on('SIGINT', () => { void shutdown(); });\n process.on('SIGTERM', () => { void shutdown(); });\n\n // Park until a signal handler exits the process.\n await new Promise<never>(() => {});\n}\n"]}
1
+ {"version":3,"sources":["../src/cli/server.ts"],"names":["dist"],"mappings":";;;;;;;;;AA4CA,SAAS,aAAA,GAAmB;AAC1B,EAAA,IAAI,OAAA;AACJ,EAAA,IAAI,MAAA;AACJ,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAW,CAAC,KAAK,GAAA,KAAQ;AAC3C,IAAA,OAAA,GAAU,GAAA;AACV,IAAA,MAAA,GAAS,GAAA;AAAA,EACX,CAAC,CAAA;AACD,EAAA,OAAO,EAAE,OAAA,EAAS,OAAA,EAAS,MAAA,EAAO;AACpC;AAEA,SAAS,eAAA,CACP,OAAA,EACA,IAAA,EACA,IAAA,EACyB;AACzB,EAAA,MAAM,IAAK,UAAA,CAAoJ,GAAA;AAC/J,EAAA,IAAI,GAAG,KAAA,EAAO;AACZ,IAAA,MAAM,CAAA,GAAI,EAAE,KAAA,CAAM,EAAE,MAAM,QAAA,EAAU,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,CAAA;AAC1D,IAAA,OAAO,OAAA,CAAQ,QAAQ,EAAE,IAAA,EAAM,MAAM,CAAA,CAAE,IAAA,IAAQ,CAAA;AAAA,EACjD;AAGA,EAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,MAAA,KAAW,aAAA,EAA8B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IAChB;AAAA,EACF,CAAA;AACA,EAAA,OAAA,CAAQ,EAAA,CAAG,UAAU,MAAM;AAAE,IAAA,KAAK,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAC/C,EAAA,OAAA,CAAQ,EAAA,CAAG,WAAW,MAAM;AAAE,IAAA,KAAK,QAAA,EAAS;AAAA,EAAG,CAAC,CAAA;AAGhD,EAAA,MAAM,IAAI,QAAe,MAAM;AAAA,EAAC,CAAC,CAAA;AACnC","file":"chunk-RWNL6APX.mjs","sourcesContent":["/**\n * server.ts — `wod server` (alias `serve`) / `wod playground` (Bun-only front\n * door).\n *\n * Serves the packaged engine stack: the shared fetch handler shipped in this\n * package (the same code the Docker image serves) plus the frontend build\n * packaged under the engine's dist/web/ — no repository checkout, no runtime\n * build.\n *\n * server probes the configured database first (never creates schema —\n * that's `wod init`), then serves API + SPA.\n * playground serves the browser-storage SPA build and never opens a database\n * (every /api request answers 404).\n *\n * Retains the event loop until SIGINT/SIGTERM; shutdown drains in-flight\n * requests before closing the database.\n */\n\nimport http from 'node:http';\nimport { Readable } from 'node:stream';\nimport { openCliDb, nodeFs, nodePath } from './db';\nimport type { CliDatabaseConfig } from './config';\nimport type { CliDb } from './db';\nimport { createHandler } from '../server/app';\ntype WriteOut = (text: string) => void;\n\nexport type CliServerMode = 'server' | 'playground';\n\nexport interface CliServerOptions {\n /** Resolved database configuration. REQUIRED for 'server'; ignored — never\n * opened or validated — for 'playground'. */\n database?: CliDatabaseConfig;\n host?: string;\n port?: string;\n /** Explicit dist directory (flag or PLAYGROUND_DIST); must already exist. */\n dist?: string;\n /** Merged CLI environment (process env + .env). */\n env: Record<string, string | undefined>;\n}\n\ninterface HttpServerLike {\n stop(): Promise<void>;\n}\n\nfunction withResolvers<T>() {\n let resolve!: (value: T | PromiseLike<T>) => void;\n let reject!: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\nfunction startHttpServer(\n handler: (request: Request) => Promise<Response>,\n host: string,\n port: number,\n): Promise<HttpServerLike> {\n const b = (globalThis as { Bun?: { serve(opts: { port: number; hostname: string; fetch: (req: Request) => Promise<Response> }): { stop(): Promise<void> } } }).Bun;\n if (b?.serve) {\n const s = b.serve({ port, hostname: host, fetch: handler });\n return Promise.resolve({ stop: () => s.stop() });\n }\n\n // ponytail: node:http adapter streams Web Request/Response in pure Node (v18+) without express/fastify dependencies\n const { promise, resolve, reject } = withResolvers<HttpServerLike>();\n const server = http.createServer(async (req, res) => {\n try {\n const url = new URL(req.url || '/', `http://${req.headers.host || `${host}:${port}`}`);\n const hasBody = req.method !== 'GET' && req.method !== 'HEAD';\n const webReq = new Request(url, {\n method: req.method,\n headers: req.headers as Record<string, string>,\n body: hasBody ? (Readable.toWeb(req) as unknown as BodyInit) : null,\n ...(hasBody ? { duplex: 'half' } : {}),\n } as RequestInit);\n const webRes = await handler(webReq);\n res.writeHead(webRes.status, Object.fromEntries(webRes.headers.entries()));\n if (webRes.body) {\n Readable.fromWeb(webRes.body as any).pipe(res);\n } else {\n res.end();\n }\n } catch {\n res.statusCode = 500;\n res.end('internal server error');\n }\n });\n\n server.once('error', reject);\n server.listen(port, host, () => {\n resolve({\n stop: () => {\n const close = withResolvers<void>();\n server.close(() => close.resolve());\n return close.promise;\n },\n });\n });\n return promise;\n}\n\n/**\n * This module's directory, robust across shipped layouts: ESM via\n * import.meta.url (works under node and Bun; esbuild shims it in CJS too) and\n * Bun's import.meta.dir. ESM code splitting may relocate this module to a\n * chunk at dist/ root, so never assume dist/cli.\n */\nfunction moduleDir(): string {\n const p = nodePath();\n const meta: { dir?: unknown; url?: unknown } = import.meta; // Bun adds `dir`; the TS lib knows neither.\n if (typeof meta.dir === 'string') return p.resolve(meta.dir);\n if (typeof meta.url === 'string' && meta.url.startsWith('file:')) {\n return p.resolve(p.dirname(decodeURIComponent(new URL('.', meta.url).pathname)));\n }\n throw new Error('wod server/playground: cannot determine the installed engine module directory');\n}\n\n/**\n * The installed engine package root: nearest enclosing package.json belonging\n * to this package, walking up from the executing module (dist/cli, a split\n * chunk at dist/ root, dist/bin, or src/cli in a checkout).\n */\nfunction engineRoot(): string {\n const p = nodePath();\n const fs = nodeFs();\n for (let dir = moduleDir(); ; dir = p.dirname(dir)) {\n try {\n if (JSON.parse(fs.readFileSync(p.resolve(dir, 'package.json'), 'utf8')).name === '@bitcobblers/wod-wiki-tools') return dir;\n } catch { /* no manifest here — keep walking */ }\n const parent = p.dirname(dir);\n if (parent === dir) break;\n }\n throw new Error('wod server/playground: cannot locate the installed @bitcobblers/wod-wiki-tools package');\n}\n\n/**\n * Resolve the frontend dist directory. The packaged default lives inside the\n * installed engine module (dist/web/server or dist/web/playground); an\n * explicit --dist/PLAYGROUND_DIST is cwd-relative and must already contain a\n * built SPA (index.html). Nothing is built at runtime.\n */\nfunction resolveDist(mode: CliServerMode, options: CliServerOptions): string {\n const p = nodePath();\n const explicit = options.dist?.trim() || options.env.PLAYGROUND_DIST?.trim() || undefined;\n if (explicit) {\n const dist = p.resolve(explicit); // cwd-relative override\n if (!nodeFs().existsSync(p.resolve(dist, 'index.html'))) {\n throw new Error(\n `wod ${mode}: no built frontend (index.html) at ${dist} — --dist/PLAYGROUND_DIST must `\n + 'point at an already-built directory (the CLI never builds frontends at runtime)',\n );\n }\n return dist;\n }\n const dist = p.resolve(engineRoot(), 'dist', 'web', mode === 'playground' ? 'playground' : 'server');\n if (!nodeFs().existsSync(p.resolve(dist, 'index.html'))) {\n throw new Error(\n `wod ${mode}: packaged frontend missing — expected ${dist}/index.html. `\n + 'Reinstall @bitcobblers/wod-wiki-tools (bun add @bitcobblers/wod-wiki-tools), '\n + 'or rebuild the release assets from a checkout (bun run build:cli) and reinstall the package.',\n );\n }\n return dist;\n}\n\n/** Validate bind address first: flag > HOST/PORT env > loopback:3000. */\nfunction resolveBind(mode: CliServerMode, options: CliServerOptions): { host: string; port: number } {\n const host = options.host?.trim() || options.env.HOST?.trim() || '127.0.0.1';\n const rawPort = options.port?.trim() || options.env.PORT?.trim() || '3000';\n const port = Number(rawPort);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(`wod ${mode}: invalid port ${JSON.stringify(rawPort)} (need integer 1..65535)`);\n }\n return { host, port };\n}\n\n/**\n * Start the shared server for `wod server` / `wod playground`. Throws on any\n * startup failure; on success it never returns until SIGINT/SIGTERM (drain,\n * close database, exit 0).\n */\nexport async function runCliServer(\n mode: CliServerMode,\n options: CliServerOptions,\n writeOut: WriteOut,\n): Promise<void> {\n const { host, port } = resolveBind(mode, options); // Validate bind before opening anything.\n\n // Server probes the database BEFORE binding a socket: a missing/uninitialized\n // database refuses with `wod init` guidance.\n let db: CliDb | undefined;\n let dbLabel = 'no database';\n if (mode === 'server') {\n const database = options.database; // hoisted so the guard's narrowing sticks\n if (!database) {\n throw new Error('wod server: no database configuration resolved — this is a runner bug (expected resolveDatabaseConfig output)');\n }\n try {\n db = await openCliDb(database, { initialize: false });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`wod server: database not ready — run \\`wod init\\` first. ${message}`, { cause: e });\n }\n dbLabel = db.path;\n }\n\n let server: HttpServerLike;\n try {\n const dist = resolveDist(mode, options);\n // Bundled server handler\n const handler = createHandler(db?.db ?? null, { playgroundDist: dist });\n // Playground: no database exists to close — createHandler(null) answers\n server = await startHttpServer(handler, host, port);\n if (mode === 'server') {\n writeOut(`wod server: http://${host}:${port} — ${dbLabel} · dist ${dist}`);\n } else {\n writeOut(`wod playground: http://${host}:${port} — in-browser storage (no database) · dist ${dist}`);\n }\n } catch (e) {\n if (db) await db.close(); // never leak the probe connection when startup fails\n throw e;\n }\n\n let closing = false;\n const shutdown = async (): Promise<void> => {\n if (closing) process.exit(0); // second signal forces the exit\n closing = true;\n try {\n await server.stop();\n } finally {\n if (db) await db.close();\n process.exit(0);\n }\n };\n process.on('SIGINT', () => { void shutdown(); });\n process.on('SIGTERM', () => { void shutdown(); });\n\n // Park until a signal handler exits the process.\n await new Promise<never>(() => {});\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  import { createRequire } from 'module';
2
- import { compileSeedRow, SEED_SCHEMA, writeBuildReport } from './chunk-NATJMTAW.mjs';
3
- import { VERSION } from './chunk-SQAI6B4P.mjs';
4
- import { openCliDb, nodeFs, sqliteIndexStore, sqliteEffortStore, sqliteBlockStore, sqliteNoteStore, sqliteEventStore, getNoteBundle, getSessionBundle, getEffortBySlug, listTagsByType, nodePath, loadSql, uuid5, CLI_UUID_NAMESPACE, nodeCrypto, stableNoteId, randomId } from './chunk-CYKNTEGY.mjs';
2
+ import { compileSeedRow, SEED_SCHEMA, writeBuildReport } from './chunk-IEW74LUO.mjs';
3
+ import { VERSION } from './chunk-YO256WSO.mjs';
4
+ import { openCliDb, nodeFs, sqliteIndexStore, sqliteEffortStore, sqliteBlockStore, sqliteNoteStore, sqliteEventStore, getNoteBundle, getSessionBundle, getEffortBySlug, getEquipmentBySlug, listTagsByType, nodePath, loadSql, uuid5, CLI_UUID_NAMESPACE, nodeCrypto, stableNoteId, randomId } from './chunk-IWT7U3WX.mjs';
5
5
  import { __require } from './chunk-6L5ZDZJ7.mjs';
6
- import { createParser, frozenNow, createCompiler, createMockClock, RuntimeStack, EventBus, ScriptRuntime, createAnalyticsEngineForBlock, StartSessionAction, NextEvent, toStoredOutputStatement, bundledEfforts, parseScript } from '@bitcobblers/wod-wiki-lang';
7
- import { buildStatementTree, createIRFile, registerLanguagePack, extractNoteIdentity, extractTypedTags, composeNoteMarkdown, sessionToCsv, effortToMarkdown, equipmentToCsv, markdownToEffort, csvToEquipmentLabels, csvToSessionRows, isIRFile, inMemoryEventStore, readFrontmatterMeta, assertSeedManifest, seedMetaKey, SEED_SCHEMA as SEED_SCHEMA$1, emptySeedMeta, CANVAS_CHUNK_ID, assertSeedRows, seedNoteId, applySeedChunk } from '@bitcobblers/wod-wiki-engine';
6
+ import { createParser, frozenNow, createCompiler, createMockClock, RuntimeStack, EventBus, ScriptRuntime, createAnalyticsEngineForBlock, StartSessionAction, NextEvent, toStoredOutputStatement, bundledEfforts, parseEffortFile, parseEquipmentFile, createReferenceIndex, parseScript, extractStatementRefs } from '@bitcobblers/wod-wiki-lang';
7
+ import { buildStatementTree, createIRFile, registerLanguagePack, extractNoteIdentity, extractTypedTags, composeNoteMarkdown, sessionToCsv, effortToMarkdown, equipmentToMarkdown, equipmentToCsv, csvToEquipmentLabels, csvToSessionRows, isIRFile, inMemoryEventStore, readFrontmatterMeta, assertSeedManifest, seedMetaKey, SEED_SCHEMA as SEED_SCHEMA$1, emptySeedMeta, CANVAS_CHUNK_ID, assertSeedRows, seedNoteId, applySeedChunk } from '@bitcobblers/wod-wiki-engine';
8
8
  import { toEventRows, toSummaryEventRows, parseQuery, QueryService, isPipelineQuery, isFindQuery, catalogOfItem } from '@bitcobblers/wod-wiki-wql';
9
- import { validateNoteBlocks, parseDocumentSections, blockContentId, reconcileNoteBlocks, KNOWN_SECTION_WIDGETS } from '@bitcobblers/wod-wiki-core';
9
+ import { validateNoteBlocks, parseDocumentSections, blockContentId, reconcileNoteBlocks, KNOWN_SECTION_WIDGETS, MetricType } from '@bitcobblers/wod-wiki-core';
10
10
  import { rowsEqual } from '@bitcobblers/wod-wiki-storage';
11
11
 
12
12
  if (typeof globalThis.require === 'undefined') {
@@ -924,23 +924,7 @@ ${escapeCsvField(data.parsed.metric)},${data.scalar},${escapeCsvField(data.unit
924
924
  return lines.join("\n");
925
925
  }
926
926
  var registeredWidgets = KNOWN_SECTION_WIDGETS;
927
- var saveStores = ["notes", "block_revisions", "block_index", "block_efforts", "tags", "note_tags", "sessions"];
928
- function extractEffortSlugs(statements) {
929
- const slugs = /* @__PURE__ */ new Set();
930
- for (const statement of statements) {
931
- if (statement.exerciseId) {
932
- slugs.add(statement.exerciseId);
933
- } else {
934
- const effortMetric = statement.metrics?.getMetric?.("effort");
935
- const effort = effortMetric && "effort" in effortMetric ? effortMetric.effort : void 0;
936
- if (typeof effort === "string") {
937
- const slug = effort.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
938
- if (slug) slugs.add(slug);
939
- }
940
- }
941
- }
942
- return [...slugs];
943
- }
927
+ var saveStores = ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "efforts", "equipment", "tags", "note_tags", "sessions"];
944
928
  function titleFromLabel(sourceLabel) {
945
929
  if (!sourceLabel || sourceLabel === "-") return "stdin";
946
930
  const stem = sourceLabel.split("/").pop() ?? sourceLabel;
@@ -1012,9 +996,19 @@ async function saveSource(db, options, startTime) {
1012
996
  };
1013
997
  const priorRows = await tx.readonly("block_index").getAllFromIndex("by-note", noteId);
1014
998
  const priorEfforts = await tx.readonly("block_efforts").getAllFromIndex("by-note", noteId);
999
+ const priorEquipment = await tx.readonly("block_equipment").getAllFromIndex("by-note", noteId);
1000
+ const storedEfforts = await tx.readonly("efforts").getAll();
1001
+ const effortsBySlug = /* @__PURE__ */ new Map();
1002
+ for (const effort of bundledEfforts) effortsBySlug.set(effort.slug, effort);
1003
+ for (const effort of storedEfforts) effortsBySlug.set(effort.slug, effort);
1004
+ const referenceIndex = createReferenceIndex({
1005
+ efforts: [...effortsBySlug.values()],
1006
+ equipment: await tx.readonly("equipment").getAll()
1007
+ });
1015
1008
  const priorById = new Map(priorRows.map((row) => [row.id, row]));
1016
1009
  const nextRows = [];
1017
1010
  const nextEfforts = [];
1011
+ const nextEquipment = [];
1018
1012
  for (const [position, block] of Object.values(blocks).sort((a, b) => a.from - b.from).entries()) {
1019
1013
  const id = `${noteId}:${block.id}`;
1020
1014
  const prior = priorById.get(id);
@@ -1040,7 +1034,20 @@ async function saveSource(db, options, startTime) {
1040
1034
  ...note.sourceId ? { sourceId: note.sourceId } : {}
1041
1035
  });
1042
1036
  if (block.kind === "wod") {
1043
- for (const effortSlug of extractEffortSlugs(parseScript(body, { sport: block.sport, dialect: block.dialect }).statements)) {
1037
+ const statements = parseScript(body, { sport: block.sport, dialect: block.dialect, references: referenceIndex }).statements;
1038
+ const refs = extractStatementRefs(statements);
1039
+ const effortSlugs = new Set(refs.efforts);
1040
+ if (effortSlugs.size === 0) {
1041
+ for (const s of statements) {
1042
+ const m = s.metrics?.getMetric?.(MetricType.Effort);
1043
+ const val = typeof m?.value === "string" ? m.value : m && "effort" in m ? String(m.effort) : "";
1044
+ const slug = val.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1045
+ if (slug && !["rest", "amrap", "emom", "tabata", "for-time"].includes(slug)) {
1046
+ effortSlugs.add(slug);
1047
+ }
1048
+ }
1049
+ }
1050
+ for (const effortSlug of effortSlugs) {
1044
1051
  const effortId = `${noteId}:${block.id}:${effortSlug}`;
1045
1052
  const previous = priorEfforts.find((row) => row.id === effortId);
1046
1053
  nextEfforts.push({
@@ -1053,12 +1060,26 @@ async function saveSource(db, options, startTime) {
1053
1060
  createdAt: previous?.createdAt ?? now
1054
1061
  });
1055
1062
  }
1063
+ for (const equipmentSlug of refs.equipment) {
1064
+ const equipmentId = `${noteId}:${block.id}:${equipmentSlug}`;
1065
+ const previous = priorEquipment.find((row) => row.id === equipmentId);
1066
+ nextEquipment.push({
1067
+ ...previous,
1068
+ id: equipmentId,
1069
+ noteId,
1070
+ blockId: block.id,
1071
+ blockContentId: fingerprint,
1072
+ equipmentSlug,
1073
+ createdAt: previous?.createdAt ?? now
1074
+ });
1075
+ }
1056
1076
  }
1057
1077
  }
1058
1078
  if (!rowsEqual(existing, note)) await tx.readwrite("notes").put(note);
1059
1079
  if (revisions.length) await tx.readwrite("block_revisions").putMany(revisions);
1060
1080
  await diffProjection(tx, "block_index", priorRows, nextRows);
1061
1081
  await diffProjection(tx, "block_efforts", priorEfforts, nextEfforts);
1082
+ await diffProjection(tx, "block_equipment", priorEquipment, nextEquipment);
1062
1083
  const tags = await saveTags(tx, noteId, options.tags, now);
1063
1084
  let session;
1064
1085
  let revision;
@@ -1094,6 +1115,7 @@ async function diffProjection(tx, store, previous, next) {
1094
1115
  if (!rowsEqual(old.get(row.id), row)) {
1095
1116
  if (store === "block_index" && "blockVersion" in row) await tx.readwrite("block_index").put(row);
1096
1117
  if (store === "block_efforts" && "effortSlug" in row) await tx.readwrite("block_efforts").put(row);
1118
+ if (store === "block_equipment" && "equipmentSlug" in row) await tx.readwrite("block_equipment").put(row);
1097
1119
  }
1098
1120
  }
1099
1121
  }
@@ -1185,6 +1207,12 @@ async function persistEffort(db, effort) {
1185
1207
  await sql.putRow(tx, sql.storeDefinition("efforts"), effort);
1186
1208
  });
1187
1209
  }
1210
+ async function persistEquipment(db, equipment) {
1211
+ const sql = await loadSql();
1212
+ await db.db.transaction(async (tx) => {
1213
+ await sql.putRow(tx, sql.storeDefinition("equipment"), equipment);
1214
+ });
1215
+ }
1188
1216
  async function persistTypedTags(db, labels, type) {
1189
1217
  return db.storage.transaction(["tags"], "readwrite", async (tx) => {
1190
1218
  let added = 0;
@@ -1207,17 +1235,18 @@ async function importSeedDir(db, dir, sourceId) {
1207
1235
  const source = sourceId || path.basename(dir);
1208
1236
  const manifest = assertSeedManifest(JSON.parse(fs.readFileSync(path.resolve(dir, "manifest.json"), "utf-8")));
1209
1237
  const key = seedMetaKey(source);
1210
- let expected = await db.storage.readonly("meta").get(key);
1211
- if (expected && expected.schema !== SEED_SCHEMA$1) throw new Error("Incompatible seed checkpoint; recreate storage");
1238
+ const stored = await db.storage.readonly("meta").get(key);
1239
+ let expected = stored?.schema === SEED_SCHEMA$1 ? stored : void 0;
1212
1240
  let meta = expected ?? emptySeedMeta(key);
1213
1241
  if (manifest.version < meta.seedVersion) throw new Error("Seed manifest is older than stored checkpoint");
1214
- const summary = { sourceId: source, version: manifest.version, notes: 0, efforts: 0, blocks: 0, blockEfforts: 0, deleted: 0, skippedUserOwned: 0 };
1242
+ const summary = { sourceId: source, version: manifest.version, notes: 0, efforts: 0, equipment: 0, blocks: 0, blockEfforts: 0, deleted: 0, skippedUserOwned: 0 };
1215
1243
  const metadataChanged = manifest.version !== meta.seedVersion || manifest.builtAt !== meta.builtAt;
1216
1244
  const plan = manifest.chunks.filter((c) => metadataChanged || meta.chunks[c.id]?.sha256 !== c.sha256);
1217
1245
  plan.sort((a, b) => Number(b.id === CANVAS_CHUNK_ID) - Number(a.id === CANVAS_CHUNK_ID));
1218
1246
  const accumulate = (result) => {
1219
1247
  summary.notes += result.totalNotes;
1220
1248
  summary.efforts += result.totalEfforts;
1249
+ summary.equipment += result.totalEquipment;
1221
1250
  summary.blocks += result.totalBlocks;
1222
1251
  summary.deleted += result.deleted;
1223
1252
  summary.skippedUserOwned += result.skippedUserOwned;
@@ -1287,6 +1316,7 @@ async function publishCatalogSeed(db, options) {
1287
1316
  }
1288
1317
  const allIndexRows = await db.storage.readonly("block_index").getAll();
1289
1318
  const allEffortRows = await db.storage.readonly("block_efforts").getAll();
1319
+ const allEquipmentRows = await db.storage.readonly("block_equipment").getAll();
1290
1320
  const indexByNote = /* @__PURE__ */ new Map();
1291
1321
  for (const row of allIndexRows) {
1292
1322
  const list = indexByNote.get(row.noteId) ?? [];
@@ -1299,6 +1329,12 @@ async function publishCatalogSeed(db, options) {
1299
1329
  list.push(row);
1300
1330
  effortsByNote.set(row.noteId, list);
1301
1331
  }
1332
+ const equipmentByNote = /* @__PURE__ */ new Map();
1333
+ for (const row of allEquipmentRows) {
1334
+ const list = equipmentByNote.get(row.noteId) ?? [];
1335
+ list.push(row);
1336
+ equipmentByNote.set(row.noteId, list);
1337
+ }
1302
1338
  const outDir = path.resolve(process.cwd(), options.outDir);
1303
1339
  const chunksDir = path.join(outDir, "chunks");
1304
1340
  fs.mkdirSync(chunksDir, { recursive: true });
@@ -1313,6 +1349,7 @@ async function publishCatalogSeed(db, options) {
1313
1349
  const notePath = note.sourcePath ?? `markdown/collections/${catalogName}/${stem}.md`;
1314
1350
  const noteBlockIndex = indexByNote.get(note.id) ?? [];
1315
1351
  const noteBlockEfforts = effortsByNote.get(note.id) ?? [];
1352
+ const noteBlockEquipment = equipmentByNote.get(note.id) ?? [];
1316
1353
  const blockIndex = noteBlockIndex.length > 0 ? noteBlockIndex.map((b) => ({
1317
1354
  ...b,
1318
1355
  isStatic: true,
@@ -1332,12 +1369,18 @@ async function publishCatalogSeed(db, options) {
1332
1369
  isStatic: true,
1333
1370
  sourcePath: e.sourcePath ?? notePath
1334
1371
  }));
1372
+ const blockEquipment = noteBlockEquipment.map((e) => ({
1373
+ ...e,
1374
+ isStatic: true,
1375
+ sourcePath: e.sourcePath ?? notePath
1376
+ }));
1335
1377
  chunkRows.push({
1336
1378
  path: notePath,
1337
1379
  content: note.rawContent,
1338
1380
  blocks: note.blocks,
1339
1381
  blockIndex,
1340
- blockEfforts
1382
+ blockEfforts,
1383
+ blockEquipment
1341
1384
  });
1342
1385
  }
1343
1386
  const chunkId = `collection.${catalogName}`;
@@ -1806,7 +1849,7 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
1806
1849
  writeErr("[wod init-catalog] Error: Missing catalog name (a single new directory name)");
1807
1850
  return 1;
1808
1851
  }
1809
- const { scaffoldCatalog } = await import('./scaffoldCatalog-LQOUCJ4X.mjs');
1852
+ const { scaffoldCatalog } = await import('./scaffoldCatalog-TLYSPOQK.mjs');
1810
1853
  try {
1811
1854
  const result = scaffoldCatalog(parsed.target);
1812
1855
  writeOut(`[wod init-catalog] Created ${result.dir} (${result.files.length} files)`);
@@ -2017,7 +2060,9 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2017
2060
  writeErr(`[wod ${verb}] Effort not found in ${db.path}: ${id}`);
2018
2061
  return 1;
2019
2062
  }
2020
- const markdown = effortToMarkdown(effort);
2063
+ const ownerNoteId = typeof effort.ownerNoteId === "string" ? effort.ownerNoteId : `effort/${effort.slug}`;
2064
+ const owner = await db.storage.readonly("notes").get(ownerNoteId);
2065
+ const markdown = owner?.rawContent ?? effortToMarkdown(effort);
2021
2066
  const target = parsed.output && parsed.output !== "-" ? parsed.output : `${id}.md`;
2022
2067
  if (parsed.output === "-") {
2023
2068
  writeOut(markdown);
@@ -2026,15 +2071,29 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2026
2071
  }
2027
2072
  writeOut(`[wod ${verb}] effort ${id} \u2192 ${target}`);
2028
2073
  } else {
2029
- const labels = (await listTagsByType(db.db, "equipment")).map((t) => t.label).sort();
2030
- const csv = equipmentToCsv(labels);
2031
- const target = parsed.output && parsed.output !== "-" ? parsed.output : "equipment.csv";
2032
- if (parsed.output === "-") {
2033
- writeOut(csv);
2074
+ const equipment = id ? await getEquipmentBySlug(db.db, targetId) : void 0;
2075
+ if (equipment) {
2076
+ const ownerNoteId = typeof equipment.ownerNoteId === "string" ? equipment.ownerNoteId : `equipment/${equipment.slug}`;
2077
+ const owner = await db.storage.readonly("notes").get(ownerNoteId);
2078
+ const markdown = owner?.rawContent ?? equipmentToMarkdown(equipment);
2079
+ const target = parsed.output && parsed.output !== "-" ? parsed.output : `${id}.md`;
2080
+ if (parsed.output === "-") {
2081
+ writeOut(markdown);
2082
+ } else {
2083
+ nodeFs().writeFileSync(target, markdown, "utf-8");
2084
+ }
2085
+ writeOut(`[wod ${verb}] equipment ${id} \u2192 ${target}`);
2034
2086
  } else {
2035
- nodeFs().writeFileSync(target, csv, "utf-8");
2087
+ const labels = (await listTagsByType(db.db, "equipment")).map((t) => t.label).sort();
2088
+ const csv = equipmentToCsv(labels);
2089
+ const target = parsed.output && parsed.output !== "-" ? parsed.output : "equipment.csv";
2090
+ if (parsed.output === "-") {
2091
+ writeOut(csv);
2092
+ } else {
2093
+ nodeFs().writeFileSync(target, csv, "utf-8");
2094
+ }
2095
+ writeOut(`[wod ${verb}] equipment \u2192 ${target} (${labels.length} labels)`);
2036
2096
  }
2037
- writeOut(`[wod ${verb}] equipment \u2192 ${target} (${labels.length} labels)`);
2038
2097
  }
2039
2098
  } finally {
2040
2099
  await db.close();
@@ -2076,7 +2135,7 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2076
2135
  return 0;
2077
2136
  }
2078
2137
  if (kind === "effort") {
2079
- const effort = markdownToEffort(fs.readFileSync(file, "utf-8"));
2138
+ const effort = parseEffortFile(fs.readFileSync(file, "utf-8"));
2080
2139
  if (!effort) {
2081
2140
  writeErr(`[wod import] Unparseable effort file (need frontmatter id/slug/label + numeric baseAttributes.met): ${file}`);
2082
2141
  return 1;
@@ -2090,6 +2149,21 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2090
2149
  }
2091
2150
  return 0;
2092
2151
  }
2152
+ if (kind === "equipment" && /\.md$/i.test(file)) {
2153
+ const equipment = parseEquipmentFile(fs.readFileSync(file, "utf-8"));
2154
+ if (!equipment) {
2155
+ writeErr(`[wod import] Unparseable equipment file (need frontmatter type: equipment + id/slug/label): ${file}`);
2156
+ return 1;
2157
+ }
2158
+ const db2 = await openCliDb(cliDb());
2159
+ try {
2160
+ await persistEquipment(db2, { ...equipment, registrySource: "user" });
2161
+ writeOut(`[wod import] equipment ${equipment.slug} \u2014 ${equipment.label} \u2192 ${db2.path}`);
2162
+ } finally {
2163
+ await db2.close();
2164
+ }
2165
+ return 0;
2166
+ }
2093
2167
  if (kind === "equipment") {
2094
2168
  const labels = csvToEquipmentLabels(fs.readFileSync(file, "utf-8"));
2095
2169
  if (labels.length === 0) {
@@ -2144,7 +2218,7 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2144
2218
  writeErr(`[wod build] No markdown/ corpus under ${root} \u2014 run from the content repo root (or pass its directory).`);
2145
2219
  return 1;
2146
2220
  }
2147
- const { generateSeed } = await import('./compiler-B77PITYH.mjs');
2221
+ const { generateSeed } = await import('./compiler-E6HYL477.mjs');
2148
2222
  try {
2149
2223
  const result = generateSeed({
2150
2224
  corpusRoot: root,
@@ -2214,7 +2288,7 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2214
2288
  }
2215
2289
  if (parsed.subcommand === "server" || parsed.subcommand === "serve" || parsed.subcommand === "playground") {
2216
2290
  const mode = parsed.subcommand === "playground" ? "playground" : "server";
2217
- const { runCliServer } = await import('./server-JXECWS4A.mjs');
2291
+ const { runCliServer } = await import('./server-2DVBA35J.mjs');
2218
2292
  const options = { env: cliEnv() };
2219
2293
  if (mode === "server") options.database = cliDb();
2220
2294
  if (parsed.host !== void 0) options.host = parsed.host;
@@ -2240,5 +2314,5 @@ async function cliMain(argv = process.argv.slice(2), io = {}) {
2240
2314
  }
2241
2315
 
2242
2316
  export { PackLoadError, ParseSyntaxError, WqlSyntaxError, cliMain, formatExecutionOutput, formatParseOutput, formatQueryOutput, loadCliEnvironment, loadLanguagePack, loadQueryData, parseCliArgs, readStdin, resolveDatabaseConfig, runExecution, runParse, runQueryCli };
2243
- //# sourceMappingURL=chunk-GBBJBDLS.mjs.map
2244
- //# sourceMappingURL=chunk-GBBJBDLS.mjs.map
2317
+ //# sourceMappingURL=chunk-UNJ6OZVO.mjs.map
2318
+ //# sourceMappingURL=chunk-UNJ6OZVO.mjs.map