@arbidocs/react 0.5.151 → 0.5.152

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 (34) hide show
  1. package/dist/{chunk-B6T54X65.cjs → chunk-WJIRX5MS.cjs} +4 -4
  2. package/dist/chunk-WJIRX5MS.cjs.map +1 -0
  3. package/dist/datasets/rows-source.js.map +2 -2
  4. package/dist/datasets/sources/activity.js +1 -1
  5. package/dist/datasets/sources/activity.js.map +2 -2
  6. package/dist/datasets/sources/conversations.js +1 -1
  7. package/dist/datasets/sources/conversations.js.map +2 -2
  8. package/dist/datasets/sources/database.js +17 -9
  9. package/dist/datasets/sources/database.js.map +2 -2
  10. package/dist/datasets/sources/documents.js +1 -1
  11. package/dist/datasets/sources/documents.js.map +2 -2
  12. package/dist/datasets/sources/facts.js +1 -1
  13. package/dist/datasets/sources/facts.js.map +2 -2
  14. package/dist/datasets/sources/projects.js +1 -1
  15. package/dist/datasets/sources/projects.js.map +2 -2
  16. package/dist/datasets/sources/tags.js +1 -1
  17. package/dist/datasets/sources/tags.js.map +2 -2
  18. package/dist/datasets/sources/usage.js +5 -4
  19. package/dist/datasets/sources/usage.js.map +2 -2
  20. package/dist/datasets/sources/workflows.js +1 -1
  21. package/dist/datasets/sources/workflows.js.map +2 -2
  22. package/dist/datasets/sources/workspaces.js +1 -1
  23. package/dist/datasets/sources/workspaces.js.map +2 -2
  24. package/dist/datasets/types.js.map +1 -1
  25. package/dist/index.cjs +245 -237
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/{index.d-DbcrFwS6.d.ts → index.d-Dy_Pz6Vl.d.ts} +4 -0
  28. package/dist/index.d.ts +7 -2
  29. package/dist/ui/card.js +2 -2
  30. package/dist/ui/card.js.map +2 -2
  31. package/dist/ui/index.cjs +151 -151
  32. package/dist/ui/index.d.ts +1 -1
  33. package/package.json +3 -3
  34. package/dist/chunk-B6T54X65.cjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/datasets/sources/usage.ts"],
4
- "sourcesContent": ["/**\n * AI usage (recorded by the model gateway) as datasets, for this billing period or the last\n * (`params.period` `\"0\"` / `\"1\"`):\n *\n * - `usage`: one row per project, day and model group.\n * - `usage-breakdown`: the period's totals by user, workspace, model or feature (`params.by`), one\n * row per project and name: the gateway records who and where for the period only, not by day.\n *\n * Both read one project (`params.project`, its error surfaced: a project's own usage view) or every\n * project the user owns (the server answers a project's usage to its owner alone; a project whose\n * usage cannot be read is left out rather than failing the others, so a member sees no usage).\n * Each project's usage is read through the same queries as `useProjectUsage`, so a dashboard and\n * the project's usage view share one cache. \u00A3 are ex VAT.\n */\nimport { useMemo } from 'react'\nimport { useQueries } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport { useArbi } from '../../useArbi'\nimport { useCurrentUser, useProjects, useWorkspaces } from '../../hooks'\nimport { arbiQueryKeys } from '../../query-keys'\nimport { getUserDisplayName } from '../../users/user-display'\nimport { defineRowsSource, staticFields, type RowsState } from '../rows-source'\nimport type {\n DataSource,\n DataSourceFieldsState,\n DataSourceParam,\n DataSourceParams,\n DatasetField,\n DatasetRow,\n} from '../types'\n\ntype ProjectResponse = components['schemas']['ProjectResponse']\ntype ProjectUsageResponse = components['schemas']['ProjectUsageResponse']\ntype WorkspaceResponse = components['schemas']['WorkspaceResponse']\n\n/**\n * People's names for model groups whose gateway names are not meant to be read (the LLM tiers are\n * already readable).\n */\nexport const MODEL_GROUP_LABELS: Readonly<Record<string, string>> = {\n 'arbi-transcribe-diarized': 'Transcription (diarized)',\n 'arbi-transcribe': 'Transcription',\n}\n\n/** What usage is broken down by (`usage-breakdown`'s `by`). */\nexport type UsageBreakdownKey = 'user' | 'workspace' | 'model' | 'feature'\n\n/** `usage-breakdown`'s `by`: a breakdown, or `total` (the period's totals as the server counts them). */\nexport type UsageBreakdownBy = UsageBreakdownKey | 'total'\n\nexport interface UsageSourceLabels {\n source: string\n description: string\n period: string\n periods: { current: string; previous: string }\n /** The project parameter (its placeholder: every project the user owns). */\n projectParam: string\n allProjects: string\n day: string\n project: string\n model: string\n spend: string\n tokens: string\n requests: string\n}\n\nexport const DEFAULT_USAGE_SOURCE_LABELS: UsageSourceLabels = {\n source: 'AI usage',\n description: 'AI usage of your projects by day and model: \u00A3 (ex VAT), tokens and requests.',\n period: 'Period',\n periods: { current: 'This period', previous: 'Last period' },\n projectParam: 'Project',\n allProjects: 'All your projects',\n day: 'Day',\n project: 'Project',\n model: 'Model',\n spend: 'AI usage (\u00A3)',\n tokens: 'Tokens',\n requests: 'Requests',\n}\n\nexport interface UsageBreakdownSourceLabels extends Omit<\n UsageSourceLabels,\n 'day' | 'model' | 'description'\n> {\n description: string\n breakdown: string\n /** The breakdowns, as the parameter's choices and the name field's label. */\n by: Record<UsageBreakdownBy, string>\n}\n\nexport const DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS: UsageBreakdownSourceLabels = {\n ...DEFAULT_USAGE_SOURCE_LABELS,\n source: 'AI usage breakdown',\n description:\n 'AI usage of your projects this period, in total or by user, workspace, model or feature: \u00A3 (ex VAT), tokens and requests.',\n breakdown: 'Breakdown',\n by: { total: 'Total', user: 'User', workspace: 'Workspace', model: 'Model', feature: 'Feature' },\n}\n\nconst monthsBackOf = (params: DataSourceParams) => (String(params.period ?? '0') === '1' ? 1 : 0)\n\nconst projectOf = (params: DataSourceParams) =>\n typeof params.project === 'string' && params.project ? params.project : undefined\n\nconst BREAKDOWNS: readonly UsageBreakdownBy[] = ['total', 'user', 'workspace', 'model', 'feature']\n\nconst breakdownOf = (params: DataSourceParams): UsageBreakdownBy =>\n BREAKDOWNS.find((b) => b === params.by) ?? 'user'\n\n/** The projects `me` owns (the server answers a project's usage to its owner alone). */\nconst ownedBy = (projects: unknown, me: string | undefined) =>\n ((projects as ProjectResponse[] | undefined) ?? []).filter((p) => !!me && p.created_by === me)\n\n/** Every day of the billing period starting `start` (to the day before the same date next month). */\nfunction periodDays(start: string): string[] {\n const end = new Date(`${start}T00:00:00Z`)\n end.setUTCMonth(end.getUTCMonth() + 1)\n end.setUTCDate(end.getUTCDate() - 1)\n const days: string[] = []\n for (const d = new Date(`${start}T00:00:00Z`); d <= end; d.setUTCDate(d.getUTCDate() + 1)) {\n days.push(d.toISOString().slice(0, 10))\n }\n return days\n}\n\n/** A feature key as people read it: `document_qa` \u2192 \"Document qa\". */\nconst featureLabel = (key: string) =>\n key.replace(/[_-]+/g, ' ').replace(/^\\w/, (c) => c.toUpperCase())\n\n/** A model group as people read it. */\nconst modelLabelOf = (group: string) => MODEL_GROUP_LABELS[group] ?? group\n\n/**\n * Rows of one project's usage: a row per day and model group. The days without usage get a row of\n * 0, so a chart by day spans the whole billing period.\n */\nexport function usageRows(\n usage: ProjectUsageResponse,\n project: string,\n modelLabel: (group: string) => string = modelLabelOf\n): DatasetRow[] {\n const rows: DatasetRow[] = (usage.daily ?? []).flatMap((day) =>\n Object.entries(day.model_groups ?? {}).map(([group, mg]) => ({\n day: day.date,\n project,\n model: modelLabel(group),\n spend: mg.spend ?? 0,\n tokens: mg.total_tokens ?? 0,\n requests: (mg.successful_requests ?? 0) + (mg.failed_requests ?? 0),\n }))\n )\n const model = rows[0]?.model\n if (!usage.period_start || model === undefined) return rows\n const used = new Set(rows.map((r) => r.day))\n const gaps = periodDays(usage.period_start)\n .filter((day) => !used.has(day))\n .map((day) => ({ day, project, model, spend: 0, tokens: 0, requests: 0 }))\n return [...rows, ...gaps]\n}\n\n/** Workspace and member names by external id, from the workspaces the user can see. */\nfunction usageNamesOf(workspaces: readonly WorkspaceResponse[]): Record<string, string> {\n const names: Record<string, string> = {}\n for (const ws of workspaces) {\n names[ws.external_id] = ws.name\n for (const wu of ws.users ?? []) {\n const user = wu.user\n if (user?.external_id && !names[user.external_id]) {\n names[user.external_id] = getUserDisplayName(user)\n }\n }\n }\n return names\n}\n\n/** Rows of one project's period totals by `by`: a row per name. */\nfunction usageBreakdownRows(\n usage: ProjectUsageResponse,\n project: string,\n by: UsageBreakdownBy,\n names: Readonly<Record<string, string>> = {},\n totalLabel = 'Total'\n): DatasetRow[] {\n if (by === 'total') {\n return [\n {\n project,\n name: totalLabel,\n spend: usage.total_spend ?? 0,\n tokens: usage.total_tokens ?? 0,\n requests: usage.total_requests ?? 0,\n },\n ]\n }\n if (by === 'model') {\n return Object.entries(usage.model_groups ?? {}).map(([group, mg]) => ({\n project,\n name: names[group] ?? modelLabelOf(group),\n spend: mg.spend ?? 0,\n tokens: mg.total_tokens ?? 0,\n requests: (mg.successful_requests ?? 0) + (mg.failed_requests ?? 0),\n }))\n }\n const totals =\n by === 'workspace' ? usage.by_workspace : by === 'feature' ? usage.by_feature : usage.by_user\n return Object.entries(totals ?? {}).map(([key, t]) => ({\n project,\n name: by === 'feature' ? featureLabel(key) : (names[key] ?? key),\n spend: t.spend ?? 0,\n tokens: t.total_tokens ?? 0,\n requests: t.requests ?? 0,\n }))\n}\n\ninterface UsageResponses {\n /** Each project read with its usage (absent when it could not be read). */\n usages:\n | {\n project: ProjectResponse | { external_id: string; name: string }\n usage?: ProjectUsageResponse\n }[]\n | undefined\n isLoading: boolean\n error: unknown\n}\n\n/** The usage of the project asked for, or of every project the user owns. */\nfunction useUsageResponses(params: DataSourceParams, enabled: boolean): UsageResponses {\n const arbi = useArbi()\n const monthsBack = monthsBackOf(params)\n const only = projectOf(params)\n const projects = useProjects({ enabled })\n const user = useCurrentUser({ enabled: enabled && arbi.isLoggedIn && !only })\n const me = user.data?.external_id\n const list = useMemo(() => {\n const all = (projects.data as ProjectResponse[] | undefined) ?? []\n if (only) return [all.find((p) => p.external_id === only) ?? { external_id: only, name: only }]\n return ownedBy(all, me)\n }, [projects.data, me, only])\n const results = useQueries({\n queries: list.map((p) => ({\n queryKey: arbiQueryKeys.projectUsage(p.external_id, monthsBack),\n queryFn: () => arbi.projects.usage(p.external_id, monthsBack),\n enabled: enabled && arbi.isLoggedIn,\n retry: false,\n })),\n })\n const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt}`).join('|')\n // `signature` stands for the results, which are a new array every render.\n const usages = useMemo(() => {\n if (results.some((r) => r.isLoading)) return undefined\n if (!only && (!projects.data || !me)) return undefined\n return results.map((r, i) => ({\n project: list[i],\n usage: r.data as ProjectUsageResponse | undefined,\n }))\n }, [projects.data, me, only, signature])\n const loading = results.some((r) => r.isLoading)\n return only\n ? // One project: its usage is the point, so its error shows (the project's name can wait).\n { usages, isLoading: loading, error: results[0]?.error ?? null }\n : {\n usages,\n isLoading: projects.isLoading || user.isLoading || loading,\n // One project's usage failing (not its owner after all, a hiccup) leaves it out.\n error: projects.error ?? user.error ?? null,\n }\n}\n\n/** The period and project parameters both sources take. */\nfunction usageParams(\n l: Pick<UsageSourceLabels, 'period' | 'periods' | 'projectParam' | 'allProjects'>\n): DataSourceParam[] {\n const periodOptions = {\n options: [\n { value: '0', label: l.periods.current },\n { value: '1', label: l.periods.previous },\n ],\n isLoading: false,\n }\n return [\n {\n id: 'period',\n label: l.period,\n placeholder: l.periods.current,\n useOptions: () => periodOptions,\n },\n {\n id: 'project',\n label: l.projectParam,\n placeholder: l.allProjects,\n useOptions() {\n const arbi = useArbi()\n const projects = useProjects()\n const user = useCurrentUser({ enabled: arbi.isLoggedIn })\n const me = user.data?.external_id\n const options = useMemo(\n () => ownedBy(projects.data, me).map((p) => ({ value: p.external_id, label: p.name })),\n [projects.data, me]\n )\n return { options, isLoading: projects.isLoading || user.isLoading }\n },\n },\n ]\n}\n\nexport function createUsageSource(labels?: Partial<UsageSourceLabels>): DataSource {\n const l = { ...DEFAULT_USAGE_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'day', label: l.day, type: 'date' },\n { id: 'project', label: l.project, type: 'string' },\n { id: 'model', label: l.model, type: 'string' },\n { id: 'spend', label: l.spend, type: 'number', unit: 'gbp' },\n { id: 'tokens', label: l.tokens, type: 'number', unit: 'tokens' },\n { id: 'requests', label: l.requests, type: 'number' },\n ]\n return defineRowsSource({\n id: 'usage',\n label: l.source,\n description: l.description,\n params: usageParams(l),\n useFields: staticFields(fields),\n useRows(params, enabled): RowsState {\n const { usages, isLoading, error } = useUsageResponses(params, enabled)\n const rows = useMemo(\n () => usages?.flatMap((u) => (u.usage ? usageRows(u.usage, u.project.name) : [])),\n [usages]\n )\n return { rows, isLoading, error }\n },\n })\n}\n\nexport function createUsageBreakdownSource(\n labels?: Partial<UsageBreakdownSourceLabels>\n): DataSource {\n const l = { ...DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS, ...labels }\n const fieldsBy = Object.fromEntries(\n BREAKDOWNS.map((by): [UsageBreakdownBy, DataSourceFieldsState] => [\n by,\n {\n fields: [\n { id: 'project', label: l.project, type: 'string' },\n { id: 'name', label: l.by[by], type: 'string' },\n { id: 'spend', label: l.spend, type: 'number', unit: 'gbp' },\n { id: 'tokens', label: l.tokens, type: 'number', unit: 'tokens' },\n { id: 'requests', label: l.requests, type: 'number' },\n ],\n isLoading: false,\n error: null,\n },\n ])\n ) as Record<UsageBreakdownBy, DataSourceFieldsState>\n const byOptions = {\n options: BREAKDOWNS.map((by) => ({ value: by, label: l.by[by] })),\n isLoading: false,\n }\n return defineRowsSource({\n id: 'usage-breakdown',\n label: l.source,\n description: l.description,\n params: [\n ...usageParams(l),\n { id: 'by', label: l.breakdown, placeholder: l.by.user, useOptions: () => byOptions },\n ],\n useFields: (params) => fieldsBy[breakdownOf(params)],\n useRows(params, enabled): RowsState {\n const by = breakdownOf(params)\n const { usages, isLoading, error } = useUsageResponses(params, enabled)\n // Names only matter for people and workspaces; models and features name themselves.\n const workspaces = useWorkspaces({\n enabled: enabled && (by === 'user' || by === 'workspace'),\n })\n const names = useMemo(\n () => usageNamesOf((workspaces.data as WorkspaceResponse[] | undefined) ?? []),\n [workspaces.data]\n )\n const rows = useMemo(\n () =>\n usages?.flatMap((u) =>\n u.usage ? usageBreakdownRows(u.usage, u.project.name, by, names, l.by.total) : []\n ),\n [usages, by, names, l.by.total]\n )\n return { rows, is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AAI,OAAO,EAAE,GAAG,KAAK;AAAA,MAChC;AACA,aAAO,EAAE,MAAM,WAAW,MAAM;AAAA,IAClC;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["/**\n * AI usage (recorded by the model gateway) as datasets, for this billing period or the last\n * (`params.period` `\"0\"` / `\"1\"`):\n *\n * - `usage`: one row per project, day and model group.\n * - `usage-breakdown`: the period's totals by user, workspace, model or feature (`params.by`), one\n * row per project and name: the gateway records who and where for the period only, not by day.\n *\n * Both read one project (`params.project`, its error surfaced: a project's own usage view) or every\n * project the user owns (the server answers a project's usage to its owner alone; a project whose\n * usage cannot be read is left out rather than failing the others, so a member sees no usage).\n * Each project's usage is read through the same queries as `useProjectUsage`, so a dashboard and\n * the project's usage view share one cache. \u00A3 are ex VAT.\n */\nimport { useMemo } from 'react'\nimport { useQueries } from '@tanstack/react-query'\nimport type { components } from '@arbidocs/client'\nimport { useArbi } from '../../useArbi'\nimport { useCurrentUser, useProjects, useWorkspaces } from '../../hooks'\nimport { arbiQueryKeys } from '../../query-keys'\nimport { getUserDisplayName } from '../../users/user-display'\nimport { defineRowsSource, staticFields, type RowsState } from '../rows-source'\nimport type {\n DataSource,\n DataSourceFieldsState,\n DataSourceParam,\n DataSourceParams,\n DatasetField,\n DatasetRow,\n} from '../types'\n\ntype ProjectResponse = components['schemas']['ProjectResponse']\ntype ProjectUsageResponse = components['schemas']['ProjectUsageResponse']\ntype WorkspaceResponse = components['schemas']['WorkspaceResponse']\n\n/**\n * People's names for model groups whose gateway names are not meant to be read (the LLM tiers are\n * already readable).\n */\nexport const MODEL_GROUP_LABELS: Readonly<Record<string, string>> = {\n 'arbi-transcribe-diarized': 'Transcription (diarized)',\n 'arbi-transcribe': 'Transcription',\n}\n\n/** What usage is broken down by (`usage-breakdown`'s `by`). */\nexport type UsageBreakdownKey = 'user' | 'workspace' | 'model' | 'feature'\n\n/** `usage-breakdown`'s `by`: a breakdown, or `total` (the period's totals as the server counts them). */\nexport type UsageBreakdownBy = UsageBreakdownKey | 'total'\n\nexport interface UsageSourceLabels {\n source: string\n description: string\n period: string\n periods: { current: string; previous: string }\n /** The project parameter (its placeholder: every project the user owns). */\n projectParam: string\n allProjects: string\n day: string\n project: string\n model: string\n spend: string\n tokens: string\n requests: string\n}\n\nexport const DEFAULT_USAGE_SOURCE_LABELS: UsageSourceLabels = {\n source: 'AI usage',\n description: 'AI usage of your projects by day and model: \u00A3 (ex VAT), tokens and requests.',\n period: 'Period',\n periods: { current: 'This period', previous: 'Last period' },\n projectParam: 'Project',\n allProjects: 'All your projects',\n day: 'Day',\n project: 'Project',\n model: 'Model',\n spend: 'AI usage (\u00A3)',\n tokens: 'Tokens',\n requests: 'Requests',\n}\n\nexport interface UsageBreakdownSourceLabels extends Omit<\n UsageSourceLabels,\n 'day' | 'model' | 'description'\n> {\n description: string\n breakdown: string\n /** The breakdowns, as the parameter's choices and the name field's label. */\n by: Record<UsageBreakdownBy, string>\n}\n\nexport const DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS: UsageBreakdownSourceLabels = {\n ...DEFAULT_USAGE_SOURCE_LABELS,\n source: 'AI usage breakdown',\n description:\n 'AI usage of your projects this period, in total or by user, workspace, model or feature: \u00A3 (ex VAT), tokens and requests.',\n breakdown: 'Breakdown',\n by: { total: 'Total', user: 'User', workspace: 'Workspace', model: 'Model', feature: 'Feature' },\n}\n\nconst monthsBackOf = (params: DataSourceParams) => (String(params.period ?? '0') === '1' ? 1 : 0)\n\nconst projectOf = (params: DataSourceParams) =>\n typeof params.project === 'string' && params.project ? params.project : undefined\n\nconst BREAKDOWNS: readonly UsageBreakdownBy[] = ['total', 'user', 'workspace', 'model', 'feature']\n\nconst breakdownOf = (params: DataSourceParams): UsageBreakdownBy =>\n BREAKDOWNS.find((b) => b === params.by) ?? 'user'\n\n/** The projects `me` owns (the server answers a project's usage to its owner alone). */\nconst ownedBy = (projects: unknown, me: string | undefined) =>\n ((projects as ProjectResponse[] | undefined) ?? []).filter((p) => !!me && p.created_by === me)\n\n/** Every day of the billing period starting `start` (to the day before the same date next month). */\nfunction periodDays(start: string): string[] {\n const end = new Date(`${start}T00:00:00Z`)\n end.setUTCMonth(end.getUTCMonth() + 1)\n end.setUTCDate(end.getUTCDate() - 1)\n const days: string[] = []\n for (const d = new Date(`${start}T00:00:00Z`); d <= end; d.setUTCDate(d.getUTCDate() + 1)) {\n days.push(d.toISOString().slice(0, 10))\n }\n return days\n}\n\n/** A feature key as people read it: `document_qa` \u2192 \"Document qa\". */\nconst featureLabel = (key: string) =>\n key.replace(/[_-]+/g, ' ').replace(/^\\w/, (c) => c.toUpperCase())\n\n/** A model group as people read it. */\nconst modelLabelOf = (group: string) => MODEL_GROUP_LABELS[group] ?? group\n\n/**\n * Rows of one project's usage: a row per day and model group. The days without usage get a row of\n * 0, so a chart by day spans the whole billing period.\n */\nexport function usageRows(\n usage: ProjectUsageResponse,\n project: string,\n modelLabel: (group: string) => string = modelLabelOf\n): DatasetRow[] {\n const rows: DatasetRow[] = (usage.daily ?? []).flatMap((day) =>\n Object.entries(day.model_groups ?? {}).map(([group, mg]) => ({\n day: day.date,\n project,\n model: modelLabel(group),\n spend: mg.spend ?? 0,\n tokens: mg.total_tokens ?? 0,\n requests: (mg.successful_requests ?? 0) + (mg.failed_requests ?? 0),\n }))\n )\n const model = rows[0]?.model\n if (!usage.period_start || model === undefined) return rows\n const used = new Set(rows.map((r) => r.day))\n const gaps = periodDays(usage.period_start)\n .filter((day) => !used.has(day))\n .map((day) => ({ day, project, model, spend: 0, tokens: 0, requests: 0 }))\n return [...rows, ...gaps]\n}\n\n/** Workspace and member names by external id, from the workspaces the user can see. */\nfunction usageNamesOf(workspaces: readonly WorkspaceResponse[]): Record<string, string> {\n const names: Record<string, string> = {}\n for (const ws of workspaces) {\n names[ws.external_id] = ws.name\n for (const wu of ws.users ?? []) {\n const user = wu.user\n if (user?.external_id && !names[user.external_id]) {\n names[user.external_id] = getUserDisplayName(user)\n }\n }\n }\n return names\n}\n\n/** Rows of one project's period totals by `by`: a row per name. */\nfunction usageBreakdownRows(\n usage: ProjectUsageResponse,\n project: string,\n by: UsageBreakdownBy,\n names: Readonly<Record<string, string>> = {},\n totalLabel = 'Total'\n): DatasetRow[] {\n if (by === 'total') {\n return [\n {\n project,\n name: totalLabel,\n spend: usage.total_spend ?? 0,\n tokens: usage.total_tokens ?? 0,\n requests: usage.total_requests ?? 0,\n },\n ]\n }\n if (by === 'model') {\n return Object.entries(usage.model_groups ?? {}).map(([group, mg]) => ({\n project,\n name: names[group] ?? modelLabelOf(group),\n spend: mg.spend ?? 0,\n tokens: mg.total_tokens ?? 0,\n requests: (mg.successful_requests ?? 0) + (mg.failed_requests ?? 0),\n }))\n }\n const totals =\n by === 'workspace' ? usage.by_workspace : by === 'feature' ? usage.by_feature : usage.by_user\n return Object.entries(totals ?? {}).map(([key, t]) => ({\n project,\n name: by === 'feature' ? featureLabel(key) : (names[key] ?? key),\n spend: t.spend ?? 0,\n tokens: t.total_tokens ?? 0,\n requests: t.requests ?? 0,\n }))\n}\n\ninterface UsageResponses {\n /** Each project read with its usage (absent when it could not be read). */\n usages:\n | {\n project: ProjectResponse | { external_id: string; name: string }\n usage?: ProjectUsageResponse\n }[]\n | undefined\n isLoading: boolean\n error: unknown\n}\n\n/** The usage of the project asked for, or of every project the user owns. */\nfunction useUsageResponses(params: DataSourceParams, enabled: boolean): UsageResponses {\n const arbi = useArbi()\n const monthsBack = monthsBackOf(params)\n const only = projectOf(params)\n const projects = useProjects({ enabled })\n const user = useCurrentUser({ enabled: enabled && arbi.isLoggedIn && !only })\n const me = user.data?.external_id\n const list = useMemo(() => {\n const all = (projects.data as ProjectResponse[] | undefined) ?? []\n if (only) return [all.find((p) => p.external_id === only) ?? { external_id: only, name: only }]\n return ownedBy(all, me)\n }, [projects.data, me, only])\n const results = useQueries({\n queries: list.map((p) => ({\n queryKey: arbiQueryKeys.projectUsage(p.external_id, monthsBack),\n queryFn: () => arbi.projects.usage(p.external_id, monthsBack),\n enabled: enabled && arbi.isLoggedIn,\n retry: false,\n })),\n })\n const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt}`).join('|')\n // Pending, not only fetching: a read waiting to start (the projects, the user) is loading too.\n const loading = enabled && arbi.isLoggedIn && results.some((r) => r.isPending)\n const userPending = enabled && arbi.isLoggedIn && !only && user.isPending\n // `signature` stands for the results, which are a new array every render.\n const usages = useMemo(() => {\n if (loading) return undefined\n if (!only && (!projects.data || !me)) return undefined\n return results.map((r, i) => ({\n project: list[i],\n usage: r.data as ProjectUsageResponse | undefined,\n }))\n }, [projects.data, me, only, signature, loading])\n return only\n ? // One project: its usage is the point, so its error shows (the project's name can wait).\n { usages, isLoading: loading, error: results[0]?.error ?? null }\n : {\n usages,\n isLoading: (enabled && projects.isPending) || userPending || loading,\n // One project's usage failing (not its owner after all, a hiccup) leaves it out.\n error: projects.error ?? user.error ?? null,\n }\n}\n\n/** The period and project parameters both sources take. */\nfunction usageParams(\n l: Pick<UsageSourceLabels, 'period' | 'periods' | 'projectParam' | 'allProjects'>\n): DataSourceParam[] {\n const periodOptions = {\n options: [\n { value: '0', label: l.periods.current },\n { value: '1', label: l.periods.previous },\n ],\n isLoading: false,\n }\n return [\n {\n id: 'period',\n label: l.period,\n placeholder: l.periods.current,\n useOptions: () => periodOptions,\n },\n {\n id: 'project',\n label: l.projectParam,\n placeholder: l.allProjects,\n useOptions() {\n const arbi = useArbi()\n const projects = useProjects()\n const user = useCurrentUser({ enabled: arbi.isLoggedIn })\n const me = user.data?.external_id\n const options = useMemo(\n () => ownedBy(projects.data, me).map((p) => ({ value: p.external_id, label: p.name })),\n [projects.data, me]\n )\n return { options, isLoading: projects.isLoading || user.isLoading }\n },\n },\n ]\n}\n\nexport function createUsageSource(labels?: Partial<UsageSourceLabels>): DataSource {\n const l = { ...DEFAULT_USAGE_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'day', label: l.day, type: 'date' },\n { id: 'project', label: l.project, type: 'string' },\n { id: 'model', label: l.model, type: 'string' },\n { id: 'spend', label: l.spend, type: 'number', unit: 'gbp' },\n { id: 'tokens', label: l.tokens, type: 'number', unit: 'tokens' },\n { id: 'requests', label: l.requests, type: 'number' },\n ]\n return defineRowsSource({\n id: 'usage',\n label: l.source,\n description: l.description,\n params: usageParams(l),\n useFields: staticFields(fields),\n useRows(params, enabled): RowsState {\n const { usages, isLoading, error } = useUsageResponses(params, enabled)\n const rows = useMemo(\n () => usages?.flatMap((u) => (u.usage ? usageRows(u.usage, u.project.name) : [])),\n [usages]\n )\n return { rows, isLoading, error }\n },\n })\n}\n\nexport function createUsageBreakdownSource(\n labels?: Partial<UsageBreakdownSourceLabels>\n): DataSource {\n const l = { ...DEFAULT_USAGE_BREAKDOWN_SOURCE_LABELS, ...labels }\n const fieldsBy = Object.fromEntries(\n BREAKDOWNS.map((by): [UsageBreakdownBy, DataSourceFieldsState] => [\n by,\n {\n fields: [\n { id: 'project', label: l.project, type: 'string' },\n { id: 'name', label: l.by[by], type: 'string' },\n { id: 'spend', label: l.spend, type: 'number', unit: 'gbp' },\n { id: 'tokens', label: l.tokens, type: 'number', unit: 'tokens' },\n { id: 'requests', label: l.requests, type: 'number' },\n ],\n isLoading: false,\n error: null,\n },\n ])\n ) as Record<UsageBreakdownBy, DataSourceFieldsState>\n const byOptions = {\n options: BREAKDOWNS.map((by) => ({ value: by, label: l.by[by] })),\n isLoading: false,\n }\n return defineRowsSource({\n id: 'usage-breakdown',\n label: l.source,\n description: l.description,\n params: [\n ...usageParams(l),\n { id: 'by', label: l.breakdown, placeholder: l.by.user, useOptions: () => byOptions },\n ],\n useFields: (params) => fieldsBy[breakdownOf(params)],\n useRows(params, enabled): RowsState {\n const by = breakdownOf(params)\n const { usages, isLoading, error } = useUsageResponses(params, enabled)\n // Names only matter for people and workspaces; models and features name themselves.\n const workspaces = useWorkspaces({\n enabled: enabled && (by === 'user' || by === 'workspace'),\n })\n const names = useMemo(\n () => usageNamesOf((workspaces.data as WorkspaceResponse[] | undefined) ?? []),\n [workspaces.data]\n )\n const rows = useMemo(\n () =>\n usages?.flatMap((u) =>\n u.usage ? usageBreakdownRows(u.usage, u.project.name, by, names, l.by.total) : []\n ),\n [usages, by, names, l.by.total]\n )\n return { rows, isLoading, error }\n },\n })\n}\n"],
5
+ "mappings": "AAcA,SAAS,eAAe;AACxB,SAAS,kBAAkB;AAE3B,SAAS,eAAe;AACxB,SAAS,gBAAgB,aAAa,qBAAqB;AAC3D,SAAS,qBAAqB;AAC9B,SAAS,0BAA0B;AACnC,SAAS,kBAAkB,oBAAoC;AAkBxD,MAAM,qBAAuD;AAAA,EAClE,4BAA4B;AAAA,EAC5B,mBAAmB;AACrB;AAwBO,MAAM,8BAAiD;AAAA,EAC5D,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS,EAAE,SAAS,eAAe,UAAU,cAAc;AAAA,EAC3D,cAAc;AAAA,EACd,aAAa;AAAA,EACb,KAAK;AAAA,EACL,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAYO,MAAM,wCAAoE;AAAA,EAC/E,GAAG;AAAA,EACH,QAAQ;AAAA,EACR,aACE;AAAA,EACF,WAAW;AAAA,EACX,IAAI,EAAE,OAAO,SAAS,MAAM,QAAQ,WAAW,aAAa,OAAO,SAAS,SAAS,UAAU;AACjG;AAEA,MAAM,eAAe,CAAC,WAA8B,OAAO,OAAO,UAAU,GAAG,MAAM,MAAM,IAAI;AAE/F,MAAM,YAAY,CAAC,WACjB,OAAO,OAAO,YAAY,YAAY,OAAO,UAAU,OAAO,UAAU;AAE1E,MAAM,aAA0C,CAAC,SAAS,QAAQ,aAAa,SAAS,SAAS;AAEjG,MAAM,cAAc,CAAC,WACnB,WAAW,KAAK,CAAC,MAAM,MAAM,OAAO,EAAE,KAAK;AAG7C,MAAM,UAAU,CAAC,UAAmB,QAChC,YAA8C,CAAC,GAAG,OAAO,CAAC,MAAM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AAM,OAAO;AAAA,QACX,MACE,QAAQ;AAAA,UAAQ,CAAC,MACf,EAAE,QAAQ,mBAAmB,EAAE,OAAO,EAAE,QAAQ,MAAM,IAAI,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC;AAAA,QAClF;AAAA,QACF,CAAC,QAAQ,IAAI,OAAO,EAAE,GAAG,KAAK;AAAA,MAChC;AACA,aAAO,EAAE,MAAM,WAAW,MAAM;AAAA,IAClC;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -80,7 +80,7 @@ function createWorkflowsSource(labels) {
80
80
  }),
81
81
  [query.data, nameOf, workspaceId]
82
82
  );
83
- return { rows, isLoading: query.isLoading, error: query.error };
83
+ return { rows, isLoading: enabled && on && query.isPending, error: query.error };
84
84
  }
85
85
  });
86
86
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/datasets/sources/workflows.ts"],
4
- "sourcesContent": ["/**\n * The open workspace's workflows as a dataset: a row per workflow with what starts it, whether it\n * is on, how its last run ended and when it runs next. Reads the shared workflow list\n * (`useWorkflows`), keeping the workflows of the open workspace, so the figures match its\n * activity (a workflow's runs over time are the activity source's `workflow` entries). Nothing is\n * read while the host's `workflows` feature is off.\n */\nimport { useMemo } from 'react'\nimport type { WorkflowResponse } from '@arbidocs/sdk/browser'\nimport { useFeature } from '../../host/features'\nimport { useArbiSessionState } from '../../session'\nimport { useWorkflows } from '../../workforce'\nimport { useNames } from '../members'\nimport { defineRowsSource, staticFields } from '../rows-source'\nimport type { DataSource, DatasetField, DatasetRow } from '../types'\n\ntype Trigger = 'manual' | 'after' | 'event' | 'schedule' | 'once'\n\nexport interface WorkflowsSourceLabels {\n source: string\n description: string\n name: string\n trigger: string\n triggers: Record<Trigger, string>\n active: string\n lastRun: string\n lastResult: string\n /** A last run status by the server's name; one not listed is shown as it comes. */\n results: Readonly<Record<string, string>>\n nextRun: string\n owner: string\n shared: string\n created: string\n}\n\nexport const DEFAULT_WORKFLOWS_SOURCE_LABELS: WorkflowsSourceLabels = {\n source: 'Workflows',\n description:\n 'Your workflows: what starts them, how their last run ended, and when they run next.',\n name: 'Workflow',\n trigger: 'Starts',\n triggers: {\n manual: 'By hand',\n after: 'After a task',\n event: 'On an event',\n schedule: 'On a schedule',\n once: 'Once',\n },\n active: 'On',\n lastRun: 'Last run',\n lastResult: 'Last result',\n results: {\n completed: 'Success',\n success: 'Success',\n failed: 'Failed',\n running: 'In progress',\n awaiting_authorization: 'Awaiting access',\n },\n nextRun: 'Next run',\n owner: 'Owner',\n shared: 'Shared',\n created: 'Created',\n}\n\nfunction triggerOf(w: WorkflowResponse): Trigger {\n if (w.on_demand) return 'manual'\n if (w.after_conversation_ext_id) return 'after'\n if (w.event_kind) return 'event'\n if (w.rrule) return 'schedule'\n if (w.run_at) return 'once'\n return 'manual'\n}\n\nexport function createWorkflowsSource(labels?: Partial<WorkflowsSourceLabels>): DataSource {\n const l = { ...DEFAULT_WORKFLOWS_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'name', label: l.name, type: 'string' },\n { id: 'trigger', label: l.trigger, type: 'string', options: Object.values(l.triggers) },\n { id: 'active', label: l.active, type: 'boolean' },\n { id: 'lastRun', label: l.lastRun, type: 'date' },\n { id: 'lastResult', label: l.lastResult, type: 'string' },\n { id: 'nextRun', label: l.nextRun, type: 'date' },\n { id: 'owner', label: l.owner, type: 'string' },\n { id: 'shared', label: l.shared, type: 'boolean' },\n { id: 'created', label: l.created, type: 'date' },\n ]\n return defineRowsSource({\n id: 'workflows',\n scope: 'workspace',\n label: l.source,\n description: l.description,\n useFields: staticFields(fields),\n useRows(_params, enabled) {\n const on = useFeature('workflows')\n const workspaceId = useArbiSessionState((s) => s.workspaceId)\n const query = useWorkflows({ enabled: enabled && on })\n const nameOf = useNames(enabled)\n const rows = useMemo(\n () =>\n query.data\n ?.filter((w) => !!workspaceId && w.workspace_ext_id === workspaceId)\n .map((w): DatasetRow => {\n const result = w.last_run_status\n return {\n name: w.name,\n trigger: l.triggers[triggerOf(w)],\n active: w.active,\n lastRun: w.last_fired_at ?? null,\n lastResult: result ? (l.results[result] ?? result.replaceAll('_', ' ')) : null,\n nextRun: w.next_fire_at ?? null,\n owner: nameOf(w.owner_ext_id),\n shared: w.shared,\n created: w.created_at,\n }\n }),\n [query.data, nameOf, workspaceId]\n )\n return { rows, isLoading: query.isLoading, error: query.error }\n },\n })\n}\n"],
5
- "mappings": "AAOA,SAAS,eAAe;AAExB,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,kBAAkB,oBAAoB;AAsBxC,MAAM,kCAAyD;AAAA,EACpE,QAAQ;AAAA,EACR,aACE;AAAA,EACF,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,OAAO;AAAA,IACP,UAAU;AAAA,IACV,MAAM;AAAA,EACR;AAAA,EACA,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,WAAW;AAAA,IACX,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,wBAAwB;AAAA,EAC1B;AAAA,EACA,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AACX;AAEA,SAAS,UAAU,GAA8B;AAC/C,MAAI,EAAE,UAAW,QAAO;AACxB,MAAI,EAAE,0BAA2B,QAAO;AACxC,MAAI,EAAE,WAAY,QAAO;AACzB,MAAI,EAAE,MAAO,QAAO;AACpB,MAAI,EAAE,OAAQ,QAAO;AACrB,SAAO;AACT;AAEO,SAAS,sBAAsB,QAAqD;AACzF,QAAM,IAAI,EAAE,GAAG,iCAAiC,GAAG,OAAO;AAC1D,QAAM,SAAyB;AAAA,IAC7B,EAAE,IAAI,QAAQ,OAAO,EAAE,MAAM,MAAM,SAAS;AAA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K;AAAA,YAC1E,SAAS,EAAE,gBAAgB;AAAA,YAC3B,OAAO,OAAO,EAAE,YAAY;AAAA,YAC5B,QAAQ,EAAE;AAAA,YACV,SAAS,EAAE;AAAA,UACb;AAAA,QACF,CAAC;AAAA,QACL,CAAC,MAAM,MAAM,QAAQ,WAAW;AAAA,MAClC;AACA,aAAO,EAAE,MAAM,WAAW,MAAM,WAAW,OAAO,MAAM,MAAM;AAAA,IAChE;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["/**\n * The open workspace's workflows as a dataset: a row per workflow with what starts it, whether it\n * is on, how its last run ended and when it runs next. Reads the shared workflow list\n * (`useWorkflows`), keeping the workflows of the open workspace, so the figures match its\n * activity (a workflow's runs over time are the activity source's `workflow` entries). Nothing is\n * read while the host's `workflows` feature is off.\n */\nimport { useMemo } from 'react'\nimport type { WorkflowResponse } from '@arbidocs/sdk/browser'\nimport { useFeature } from '../../host/features'\nimport { useArbiSessionState } from '../../session'\nimport { useWorkflows } from '../../workforce'\nimport { useNames } from '../members'\nimport { defineRowsSource, staticFields } from '../rows-source'\nimport type { DataSource, DatasetField, DatasetRow } from '../types'\n\ntype Trigger = 'manual' | 'after' | 'event' | 'schedule' | 'once'\n\nexport interface WorkflowsSourceLabels {\n source: string\n description: string\n name: string\n trigger: string\n triggers: Record<Trigger, string>\n active: string\n lastRun: string\n lastResult: string\n /** A last run status by the server's name; one not listed is shown as it comes. */\n results: Readonly<Record<string, string>>\n nextRun: string\n owner: string\n shared: string\n created: string\n}\n\nexport const DEFAULT_WORKFLOWS_SOURCE_LABELS: WorkflowsSourceLabels = {\n source: 'Workflows',\n description:\n 'Your workflows: what starts them, how their last run ended, and when they run next.',\n name: 'Workflow',\n trigger: 'Starts',\n triggers: {\n manual: 'By hand',\n after: 'After a task',\n event: 'On an event',\n schedule: 'On a schedule',\n once: 'Once',\n },\n active: 'On',\n lastRun: 'Last run',\n lastResult: 'Last result',\n results: {\n completed: 'Success',\n success: 'Success',\n failed: 'Failed',\n running: 'In progress',\n awaiting_authorization: 'Awaiting access',\n },\n nextRun: 'Next run',\n owner: 'Owner',\n shared: 'Shared',\n created: 'Created',\n}\n\nfunction triggerOf(w: WorkflowResponse): Trigger {\n if (w.on_demand) return 'manual'\n if (w.after_conversation_ext_id) return 'after'\n if (w.event_kind) return 'event'\n if (w.rrule) return 'schedule'\n if (w.run_at) return 'once'\n return 'manual'\n}\n\nexport function createWorkflowsSource(labels?: Partial<WorkflowsSourceLabels>): DataSource {\n const l = { ...DEFAULT_WORKFLOWS_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'name', label: l.name, type: 'string' },\n { id: 'trigger', label: l.trigger, type: 'string', options: Object.values(l.triggers) },\n { id: 'active', label: l.active, type: 'boolean' },\n { id: 'lastRun', label: l.lastRun, type: 'date' },\n { id: 'lastResult', label: l.lastResult, type: 'string' },\n { id: 'nextRun', label: l.nextRun, type: 'date' },\n { id: 'owner', label: l.owner, type: 'string' },\n { id: 'shared', label: l.shared, type: 'boolean' },\n { id: 'created', label: l.created, type: 'date' },\n ]\n return defineRowsSource({\n id: 'workflows',\n scope: 'workspace',\n label: l.source,\n description: l.description,\n useFields: staticFields(fields),\n useRows(_params, enabled) {\n const on = useFeature('workflows')\n const workspaceId = useArbiSessionState((s) => s.workspaceId)\n const query = useWorkflows({ enabled: enabled && on })\n const nameOf = useNames(enabled)\n const rows = useMemo(\n () =>\n query.data\n ?.filter((w) => !!workspaceId && w.workspace_ext_id === workspaceId)\n .map((w): DatasetRow => {\n const result = w.last_run_status\n return {\n name: w.name,\n trigger: l.triggers[triggerOf(w)],\n active: w.active,\n lastRun: w.last_fired_at ?? null,\n lastResult: result ? (l.results[result] ?? result.replaceAll('_', ' ')) : null,\n nextRun: w.next_fire_at ?? null,\n owner: nameOf(w.owner_ext_id),\n shared: w.shared,\n created: w.created_at,\n }\n }),\n [query.data, nameOf, workspaceId]\n )\n return { rows, isLoading: enabled && on && query.isPending, error: query.error }\n },\n })\n}\n"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AAAA,IACjF;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -56,7 +56,7 @@ function createWorkspacesSource(labels) {
56
56
  shared: w.is_public ?? null
57
57
  }));
58
58
  }, [workspaces.data, projects.data]);
59
- return { rows, isLoading: workspaces.isLoading, error: workspaces.error };
59
+ return { rows, isLoading: enabled && workspaces.isPending, error: workspaces.error };
60
60
  }
61
61
  });
62
62
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/datasets/sources/workspaces.ts"],
4
- "sourcesContent": ["/**\n * The workspaces the user can see as a dataset: a row per workspace with its project, how many\n * documents, threads and members it has, and its stored files. Documents or storage by workspace or\n * by project are a group-by and a sum away. Reads the shared lists (`useWorkspaces`, `useProjects`).\n */\nimport { useMemo } from 'react'\nimport { useProjects, useWorkspaces } from '../../hooks'\nimport { defineRowsSource, staticFields } from '../rows-source'\nimport type { DataSource, DatasetField, DatasetRow } from '../types'\n\nexport interface WorkspacesSourceLabels {\n source: string\n description: string\n name: string\n project: string\n documents: string\n threads: string\n members: string\n storage: string\n created: string\n updated: string\n shared: string\n}\n\nexport const DEFAULT_WORKSPACES_SOURCE_LABELS: WorkspacesSourceLabels = {\n source: 'Workspaces',\n description: 'Your workspaces: their project, documents, threads, members and storage.',\n name: 'Workspace',\n project: 'Project',\n documents: 'Documents',\n threads: 'Threads',\n members: 'Members',\n storage: 'Storage (MB)',\n created: 'Created',\n updated: 'Updated',\n shared: 'Public',\n}\n\ninterface WorkspaceLike {\n external_id: string\n name: string\n project_ext_id?: string | null\n shared_document_count?: number | null\n private_document_count?: number | null\n shared_conversation_count?: number | null\n private_conversation_count?: number | null\n users?: unknown[] | null\n user_files_mb?: number | null\n created_at?: string | null\n updated_at?: string | null\n is_public?: boolean | null\n}\n\nexport function createWorkspacesSource(labels?: Partial<WorkspacesSourceLabels>): DataSource {\n const l = { ...DEFAULT_WORKSPACES_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'name', label: l.name, type: 'string' },\n { id: 'project', label: l.project, type: 'string' },\n { id: 'documents', label: l.documents, type: 'number' },\n { id: 'threads', label: l.threads, type: 'number' },\n { id: 'members', label: l.members, type: 'number' },\n { id: 'storage', label: l.storage, type: 'number', unit: 'MB' },\n { id: 'created', label: l.created, type: 'date' },\n { id: 'updated', label: l.updated, type: 'date' },\n { id: 'shared', label: l.shared, type: 'boolean' },\n ]\n return defineRowsSource({\n id: 'workspaces',\n label: l.source,\n description: l.description,\n useFields: staticFields(fields),\n useRows(_params, enabled) {\n const workspaces = useWorkspaces({ enabled })\n const projects = useProjects({ enabled })\n const rows = useMemo(() => {\n const list = workspaces.data as WorkspaceLike[] | undefined\n if (!list) return undefined\n const projectNames = new Map(\n ((projects.data ?? []) as Array<{ external_id: string; name: string }>).map((p) => [\n p.external_id,\n p.name,\n ])\n )\n return list.map((w): DatasetRow => ({\n name: w.name,\n project: w.project_ext_id ? (projectNames.get(w.project_ext_id) ?? null) : null,\n documents: (w.shared_document_count ?? 0) + (w.private_document_count ?? 0),\n threads: (w.shared_conversation_count ?? 0) + (w.private_conversation_count ?? 0),\n members: w.users?.length ?? 0,\n storage: Math.round((w.user_files_mb ?? 0) * 10) / 10,\n created: w.created_at ?? null,\n updated: w.updated_at ?? null,\n shared: w.is_public ?? null,\n }))\n }, [workspaces.data, projects.data])\n return { rows, isLoading: workspaces.isLoading, error: workspaces.error }\n },\n })\n}\n"],
5
- "mappings": "AAKA,SAAS,eAAe;AACxB,SAAS,aAAa,qBAAqB;AAC3C,SAAS,kBAAkB,oBAAoB;AAiBxC,MAAM,mCAA2D;AAAA,EACtE,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EACX,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AACV;AAiBO,SAAS,uBAAuB,QAAsD;AAC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AAAA,UAC3E,YAAY,EAAE,yBAAyB,MAAM,EAAE,0BAA0B;AAAA,UACzE,UAAU,EAAE,6BAA6B,MAAM,EAAE,8BAA8B;AAAA,UAC/E,SAAS,EAAE,OAAO,UAAU;AAAA,UAC5B,SAAS,KAAK,OAAO,EAAE,iBAAiB,KAAK,EAAE,IAAI;AAAA,UACnD,SAAS,EAAE,cAAc;AAAA,UACzB,SAAS,EAAE,cAAc;AAAA,UACzB,QAAQ,EAAE,aAAa;AAAA,QACzB,EAAE;AAAA,MACJ,GAAG,CAAC,WAAW,MAAM,SAAS,IAAI,CAAC;AACnC,aAAO,EAAE,MAAM,WAAW,WAAW,WAAW,OAAO,WAAW,MAAM;AAAA,IAC1E;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["/**\n * The workspaces the user can see as a dataset: a row per workspace with its project, how many\n * documents, threads and members it has, and its stored files. Documents or storage by workspace or\n * by project are a group-by and a sum away. Reads the shared lists (`useWorkspaces`, `useProjects`).\n */\nimport { useMemo } from 'react'\nimport { useProjects, useWorkspaces } from '../../hooks'\nimport { defineRowsSource, staticFields } from '../rows-source'\nimport type { DataSource, DatasetField, DatasetRow } from '../types'\n\nexport interface WorkspacesSourceLabels {\n source: string\n description: string\n name: string\n project: string\n documents: string\n threads: string\n members: string\n storage: string\n created: string\n updated: string\n shared: string\n}\n\nexport const DEFAULT_WORKSPACES_SOURCE_LABELS: WorkspacesSourceLabels = {\n source: 'Workspaces',\n description: 'Your workspaces: their project, documents, threads, members and storage.',\n name: 'Workspace',\n project: 'Project',\n documents: 'Documents',\n threads: 'Threads',\n members: 'Members',\n storage: 'Storage (MB)',\n created: 'Created',\n updated: 'Updated',\n shared: 'Public',\n}\n\ninterface WorkspaceLike {\n external_id: string\n name: string\n project_ext_id?: string | null\n shared_document_count?: number | null\n private_document_count?: number | null\n shared_conversation_count?: number | null\n private_conversation_count?: number | null\n users?: unknown[] | null\n user_files_mb?: number | null\n created_at?: string | null\n updated_at?: string | null\n is_public?: boolean | null\n}\n\nexport function createWorkspacesSource(labels?: Partial<WorkspacesSourceLabels>): DataSource {\n const l = { ...DEFAULT_WORKSPACES_SOURCE_LABELS, ...labels }\n const fields: DatasetField[] = [\n { id: 'name', label: l.name, type: 'string' },\n { id: 'project', label: l.project, type: 'string' },\n { id: 'documents', label: l.documents, type: 'number' },\n { id: 'threads', label: l.threads, type: 'number' },\n { id: 'members', label: l.members, type: 'number' },\n { id: 'storage', label: l.storage, type: 'number', unit: 'MB' },\n { id: 'created', label: l.created, type: 'date' },\n { id: 'updated', label: l.updated, type: 'date' },\n { id: 'shared', label: l.shared, type: 'boolean' },\n ]\n return defineRowsSource({\n id: 'workspaces',\n label: l.source,\n description: l.description,\n useFields: staticFields(fields),\n useRows(_params, enabled) {\n const workspaces = useWorkspaces({ enabled })\n const projects = useProjects({ enabled })\n const rows = useMemo(() => {\n const list = workspaces.data as WorkspaceLike[] | undefined\n if (!list) return undefined\n const projectNames = new Map(\n ((projects.data ?? []) as Array<{ external_id: string; name: string }>).map((p) => [\n p.external_id,\n p.name,\n ])\n )\n return list.map((w): DatasetRow => ({\n name: w.name,\n project: w.project_ext_id ? (projectNames.get(w.project_ext_id) ?? null) : null,\n documents: (w.shared_document_count ?? 0) + (w.private_document_count ?? 0),\n threads: (w.shared_conversation_count ?? 0) + (w.private_conversation_count ?? 0),\n members: w.users?.length ?? 0,\n storage: Math.round((w.user_files_mb ?? 0) * 10) / 10,\n created: w.created_at ?? null,\n updated: w.updated_at ?? null,\n shared: w.is_public ?? null,\n }))\n }, [workspaces.data, projects.data])\n return { rows, isLoading: enabled && workspaces.isPending, error: workspaces.error }\n },\n })\n}\n"],
5
+ "mappings": "AAKA,SAAS,eAAe;AACxB,SAAS,aAAa,qBAAqB;AAC3C,SAAS,kBAAkB,oBAAoB;AAiBxC,MAAM,mCAA2D;AAAA,EACtE,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,MAAM;AAAA,EACN,SAAS;AAAA,EACT,WAAW;AAAA,EAC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H;AACA,eAAO,KAAK,IAAI,CAAC,OAAmB;AAAA,UAClC,MAAM,EAAE;AAAA,UACR,SAAS,EAAE,iBAAkB,aAAa,IAAI,EAAE,cAAc,KAAK,OAAQ;AAAA,UAC3E,YAAY,EAAE,yBAAyB,MAAM,EAAE,0BAA0B;AAAA,UACzE,UAAU,EAAE,6BAA6B,MAAM,EAAE,8BAA8B;AAAA,UAC/E,SAAS,EAAE,OAAO,UAAU;AAAA,UAC5B,SAAS,KAAK,OAAO,EAAE,iBAAiB,KAAK,EAAE,IAAI;AAAA,UACnD,SAAS,EAAE,cAAc;AAAA,UACzB,SAAS,EAAE,cAAc;AAAA,UACzB,QAAQ,EAAE,aAAa;AAAA,QACzB,EAAE;AAAA,MACJ,GAAG,CAAC,WAAW,MAAM,SAAS,IAAI,CAAC;AACnC,aAAO,EAAE,MAAM,WAAW,WAAW,WAAW,WAAW,OAAO,WAAW,MAAM;AAAA,IACrF;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/datasets/types.ts"],
4
- "sourcesContent": ["/**\n * Datasets: the one shape every chart and dashboard reads, whatever the data comes from.\n *\n * Three layers, each knowing only the one below it:\n * 1. A `DataSource` adapter (AI usage, documents, threads, projects, a database, later an external\n * feed) exposes its data as a normalized `Dataset`: typed fields and plain rows. Filtering,\n * grouping and aggregation happen here (`aggregateDataset`, or on the server where the backend\n * can, as a database does), never in a chart.\n * 2. A `ChartSpec` (inside a `PanelSpec`, inside a `DashboardSpec`) says what to show in terms of\n * field ids only: the chart type, x / series / y fields, the aggregate, sort and limit. It is\n * plain JSON, saved in dashboards and studio pages.\n * 3. A renderer (`@arbidocs/blocks/dashboards`) maps a spec plus the aggregated dataset onto the\n * drawing component. No renderer type appears here, so the renderer stays swappable.\n */\n\n/** A field's value type. Dates are ISO strings (`2026-06-12` or a full timestamp). */\nexport type DatasetFieldType = 'string' | 'number' | 'date' | 'boolean'\n\n/** One column of a dataset. */\nexport interface DatasetField {\n /** Stable id: what specs and rows use. */\n id: string\n /** What people read (a column name, \"Status\"). */\n label: string\n type: DatasetFieldType\n /**\n * The unit of a number field, which picks its formatting: `gbp` (\u00A3), `bytes`, `tokens`, or any\n * suffix (`\"MB\"`, `\"%\"`).\n */\n unit?: string\n /** The values a string field takes, when known (a select column's options), for a filter picker. */\n options?: readonly string[]\n /** A string field whose cell holds several values (tags, linked rows): a row counts in each. */\n multiple?: boolean\n}\n\n/** A cell: a scalar, `null` when empty, or a list for a `multiple` field. */\nexport type DatasetValue = string | number | boolean | null | readonly string[]\n\n/** One row, keyed by field id. */\nexport type DatasetRow = Readonly<Record<string, DatasetValue | undefined>>\n\n/** A normalized dataset: typed fields and the rows. */\nexport interface Dataset {\n fields: readonly DatasetField[]\n rows: readonly DatasetRow[]\n /** Rows matched before grouping (after filters). */\n totalRows?: number\n /** More groups existed than the query's `limit`. */\n truncated?: boolean\n}\n\n/** How a date field is grouped. Keys: `2026-06-12`, `2026-W24`, `2026-06`, `2026-Q2`, `2026`. */\nexport type TimeBucket = 'day' | 'week' | 'month' | 'quarter' | 'year'\n\nexport type AggregateOp = 'count' | 'sum' | 'avg' | 'min' | 'max'\n\nexport type FilterOp =\n 'eq' | 'neq' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'empty' | 'not_empty'\n\n/** Keep rows whose `field` satisfies `op value` (compared in the field's type). */\nexport interface DatasetFilter {\n field: string\n op: FilterOp\n value?: string | number | boolean | null\n}\n\n/** How the groups are ordered: by label (dates: chronological), or by value. */\nexport type DatasetSort = 'label' | 'value-desc' | 'value-asc'\n\n/** How records are ordered: by a field (empty cells last). */\nexport interface DatasetOrder {\n field: string\n /** Default `asc`. */\n direction?: 'asc' | 'desc'\n}\n\n/**\n * What to read of a source. Grouped (the default): the (filtered) rows grouped and each group\n * measured, a dataset in long form with the fields {@link AGGREGATE_FIELDS}, one row per group (and\n * series). With `records`: the matching rows themselves, ordered by `orderBy` and cut at `limit`.\n */\nexport interface DatasetQuery {\n /** List the matching records instead of grouping them (`groupBy`, `splitBy`, `measure` unused). */\n records?: boolean\n /** The order of the records. */\n orderBy?: DatasetOrder\n filters?: readonly DatasetFilter[]\n /** The field whose values (or date buckets) are the groups. Absent: one group, \"All\". */\n groupBy?: string\n /** The bucket of a date `groupBy` / `splitBy`. Default `month`. */\n bucket?: TimeBucket\n /** A second field: one series per value (a stacked or multi-line chart). */\n splitBy?: string\n /** Default: count rows. `count` with a `field` counts the rows where it is not empty. */\n measure?: { op: AggregateOp; field?: string }\n /** Default: dates chronological, others by value, largest first. */\n sort?: DatasetSort\n /** Most groups kept (by value), or records listed. Default 50 groups; every record. */\n limit?: number\n}\n\n/** The field ids of an aggregated dataset. */\nexport const AGGREGATE_FIELDS = {\n /** The group's label (\"Open\", \"2026-06\"). */\n group: 'group',\n /** The group's key as grouped (a date bucket, an id), for ordering and links. */\n key: 'key',\n /** The series' label (only with `splitBy`). */\n series: 'series',\n /** The measured value; `null` when the group has no value to measure. */\n value: 'value',\n} as const\n\n/** A dataset (or a source's fields) as a hook reads it. */\nexport interface DatasetState {\n dataset: Dataset | undefined\n isLoading: boolean\n error: unknown\n}\n\nexport interface DataSourceFieldsState {\n fields: readonly DatasetField[]\n isLoading: boolean\n error: unknown\n}\n\n/** A source's parameters as saved in a panel (a database id, a period). */\nexport type DataSourceParams = Readonly<\n Record<string, string | number | boolean | null | undefined>\n>\n\n/** A choice for a parameter (an option of a select). */\nexport interface DataSourceOption {\n value: string\n label: string\n /** Other parameters set with this choice (a database's workspace, so a panel reads it anywhere). */\n params?: DataSourceParams\n}\n\n/** A parameter the panel editor asks for, before the source's fields are known. */\nexport interface DataSourceParam {\n id: string\n label: string\n /** Absent: the parameter may be left empty. */\n required?: boolean\n /** Shown when nothing is chosen (\"All columns\"). */\n placeholder?: string\n /** The choices, read live (databases of the open workspace; a database's saved views). */\n useOptions: (params: DataSourceParams) => {\n options: readonly DataSourceOption[]\n isLoading: boolean\n }\n}\n\n/**\n * A data source adapter: where a dataset comes from.\n *\n * `useFields` and `useDataset` are hooks. A caller renders them from a component keyed by the\n * source id, so switching source mounts afresh (the hooks differ between sources).\n *\n * Extension point: an external source (an HTTP/JSON API, a CSV feed, a warehouse) is one more\n * adapter. It reads its rows however it likes (its own `useQuery`) and returns them as a `Dataset`;\n * `defineRowsSource` aggregates them for it. A host lists it in `<ArbiHost config={{ dashboards:\n * { sources } }}>` and every editor, panel and studio block offers it. Fetching third-party URLs\n * from the browser is the host's decision (CORS, credentials, what a shared dashboard may reach),\n * so none is built in; data to chart today is imported into a database (CSV / spreadsheet import).\n */\nexport interface DataSource {\n id: string\n label: string\n description?: string\n /** `workspace`: it reads the open workspace's data (documents, threads\u2026), so it shows nothing until\n * one is open; a function decides from the panel's parameters (a database panel that does not name\n * its workspace). Absent: it is the person's own or names what it reads (AI usage). */\n scope?: 'workspace' | ((params: DataSourceParams) => 'workspace' | undefined)\n params?: readonly DataSourceParam[]\n /** The fields a panel can use, given the parameters. */\n useFields: (params: DataSourceParams) => DataSourceFieldsState\n /**\n * The dataset: grouped and measured (long form with {@link AGGREGATE_FIELDS}), or the records\n * (`query.records`), filtered either way.\n */\n useDataset: (\n params: DataSourceParams,\n query: DatasetQuery,\n options?: { enabled?: boolean }\n ) => DatasetState\n}\n\n// \u2500\u2500 Specs: what a panel shows (plain JSON) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** How a panel draws its data. `metric` is one number; `table` a table of rows or groups. */\nexport type ChartType = 'metric' | 'bar' | 'line' | 'area' | 'pie' | 'donut' | 'table'\n\n/** What to show, in terms of the dataset's field ids. Serialisable. */\nexport interface ChartSpec {\n type: ChartType\n /** The category or date field along the x axis (pie slices; table groups). */\n x?: string\n /** The bucket of a date `x`. Default `month`. */\n bucket?: TimeBucket\n /** A field whose values become the series (stacked bars or areas, several lines). */\n series?: string\n /** The number field the aggregate reads (absent: rows are counted). */\n y?: string\n /** Default `count`. */\n aggregate?: AggregateOp\n sort?: DatasetSort\n limit?: number\n /** Stack the series (bar, area). */\n stacked?: boolean\n filters?: readonly DatasetFilter[]\n /** A table of records (no aggregate): the fields shown, in order. Absent: every field. */\n columns?: readonly string[]\n /** A table of records: their order. */\n orderBy?: DatasetOrder\n}\n\n/** The source a panel reads, by registry id, with its parameters. */\nexport interface DataSourceRef {\n id: string\n params?: DataSourceParams\n}\n\n/** One panel of a dashboard. */\nexport interface PanelSpec {\n id: string\n title: string\n description?: string\n source: DataSourceRef\n chart: ChartSpec\n /** Columns of the 12-column grid it spans on a wide screen (it is full width on a phone). */\n width?: number\n}\n\n/** A dashboard: a titled grid of panels. Plain JSON (`version` for later migrations). */\nexport interface DashboardSpec {\n version: 1\n title: string\n description?: string\n panels: readonly PanelSpec[]\n}\n"],
4
+ "sourcesContent": ["/**\n * Datasets: the one shape every chart and dashboard reads, whatever the data comes from.\n *\n * Three layers, each knowing only the one below it:\n * 1. A `DataSource` adapter (AI usage, documents, threads, projects, a database, later an external\n * feed) exposes its data as a normalized `Dataset`: typed fields and plain rows. Filtering,\n * grouping and aggregation happen here (`aggregateDataset`, or on the server where the backend\n * can, as a database does), never in a chart.\n * 2. A `ChartSpec` (inside a `PanelSpec`, inside a `DashboardSpec`) says what to show in terms of\n * field ids only: the chart type, x / series / y fields, the aggregate, sort and limit. It is\n * plain JSON, saved in dashboards and studio pages.\n * 3. A renderer (`@arbidocs/blocks/dashboards`) maps a spec plus the aggregated dataset onto the\n * drawing component. No renderer type appears here, so the renderer stays swappable.\n */\n\n/** A field's value type. Dates are ISO strings (`2026-06-12` or a full timestamp). */\nexport type DatasetFieldType = 'string' | 'number' | 'date' | 'boolean'\n\n/** One column of a dataset. */\nexport interface DatasetField {\n /** Stable id: what specs and rows use. */\n id: string\n /** What people read (a column name, \"Status\"). */\n label: string\n type: DatasetFieldType\n /**\n * The unit of a number field, which picks its formatting: `gbp` (\u00A3), `bytes`, `tokens`, or any\n * suffix (`\"MB\"`, `\"%\"`).\n */\n unit?: string\n /** The values a string field takes, when known (a select column's options), for a filter picker. */\n options?: readonly string[]\n /** A string field whose cell holds several values (tags, linked rows): a row counts in each. */\n multiple?: boolean\n}\n\n/** A cell: a scalar, `null` when empty, or a list for a `multiple` field. */\nexport type DatasetValue = string | number | boolean | null | readonly string[]\n\n/** One row, keyed by field id. */\nexport type DatasetRow = Readonly<Record<string, DatasetValue | undefined>>\n\n/** A normalized dataset: typed fields and the rows. */\nexport interface Dataset {\n fields: readonly DatasetField[]\n rows: readonly DatasetRow[]\n /** Rows matched before grouping (after filters). */\n totalRows?: number\n /** More groups existed than the query's `limit`. */\n truncated?: boolean\n}\n\n/** How a date field is grouped. Keys: `2026-06-12`, `2026-W24`, `2026-06`, `2026-Q2`, `2026`. */\nexport type TimeBucket = 'day' | 'week' | 'month' | 'quarter' | 'year'\n\nexport type AggregateOp = 'count' | 'sum' | 'avg' | 'min' | 'max'\n\nexport type FilterOp =\n 'eq' | 'neq' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'empty' | 'not_empty'\n\n/** Keep rows whose `field` satisfies `op value` (compared in the field's type). */\nexport interface DatasetFilter {\n field: string\n op: FilterOp\n value?: string | number | boolean | null\n}\n\n/** How the groups are ordered: by label (dates: chronological), or by value. */\nexport type DatasetSort = 'label' | 'value-desc' | 'value-asc'\n\n/** How records are ordered: by a field (empty cells last). */\nexport interface DatasetOrder {\n field: string\n /** Default `asc`. */\n direction?: 'asc' | 'desc'\n}\n\n/**\n * What to read of a source. Grouped (the default): the (filtered) rows grouped and each group\n * measured, a dataset in long form with the fields {@link AGGREGATE_FIELDS}, one row per group (and\n * series). With `records`: the matching rows themselves, ordered by `orderBy` and cut at `limit`.\n */\nexport interface DatasetQuery {\n /** List the matching records instead of grouping them (`groupBy`, `splitBy`, `measure` unused). */\n records?: boolean\n /** The order of the records. */\n orderBy?: DatasetOrder\n filters?: readonly DatasetFilter[]\n /** The field whose values (or date buckets) are the groups. Absent: one group, \"All\". */\n groupBy?: string\n /** The bucket of a date `groupBy` / `splitBy`. Default `month`. */\n bucket?: TimeBucket\n /** A second field: one series per value (a stacked or multi-line chart). */\n splitBy?: string\n /** Default: count rows. `count` with a `field` counts the rows where it is not empty. */\n measure?: { op: AggregateOp; field?: string }\n /** Default: dates chronological, others by value, largest first. */\n sort?: DatasetSort\n /** Most groups kept (by value), or records listed. Default 50 groups; every record. */\n limit?: number\n}\n\n/** The field ids of an aggregated dataset. */\nexport const AGGREGATE_FIELDS = {\n /** The group's label (\"Open\", \"2026-06\"). */\n group: 'group',\n /** The group's key as grouped (a date bucket, an id), for ordering and links. */\n key: 'key',\n /** The series' label (only with `splitBy`). */\n series: 'series',\n /** The measured value; `null` when the group has no value to measure. */\n value: 'value',\n} as const\n\n/** A dataset (or a source's fields) as a hook reads it. */\nexport interface DatasetState {\n dataset: Dataset | undefined\n /**\n * No dataset yet, and one is coming: a read in flight or still waiting to start (the workspace\n * opening, a saved view being read first). A panel says \"Loading\u2026\" then, never \"nothing to show\".\n */\n isLoading: boolean\n error: unknown\n}\n\nexport interface DataSourceFieldsState {\n fields: readonly DatasetField[]\n isLoading: boolean\n error: unknown\n}\n\n/** A source's parameters as saved in a panel (a database id, a period). */\nexport type DataSourceParams = Readonly<\n Record<string, string | number | boolean | null | undefined>\n>\n\n/** A choice for a parameter (an option of a select). */\nexport interface DataSourceOption {\n value: string\n label: string\n /** Other parameters set with this choice (a database's workspace, so a panel reads it anywhere). */\n params?: DataSourceParams\n}\n\n/** A parameter the panel editor asks for, before the source's fields are known. */\nexport interface DataSourceParam {\n id: string\n label: string\n /** Absent: the parameter may be left empty. */\n required?: boolean\n /** Shown when nothing is chosen (\"All columns\"). */\n placeholder?: string\n /** The choices, read live (databases of the open workspace; a database's saved views). */\n useOptions: (params: DataSourceParams) => {\n options: readonly DataSourceOption[]\n isLoading: boolean\n }\n}\n\n/**\n * A data source adapter: where a dataset comes from.\n *\n * `useFields` and `useDataset` are hooks. A caller renders them from a component keyed by the\n * source id, so switching source mounts afresh (the hooks differ between sources).\n *\n * Extension point: an external source (an HTTP/JSON API, a CSV feed, a warehouse) is one more\n * adapter. It reads its rows however it likes (its own `useQuery`) and returns them as a `Dataset`;\n * `defineRowsSource` aggregates them for it. A host lists it in `<ArbiHost config={{ dashboards:\n * { sources } }}>` and every editor, panel and studio block offers it. Fetching third-party URLs\n * from the browser is the host's decision (CORS, credentials, what a shared dashboard may reach),\n * so none is built in; data to chart today is imported into a database (CSV / spreadsheet import).\n */\nexport interface DataSource {\n id: string\n label: string\n description?: string\n /** `workspace`: it reads the open workspace's data (documents, threads\u2026), so it shows nothing until\n * one is open; a function decides from the panel's parameters (a database panel that does not name\n * its workspace). Absent: it is the person's own or names what it reads (AI usage). */\n scope?: 'workspace' | ((params: DataSourceParams) => 'workspace' | undefined)\n params?: readonly DataSourceParam[]\n /** The fields a panel can use, given the parameters. */\n useFields: (params: DataSourceParams) => DataSourceFieldsState\n /**\n * The dataset: grouped and measured (long form with {@link AGGREGATE_FIELDS}), or the records\n * (`query.records`), filtered either way.\n */\n useDataset: (\n params: DataSourceParams,\n query: DatasetQuery,\n options?: { enabled?: boolean }\n ) => DatasetState\n}\n\n// \u2500\u2500 Specs: what a panel shows (plain JSON) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** How a panel draws its data. `metric` is one number; `table` a table of rows or groups. */\nexport type ChartType = 'metric' | 'bar' | 'line' | 'area' | 'pie' | 'donut' | 'table'\n\n/** What to show, in terms of the dataset's field ids. Serialisable. */\nexport interface ChartSpec {\n type: ChartType\n /** The category or date field along the x axis (pie slices; table groups). */\n x?: string\n /** The bucket of a date `x`. Default `month`. */\n bucket?: TimeBucket\n /** A field whose values become the series (stacked bars or areas, several lines). */\n series?: string\n /** The number field the aggregate reads (absent: rows are counted). */\n y?: string\n /** Default `count`. */\n aggregate?: AggregateOp\n sort?: DatasetSort\n limit?: number\n /** Stack the series (bar, area). */\n stacked?: boolean\n filters?: readonly DatasetFilter[]\n /** A table of records (no aggregate): the fields shown, in order. Absent: every field. */\n columns?: readonly string[]\n /** A table of records: their order. */\n orderBy?: DatasetOrder\n}\n\n/** The source a panel reads, by registry id, with its parameters. */\nexport interface DataSourceRef {\n id: string\n params?: DataSourceParams\n}\n\n/** One panel of a dashboard. */\nexport interface PanelSpec {\n id: string\n title: string\n description?: string\n source: DataSourceRef\n chart: ChartSpec\n /** Columns of the 12-column grid it spans on a wide screen (it is full width on a phone). */\n width?: number\n}\n\n/** A dashboard: a titled grid of panels. Plain JSON (`version` for later migrations). */\nexport interface DashboardSpec {\n version: 1\n title: string\n description?: string\n panels: readonly PanelSpec[]\n}\n"],
5
5
  "mappings": "AAuGO,MAAM,mBAAmB;AAAA;AAAA,EAE9B,OAAO;AAAA;AAAA,EAEP,KAAK;AAAA;AAAA,EAEL,QAAQ;AAAA;AAAA,EAER,OAAO;AACT;",
6
6
  "names": []
7
7
  }