@ahoo-wang/wow-view-engine 9.7.0 → 9.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["QueryModelDescriptor","AnalysisCapability","AnalysisSpec","FieldAnalysisSpec","Issue","OpenCapabilities","issue","describedAnalysis","BuiltField","analysisPlan","spec","fields","undefined","narrowed","entry","analysis","plan","NonNullable","elements","own","described","children","entries","Record","child","one","field","name","buildAnalysis","descriptor","findings","map","what","push","FieldDescriptor","QueryModelDescriptor","FieldDefinition","FieldKindId","FieldOption","Issue","PagingMode","issue","describedField","DescribedField","FieldSpec","OptionSpec","FieldBuild","descriptor","paging","findings","BuiltField","field","described","spec","sensitive","children","found","code","params","Record","severity","buildFields","listed","Readonly","scope","build","Object","entries","flatMap","key","given","label","built","buildField","path","undefined","search","searchField","push","raw","fieldDescriptor","canonical","kind","kindOf","name","labelOf","comparable","sorts","sort","cursor","paged","sortsByDefault","sortable","operators","offered","operatorsOffered","operator","has","summary","functions","aggregate","fn","includes","options","optionsOf","deprecated","message","elements","some","element","map","entry","elementTitle","cell","timePrecision","assign","more","fields","searchFields","mode","searchMode","own","find","relative","slice","length","variants","values","variant","aliases","enum","temporal","semantic","type","types","description","ReadonlySet","Set","filter","add","listedOptions","value","option","known","Map","String","said","get","Array","isArray","keys","Exclude","QueryModelDescriptor","DataViewDefinition","FieldDefinition","Issue","PagingMode","RecordCapability","issue","analysisPlan","buildAnalysis","buildFields","BuiltField","narrowDefinition","constructible","builtinFieldKinds","FieldKindRegistry","DefineViewSpec","defineView","descriptor","spec","options","DefineViewOptions","findings","record","recordOf","fields","undefined","paging","definition","id","title","kind","source","map","entry","field","recordNoun","fieldGroups","plan","analysis","timeField","views","sort","flatMap","given","described","sortable","name","operators","openComparisons","withSnapshotComparisons","kinds","Set","version","open","scope","children","path","own","narrowed","ReadonlySet","index","cut","next","has","elements","PAGING","Readonly","Record","PAGED","CURSOR","offered","mode","includes","push","rowKey","identity","layouts","ViewInstance","MemorySnapshot","MemoryState","LocalStorageSnapshotOptions","storage","getItem","key","setItem","value","events","addEventListener","type","listener","event","storageArea","removeEventListener","KeptStorage","ReturnType","NonNullable","localStorageSnapshot","options","ambientStorage","undefined","ambientEvents","load","parseState","save","state","JSON","stringify","subscribe","onStorage","readable","globalThis","localStorage","Error","target","Partial","saved","parse","Array","isArray","instances","preferences","filter","isHeld","instance","id","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","ViewStore","list","definitionId","signal","AbortSignal","Promise","get","id","create","input","Omit","context","WriteContext","save","config","revision","rename","title","delete","getPreferences","setPreferences","preferences","changeAudience","audience","permissions","ViewPermissions","requestId","createPersonal","createShared","reorder","setDefault","editSystem","instance","InstancePermissions","emptyPreferences","order","defaultInstanceId","audienceOf","configBytes","isSystemInstanceId","isSystemScope","MAX_VIEW_CONFIG_BYTES","MAX_VIEW_TITLE_LENGTH","titleProblem","toSummary","ViewStoreError","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","emptyPreferences","ViewPermissions","ViewStore","WriteContext","MemoryViewStoreOptions","instances","preferences","Record","permissions","definitionId","snapshot","MemorySnapshot","load","MemoryState","save","state","subscribe","listener","MemoryViewStore","Map","outcomes","preferenceOutcomes","sequence","constructor","options","restored","restore","reload","list","Promise","summaries","values","filter","instance","map","sort","a","b","AUDIENCE_RANK","scope","resolve","get","id","copy","reject","create","input","Omit","context","replayed","requestId","refused","titleRefusal","title","configRefusal","config","has","given","stored","trim","revision","const","set","commit","delete","update","current","rename","changeAudience","audience","boards","sharedBoardsShowing","length","join","readOnlySystem","conflict","expect","persist","getPreferences","setPreferences","held","next","nextRevision","change","changed","kind","panels","Array","isArray","some","panel","shows","push","undefined","undo","Object","fromEntries","error","reasonOf","storage","clear","entries","instanceId","owned","opens","click","Readonly","system","shared","personal","test","String","Number","bytes","name","message","value","T","structuredClone","VIEW_STORE_ERROR_CODES","isReferenceFilterValue","withOutOfScope","isSystemInstanceId","clampPage","isSafeContentUrl","removeAt","analysisProbeLimit","NUMERIC_TYPES","familyOf","ANALYSIS_DATE_DIFF_UNITS","validatePanelClick","createFieldKindRegistry","isGroupItem","metricMeasures","fieldAliasSegment","expressionFieldsOf","filterStoredValue","ViewCommandError","isFilterLeaf","DELETION_STATES","metricReferenceText","DEFAULT_TEMPORAL","withSmooth","CHART_TYPES","crossFilterChoices","mergeFilters","dateFieldKind","chartUnfit","FIELD_TONES","CHART_FAMILIES","METRIC_HEADLINES","takesGroup","isViewWriteError","isSimpleTree","isDeletionState","chartPickerGroups","FIELD_CELL_IDS","withStagesFrom","MAX_MOVING_WINDOW","setPanelClick","walkFilter","resolveDateTimeRange","formulaFormat","TEMPORAL_TYPES","DERIVED_FORMAT_STYLES","defaultFilters","readValue","MAX_RELATIVE_DATE_AMOUNT","innermostElement","numberFormatOf","maxSortFields","panelFilterTree","isKnownEditorInput","validateViewConfigBase","readsAsItsField","isFieldName","wallClockAt","isValueMetric","filtersOf","walkFilterShape","booleanFieldKind","metricFieldOf","TIME_PRECISIONS","FIELD_METRIC_TYPES","filterCondition","say","isDurationFilterValue","relativeFields","DEFAULT_APPROXIMATE_METRICS","pageSummaries","clicksFilter","withFieldKinds","RELATIVE_DATE_UNITS","outOfScopeNames","summaryFunctionsOf","validateRecord","bindingsOf","filterIndexes","arrayFieldKind","metricFormat","aggregationFunctionsOf","MAX_DERIVED_DECIMALS","filterControlValue","sameFilterNode","isValidTimeZone","compileAnalysis","STRING_COMPARISONS","seriesMark","ANALYSIS_DATE_UNITS","FILTER_TYPE_OPERATOR","sameFilterTree","periodOf","compileAnalysisTotals","SUMMARY_FUNCTIONS","valueLabelsOn","ANALYSIS_PRESENTATION_MEMBERS","ONE_DAY_PRESETS","negateAt","dateTimeFieldKind","fitCharts","MAX_NUMERIC_SCALE","PEAKS_ONLY_FROM","REFERENCE_STATISTICS","urlPlaceholders","updateAt","resolveDateTimeBound","TEMPORAL_FIELD_KIND_IDS","isAdditiveMetric","DATE_PART_DOMAINS","admitFilters","withText","unknownOrOutside","isApproximate","isPresentationMember","isRootFilterIssue","describeFilter","metricFunctionOf","currencyPathOf","dateDiffUnitsOf","filterEditor","isFilterGroup","variantGroups","isFormula","DEFAULT_STRING_COMPARISON","withSlot","CHART_FAMILY","boardValueChoices","isViewCommandError","isNegation","impliedDeletion","CHART_PICKER_ORDER","FIELDLESS_FIELD_KIND_IDS","withStageOrder","MAX_CHART_LEVELS","pressableGroups","issue","DATE_TIME_PRESETS","analysisScope","isFieldlessKind","freeAlias","isBlankFilterValue","isBlankLeafValue","validateDataConfigBase","momentMetrics","isDateCell","bucketRange","groupFieldsOf","filterValueIssues","operatorsOf","DURATION_COMPARISONS","elementFilterFields","isSingleStringField","groupKeyText","isOneDayValue","textKeyOf","isNumberRange","relativeTree","SYSTEM_INSTANCE_ID_SEPARATOR","projectSummaries","isContentPanel","text","relativeName","SYSTEM_INSTANCE_ID_PREFIX","projectRecord","isOrderedRange","scopePrefix","approximateMetrics","recordValue","isOwnedPanel","durationFrom","numberFieldKind","derivedText","isFilterGroupOperator","optionTabs","filterTypeOf","validateTimeGrouping","describePresence","tabsOf","nearestPageSize","DASHBOARD_FILTER_KINDS","describedField","insertAt","elementFields","formulaMetric","DATE_SUMMARY_FUNCTIONS","withMovedTo","CARTESIAN_MISSING","mergeGlobalFilter","compileRecord","validateChart","MAX_VIEW_TITLE_LENGTH","limitBounds","DASHBOARD_PRESENTATION_MEMBERS","coversScope","compileFilter","summaryAlias","projectAnalysis","audienceOf","MAX_DASHBOARD_TABS","addTab","isBlankFilter","cursorPaging","isViewPanel","ViewStoreError","parseSystemInstanceId","BUILTIN_FIELD_KINDS","rowCurrency","configBytes","isPercentStacked","MAX_HEADING_LENGTH","moveTab","countLeaves","referenceFieldKind","derivedMetric","FILTER_GROUP_OPERATORS","offersStacking","boardWidth","validateFilterFields","conditions","searchFieldKind","OPERATOR_SIGN","toSummary","offersPercentStack","PANEL_PRESENTATION_MEMBERS","validateTabs","compilePresence","pagedPaging","referencedInstance","MAX_TIMER_DELAY_MS","comboMark","columnPinned","constructible","removeConditionAt","asksForWhole","SEARCH_MODES","peaksOnlyLabels","ANALYSIS_DATE_PARTS","nodeAt","readInstant","shapeChart","METADATA_FIELD_KIND_IDS","chartMarks","ANALYSIS_AUTO_RUN_MEMBERS","validateBoardClick","compileSummaries","measureColumns","VIEW_AUDIENCES","DASHBOARD_WIDTHS","validateDashboard","conditionOf","stringFieldKind","EXPRESSION_OPERATORS","titleProblem","isStacked","MAX_PANEL_LINKS","renameTab","validateFilter","pageAfterShrink","panelsOf","isViewStoreError","RECORD_PRESENTATION_MEMBERS","narrowDefinition","describePresenceParts","validateAnalysis","CODE_REVISION","DASHBOARD_FILTER_TYPES","clearFilter","builtinFieldKinds","metricCondition","isSystemScope","isSmooth","MAX_MARKDOWN_LENGTH","removeTab","writeValue","isDateTimeFilterValue","qualify","temporalOf","cardField","clickOf","PRESENCE_OPERATORS","pageWindow","presentationMembersOf","DEFAULT_RUNTIME_LIMITS","comboAxis","columnHidden","describedAnalysis","actions","isPresenceOperator","FIRST_PAGE","isChartColor","MAX_VIEW_CONFIG_BYTES","DASHBOARD_GRID_COLUMNS","isExecutableFilter","lastPageInWindow","panelTab","periodRollover","systemInstanceId","recordProjection","momentColumns","VIEW_SCOPES","MAX_DASHBOARD_FILTERS","validateLayout","emptyFilter","METADATA_FIELD_KINDS","durationMetric","BUILTIN_FIELD_KIND_IDS","stacks","boardCondition","ViewWriteError","isFilterNode","deletionFieldKind","wordReferences","EPOCH_TIME_UNITS","withStacked","DERIVED_KINDS","fillUrl","validateDefinition","isEmptyFilter","elementMatchFieldKind","isDuration","DEFAULT_SEARCH_MODE","withPercentStack","CHART_COLOR_SLOTS","boardFilterChoices","filterFields","enumFieldKind","expressionText","CURRENCY_CODE_PATTERN","stageValues","sameFilterType","mapGlobalFilter","EDITOR_INPUTS","groupJoinWord","metricMeasure","epochUnitOf","datePartsOf","filterOperatorOf","setPresentation","leadMetric","setFilterMultiple","drillConditions","wireableFields","narrowsTo","addFilter","nextExpansion","renameFilter","withoutLevelsFrom","removeFixedScope","withLevel","autoBindings","duplicatePanel","firstMetric","addPanel","DEFAULT_PERCENTILE","bindPanel","focusOn","referToSaved","groupableFields","editContent","groupFacts","filterReach","groupFor","setFilterOptions","drillGroups","setFilterRequired","retypeFilter","setTimeGrouping","setBoardWidth","summaryOf","filtersOnTab","splitBy","defaultRuntimeEnvironment","levelLabel","removeFilter","withElements","compactTab","aliasOf","wiredOptions","DEFAULT_MISSING_KEY","defaultPanelSize","defaultAnalysisConfig","renamePanel","metricWithCondition","removePanel","metricOfSummary","replacePanelView","summaryChoices","VIEW_KINDS","havingRows","isRecordRuntime","valueCandidateField","freeSpot","recommendDateUnit","isExportCancelledError","valueCandidatesConfig","placePanel","defaultRecordConfig","reorderPanel","switchChartType","STACKED_COLUMNS","recordCapabilityOf","reorderPanelIn","unmarkedErrors","HAVING_OPERATORS","withRootSearch","emptyDashboardConfig","readValueCandidates","fitsGrid","setFilterOneDay","setFilterDefault","fitChartSlots","placePanelIn","searchFieldOf","withLayouts","hasResult","VALUE_CANDIDATE_OPERATORS","bottomOf","ExportCancelledError","valueCandidateLimit","grownLayout","rootSearch","stackedLayout","movePanelToTab","groupOfType","ViewEngine","narrowValueCandidates","compactLayout","valueCandidateNarrowing","overlaps","hasAsked","VALUE_CANDIDATE_LIMIT","arrangePanel","detailSections","readingOrder","autoRunMembers","withHavingRows","moveFilter","nextLevel","ALWAYS_VISIBLE","resultSpan","presentationMembers","rangeSpan","unbindPanels","drillFilter","draftedClick","valueSourceKey","CSV_BOM","serializeCsv","clickDraftOf","withBoard","fieldGroups","boardValueSources","mappedValues","clickDraftGaps","urlFillable","CLICK_GO_KINDS","bucketChange","analysisPlan","spec","narrowed","entry","plan","fields","own","entries","child","one","buildAnalysis","descriptor","findings","field","found","code","params","severity","buildFields","listed","key","given","built","buildField","scope","build","path","searchField","described","raw","fieldDescriptor","kind","kindOf","labelOf","comparable","sorts","sortsByDefault","offered","operatorsOffered","operator","functions","fn","options","optionsOf","children","element","search","name","relative","variants","variant","temporal","types","listedOptions","values","value","option","known","said","defineView","record","recordOf","definition","analysis","sort","operators","openComparisons","withSnapshotComparisons","cut","index","next","open","PAGING","mode","paging","localStorageSnapshot","storage","ambientStorage","events","ambientEvents","parseState","state","onStorage","event","readable","listener","target","saved","isHeld","instance","emptyPreferences","MemoryViewStore","restored","summaries","definitionId","AUDIENCE_RANK","a","b","id","copy","replayed","context","refused","titleRefusal","input","configRefusal","revision","current","config","title","audience","boards","readOnlySystem","conflict","held","preferences","nextRevision","changed","change","panels","shows","panel","undo","error","reasonOf","stored","owned","instanceId","opens","click","bytes","message"],"sources":["../src/runtime/define/analysis.ts","../src/runtime/define/fields.ts","../src/runtime/define/defineView.ts","../src/store/localStorageSnapshot.ts","../src/store/ViewStore.ts","../src/store/MemoryViewStore.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The analyses of a `defineView` definition: which fields analyse and how\n * the host narrows each is the host's (the plan, `OpenCapabilities`); what\n * each path offers is its source's. Built here over the snapshot — what a\n * source with no descriptor runs on — and read again over a source's own\n * descriptor when it narrows (`reopened`). A narrowing beyond what the\n * snapshot grants is a warning, not an error: another store may grant it.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport type {\n AnalysisCapability,\n AnalysisSpec,\n FieldAnalysisSpec,\n Issue,\n OpenCapabilities,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { describedAnalysis } from '../../capabilities/open.js';\nimport type { BuiltField } from './fields.js';\n\n/** Which fields analyse, and the host's narrowing of each; `undefined` for none. */\nexport function analysisPlan(\n spec: AnalysisSpec | false | undefined,\n fields: readonly BuiltField[],\n): OpenCapabilities['analysis'] {\n if (spec === false) return undefined;\n const narrowed = (entry: BuiltField): FieldAnalysisSpec | null =>\n entry.spec.analysis === false ? null : (entry.spec.analysis ?? {});\n const plan: NonNullable<OpenCapabilities['analysis']> = {\n spec: spec ?? {},\n fields: {},\n elements: {},\n };\n for (const entry of fields) {\n const own = entry.described ? narrowed(entry) : null;\n if (!own) continue;\n if (entry.children) {\n const entries: Record<string, FieldAnalysisSpec> = {};\n for (const child of entry.children) {\n const one = narrowed(child);\n if (one) entries[child.field.name] = one;\n }\n (plan.elements as Record<string, typeof entries>)[entry.field.name] =\n entries;\n } else\n (plan.fields as Record<string, FieldAnalysisSpec>)[entry.field.name] =\n own;\n }\n return plan;\n}\n\n/** The plan's analyses over the snapshot, what it asks beyond said as warnings. */\nexport function buildAnalysis(\n plan: OpenCapabilities['analysis'],\n fields: readonly BuiltField[],\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): AnalysisCapability | undefined {\n if (!plan) return undefined;\n return describedAnalysis(\n plan,\n fields.map(entry => entry.field),\n descriptor,\n (field, what) =>\n findings.push(\n field === null\n ? issue(\n 'definition.analysis.wider',\n ['analysis'],\n { what },\n 'warning',\n )\n : issue(\n 'definition.field.analysis-wider',\n ['analysis'],\n { field, what },\n 'warning',\n ),\n ),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A field as `defineView` builds it (host-integration.md 3): its kind, its\n * values and whether it sorts are the descriptor's; its label, its order,\n * its cell and what it narrows are the host's. The operators are left to\n * the kind unless the host narrows them — the engine cuts them to the\n * descriptor in force whenever a view runs (N5), so a list copied here\n * would only go stale.\n */\n\nimport type {\n FieldDescriptor,\n QueryModelDescriptor,\n} from '@ahoo-wang/wow-client';\nimport type {\n FieldDefinition,\n FieldKindId,\n FieldOption,\n Issue,\n PagingMode,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport {\n describedField,\n type DescribedField,\n} from '../../capabilities/match.js';\nimport type { FieldSpec, OptionSpec } from './spec.js';\n\n/** What building the fields reads, and where it says what it found. */\ninterface FieldBuild {\n descriptor: QueryModelDescriptor;\n paging: PagingMode;\n findings: Issue[];\n}\n\n/** One built field and what it is over, for the analyses to read. */\nexport interface BuiltField {\n field: FieldDefinition;\n described: DescribedField | null;\n spec: FieldSpec;\n /** Whether the value is sensitive: masked, so never grouped or measured. */\n sensitive: boolean;\n /** An array's entries, built as its fields are. */\n children?: BuiltField[];\n}\n\nconst found = (\n code: string,\n params: Record<string, string>,\n severity: Issue['severity'] = 'error',\n): Issue => issue(code, ['fields'], params, severity);\n\n/** The fields listed, built in the order listed; one the descriptor lacks is left out. */\nexport function buildFields(\n listed: Readonly<Record<string, FieldSpec | string>>,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField[] {\n return Object.entries(listed).flatMap(([key, given]) => {\n const spec: FieldSpec =\n typeof given === 'string' ? { label: given } : given;\n const built = buildField(key, spec, scope, build);\n return built ? [built] : [];\n });\n}\n\nfunction buildField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField | null {\n const { descriptor, findings } = build;\n const path = scope === undefined ? key : `${scope}.${key}`;\n if (spec.search) return searchField(key, spec, scope, build);\n\n const described = describedField(descriptor, path, scope);\n if (!described) {\n findings.push(found('definition.field.undescribed', { field: path }));\n return null;\n }\n const raw = fieldDescriptor(descriptor, described.canonical ?? path, scope);\n const kind = spec.kind ?? kindOf(raw, described, spec);\n if (kind === null) {\n findings.push(found('definition.field.kind-unknown', { field: path }));\n return null;\n }\n const field: FieldDefinition = {\n name: key,\n label: labelOf(spec, raw, path, findings),\n kind,\n };\n const comparable = described.comparable !== false;\n\n // An entry's field is read inside its record, not what records are\n // ordered by: offered as a sort only where the host asks.\n const sorts =\n comparable &&\n (build.paging === 'cursor' ? described.sort.cursor : described.sort.paged);\n const sortsByDefault = sorts && scope === undefined;\n if (spec.sortable === true && !sorts)\n findings.push(\n found('definition.field.sort-wider', { field: path }, 'warning'),\n );\n if (sorts && (spec.sortable ?? sortsByDefault)) field.sortable = true;\n\n if (spec.operators) {\n const offered = operatorsOffered(descriptor, described, path);\n for (const operator of spec.operators)\n if (!offered.has(operator))\n findings.push(\n found(\n 'definition.field.operator-wider',\n { field: path, operator },\n 'warning',\n ),\n );\n field.operators = spec.operators;\n } else if (!comparable) field.operators = [];\n\n if (spec.summary) {\n const functions: readonly string[] = described.aggregate?.functions ?? [];\n for (const fn of spec.summary)\n if (fn !== 'COUNT' && !functions.includes(fn))\n findings.push(\n found(\n 'definition.field.summary-wider',\n { field: path, fn },\n 'warning',\n ),\n );\n field.summary = spec.summary;\n }\n\n const options = optionsOf(spec, described, path, findings);\n if (options) field.options = options;\n\n if (described.deprecated) {\n if (!spec.deprecated)\n findings.push(\n found(\n 'definition.field.deprecated',\n { field: path, message: described.deprecated.message ?? '' },\n 'warning',\n ),\n );\n field.deprecated = spec.deprecated ?? described.deprecated;\n }\n\n let children: BuiltField[] | undefined;\n if (spec.elements) {\n if (!descriptor.elements.some(element => element.path === path))\n findings.push(found('definition.field.not-elements', { field: path }));\n children = buildFields(spec.elements, path, build);\n field.elements = children.map(entry => entry.field);\n }\n if (spec.elementTitle !== undefined) field.elementTitle = spec.elementTitle;\n if (spec.cell !== undefined) field.cell = spec.cell;\n if (spec.timePrecision !== undefined)\n field.timePrecision = spec.timePrecision;\n Object.assign(field, spec.more);\n return {\n field,\n described,\n spec,\n sensitive: described.sensitive === true,\n ...(children ? { children } : {}),\n };\n}\n\n/** A search box: its fields must be paths the descriptor has. */\nfunction searchField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField {\n const search = spec.search ?? { fields: [] };\n // An entry's search names its fields within the entry (N4).\n for (const name of search.fields) {\n const path = scope === undefined ? name : `${scope}.${name}`;\n if (!describedField(build.descriptor, path, scope))\n build.findings.push(\n found('definition.field.undescribed', { field: path }),\n );\n }\n const field: FieldDefinition = {\n name: key,\n label: spec.label ?? key,\n kind: 'search',\n searchFields: search.fields,\n };\n if (search.mode) field.searchMode = search.mode;\n return { field, described: null, spec, sensitive: false };\n}\n\n/** The descriptor's own entry for a path, for what `describedField` leaves out. */\nfunction fieldDescriptor(\n descriptor: QueryModelDescriptor,\n path: string,\n scope: string | undefined,\n): FieldDescriptor | undefined {\n const own = descriptor.fields.find(\n entry => entry.path === path && entry.scope === scope,\n );\n if (own || scope === undefined) return own;\n // A variant's fields are listed relative to the element, by path or alias,\n // as `describedField` reads them.\n const relative = path.slice(scope.length + 1);\n const variants = descriptor.variants;\n if (variants?.element !== scope) return undefined;\n return variants.values\n .flatMap(variant => variant.fields)\n .find(\n entry =>\n entry.path === relative || (entry.aliases ?? []).includes(relative),\n );\n}\n\n/** The kind the descriptor says a path is; `null` where it says none. */\nfunction kindOf(\n raw: FieldDescriptor | undefined,\n described: DescribedField,\n spec: FieldSpec,\n): FieldKindId | null {\n if (spec.elements) return 'elementMatch';\n if (described.enum || spec.options) return 'enum';\n const temporal = described.semantic?.type;\n if (temporal === 'TEMPORAL_DATE') return 'date';\n if (temporal === 'TEMPORAL_EPOCH' || temporal === 'TEMPORAL_FORMATTED')\n return 'datetime';\n const types: readonly string[] = raw?.types ?? [];\n if (types.length !== 1) return null;\n switch (types[0]) {\n case 'BOOLEAN':\n return 'boolean';\n case 'INTEGER':\n case 'DECIMAL':\n return 'number';\n case 'STRING':\n return 'string';\n default:\n return null;\n }\n}\n\n/**\n * The host's word, else the domain's description, else the path — the two\n * fallbacks said, since a reader would see a program's word.\n */\nfunction labelOf(\n spec: FieldSpec,\n raw: FieldDescriptor | undefined,\n path: string,\n findings: Issue[],\n): string {\n if (spec.label !== undefined) return spec.label;\n findings.push(found('definition.field.unlabelled', { field: path }, 'note'));\n return raw?.description ?? path;\n}\n\n/**\n * The comparisons a path admits: its own operators, and a match over its\n * entries where it is an element the model filters by (capabilities.md,\n * `ELEMENT_MATCH` comes from `elements[]`).\n */\nfunction operatorsOffered(\n descriptor: QueryModelDescriptor,\n described: DescribedField,\n path: string,\n): ReadonlySet<string> {\n const offered = new Set(described.operators);\n if (descriptor.elements.some(entry => entry.path === path && entry.filter))\n offered.add('ELEMENT_MATCH');\n return offered;\n}\n\n/**\n * A category's values: the host's listed first, in its order and words,\n * then the rest of the descriptor's under their descriptions; one the host\n * hides left out. Where the descriptor lists none the host's list is the\n * whole of it.\n */\nfunction optionsOf(\n spec: FieldSpec,\n described: DescribedField,\n path: string,\n findings: Issue[],\n): FieldOption[] | undefined {\n const listed = listedOptions(spec.options);\n const values = described.enum;\n if (!values)\n return spec.options\n ? listed.flatMap(([value, given]) =>\n given === false ? [] : [option(value, given)],\n )\n : undefined;\n const known = new Map(values.map(entry => [String(entry.value), entry]));\n const said = new Set<string>();\n const options: FieldOption[] = [];\n for (const [value, given] of listed) {\n const key = String(value);\n const entry = known.get(key);\n if (!entry) {\n findings.push(\n found('definition.option.undescribed', { field: path, value: key }),\n );\n continue;\n }\n said.add(key);\n if (given !== false) options.push(option(entry.value, given));\n }\n for (const entry of values)\n if (!said.has(String(entry.value)))\n options.push({\n value: entry.value as FieldOption['value'],\n label: entry.description ?? String(entry.value),\n });\n return options;\n}\n\n/**\n * The host's values in the order written: a list as it is, a record in its\n * own order — which JavaScript puts integer-like keys first in, so a\n * category of numbers is written as a list.\n */\nfunction listedOptions(\n given: FieldSpec['options'],\n): (readonly [unknown, OptionSpec])[] {\n if (!given) return [];\n if (Array.isArray(given)) return given as (readonly [unknown, OptionSpec])[];\n // Own keys only: a value named like a prototype member is a value.\n return Object.keys(given).map(key => [\n key,\n (given as Readonly<Record<string, OptionSpec>>)[key],\n ]);\n}\n\nfunction option(\n value: unknown,\n given: Exclude<OptionSpec, false>,\n): FieldOption {\n return typeof given === 'string'\n ? { value: value as FieldOption['value'], label: given }\n : { value: value as FieldOption['value'], ...given };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport type {\n DataViewDefinition,\n FieldDefinition,\n Issue,\n PagingMode,\n RecordCapability,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { analysisPlan, buildAnalysis } from './analysis.js';\nimport { buildFields, type BuiltField } from './fields.js';\nimport { narrowDefinition } from '../../capabilities/index.js';\nimport { constructible } from '../../capabilities/analysis.js';\nimport {\n builtinFieldKinds,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport type { DefineViewSpec } from './spec.js';\n\n/**\n * A data definition built from its source's descriptor (host-integration.md\n * 3, D67): the descriptor gives the facts — which paths there are, what\n * each is, what it sorts and feeds — as an upper bound, and `spec` picks,\n * names and narrows within it. A field not listed does not appear. A path\n * or a value the descriptor lacks is an error admission reports\n * (`DataViewDefinition.described`), never a throw: a definition wrong in\n * one place still loads, and says where. A capability asked beyond the\n * snapshot is a warning: what a path sorts and aggregates by is the\n * store's, and another store may grant it.\n *\n * Facts — paths, kinds, values, sensitivity, the entries of an array —\n * are the snapshot's. Capabilities are not baked in: where the host\n * narrows nothing the definition takes whatever its source grants, and\n * where it narrows, its subset of that (`DefinitionDescribed.open`,\n * filled by the narrowing from the source's descriptor). A source with\n * no descriptor runs on the snapshot's.\n *\n * `descriptor` is the snapshot committed beside the definition (Q2): the\n * definition is built at once, when the module loads, and a test builds\n * the same one. The descriptor the source answers at run time narrows it\n * again, as any definition is (N5).\n *\n * The result is an ordinary definition: nothing past this function knows\n * how it was written, and one written in full by hand is still one.\n */\nexport function defineView(\n descriptor: QueryModelDescriptor,\n spec: DefineViewSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const findings: Issue[] = [];\n const record = recordOf(spec, descriptor, findings);\n const fields = buildFields(spec.fields, undefined, {\n descriptor,\n paging: record?.paging ?? 'paged',\n findings,\n });\n const definition: DataViewDefinition = {\n id: spec.id,\n title: spec.title,\n kind: 'data',\n source: spec.source,\n fields: fields.map(entry => entry.field),\n };\n if (spec.recordNoun !== undefined) definition.recordNoun = spec.recordNoun;\n if (spec.fieldGroups) definition.fieldGroups = spec.fieldGroups;\n if (record) definition.record = record;\n const plan = analysisPlan(spec.analysis, fields);\n const analysis = buildAnalysis(plan, fields, descriptor, findings);\n // A snapshot with no metric at all offers no analyses; a source that\n // grants some fills them in (`reopened`) rather than the definition\n // being refused for one store's word.\n if (analysis && constructible(analysis)) definition.analysis = analysis;\n if (spec.timeField !== undefined) definition.timeField = spec.timeField;\n if (spec.views) definition.views = spec.views;\n // What compares, sorts and aggregates is the store's: left to the source\n // where the host did not narrow it, filled from its descriptor when it\n // narrows (`reopened`), the snapshot's written here for a source that\n // has none.\n const sort = fields.flatMap(({ field, spec: given, described }) =>\n described && given.sortable !== false ? [field.name] : [],\n );\n const operators = openComparisons(fields);\n definition.fields = withSnapshotComparisons(\n definition.fields,\n narrowDefinition(definition, descriptor, options.kinds ?? builtinFieldKinds)\n .definition.fields,\n new Set(operators),\n );\n definition.described = {\n version: descriptor.version,\n findings,\n open: { sort, operators, ...(plan ? { analysis: plan } : {}) },\n };\n return definition;\n}\n\n/**\n * The fields whose comparisons the host left open, by path: every field\n * but one whose operators the host wrote, one that compares nothing (a\n * confidential value), and a search box.\n */\nfunction openComparisons(\n fields: readonly BuiltField[],\n scope?: string,\n): string[] {\n return fields.flatMap(({ field, spec, children }) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n // A search box is the host's to ask for, as written operators are: on\n // a source with no descriptor it is offered as declared, and a source\n // that says whether it searches narrows it.\n const own =\n spec.operators === undefined &&\n field.operators === undefined &&\n field.kind !== 'search'\n ? [path]\n : [];\n return [...own, ...openComparisons(children ?? [], path)];\n });\n}\n\n/**\n * The fields with the snapshot's comparisons written on each one left\n * open: the operators the narrowing against it keeps on each path, so a\n * source with no descriptor offers what the snapshot's store does, and no\n * more.\n */\nfunction withSnapshotComparisons(\n fields: readonly FieldDefinition[],\n narrowed: readonly FieldDefinition[],\n open: ReadonlySet<string>,\n scope?: string,\n): FieldDefinition[] {\n return fields.map((field, index) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n const cut = narrowed[index];\n let next = field;\n if (open.has(path) && cut?.operators !== undefined)\n next = { ...next, operators: cut.operators };\n if (field.elements)\n next = {\n ...next,\n elements: withSnapshotComparisons(\n field.elements,\n cut?.elements ?? [],\n open,\n path,\n ),\n };\n return next;\n });\n}\n\n/**\n * What `defineView` needs beyond the snapshot and the host's choices: the\n * field kinds the host registers (`ViewEngineOptions.kinds`) — the snapshot's\n * comparisons are written on a field of a host's own kind only when its\n * kind is known here, since it is built before any engine is. Left out,\n * the built-in kinds.\n */\nexport interface DefineViewOptions {\n kinds?: FieldKindRegistry;\n}\n\n/** The descriptor's paging modes, as a definition names them. */\nconst PAGING: Readonly<Record<string, PagingMode>> = {\n PAGED: 'paged',\n CURSOR: 'cursor',\n};\n\n/**\n * Records: the host's choices over the descriptor's identity and paging —\n * paged where the model pages, else by cursor — shown as a table unless the\n * host says otherwise. A paging the model does not offer is asked beyond it.\n */\nfunction recordOf(\n spec: DefineViewSpec,\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): RecordCapability | undefined {\n if (spec.record === false) return undefined;\n const given = spec.record ?? {};\n const offered = descriptor.record.paging.flatMap(mode =>\n PAGING[mode] ? [PAGING[mode]] : [],\n );\n const paging =\n given.paging ?? (offered.includes('paged') ? 'paged' : 'cursor');\n if (!offered.includes(paging))\n findings.push(\n issue(\n 'definition.record.paging-wider',\n ['record', 'paging'],\n { paging },\n 'warning',\n ),\n );\n return {\n ...given,\n rowKey: given.rowKey ?? descriptor.record.identity,\n paging,\n layouts: given.layouts ?? ['table'],\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ViewInstance } from '../model/index.js';\nimport type { MemorySnapshot, MemoryState } from './MemoryViewStore.js';\n\n/**\n * Where a `localStorageSnapshot` reads and writes. Both are structural, so\n * this layer names no DOM type, and a test hands in a storage of its own.\n */\nexport interface LocalStorageSnapshotOptions {\n /**\n * The storage, asked for at each read and write rather than once, so a\n * browser that refuses it (private mode, blocked site data) is a refused\n * read or write rather than a failure to make the store. Defaults to\n * `globalThis.localStorage`.\n */\n storage?: () => {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n };\n /**\n * Where another tab's change is announced as a `storage` event. Defaults to\n * `globalThis` — the window — when it has `addEventListener`; `null` listens\n * nowhere, and a write still re-reads what is stored first.\n */\n events?: {\n addEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n removeEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n } | null;\n}\n\ntype KeptStorage = ReturnType<\n NonNullable<LocalStorageSnapshotOptions['storage']>\n>;\n\n/**\n * A `MemoryViewStore` snapshot kept in `localStorage` under `key`: the whole\n * store as one JSON document, `{ instances, preferences }`. For development\n * and single-user hosts until a real backend holds the views (phase 6); it\n * is one browser's, not a second store.\n *\n * Two things a browser does to such a document are the store's to answer,\n * and this is the design (decided 2026-09-28):\n *\n * - **A write storage refuses is a failed write.** `save` throws what\n * `setItem` threw (a full quota, blocked storage), and the store undoes the\n * write and rejects it as `UNAVAILABLE` — which the engine reports to the\n * environment's `onError` as a `store` failure and the UI shows as a save\n * whose outcome needs a retry, the error marked `storage` so the line\n * says the browser's storage is full or turned off rather than that the\n * result never came back. It never pretends a view was kept.\n * - **Tabs do not overwrite each other.** The stamps are the revisions the\n * stored state already carries, one per instance and one per definition's\n * preferences. The store re-reads this document before every write and\n * checks the write's revision against it, so a write merges instance by\n * instance into what another tab stored, and one based on a revision that\n * tab has moved past is a `CONFLICT`, the same flow a stale write in one\n * tab already takes. A `storage` event for `key` reloads the store, so\n * what another tab saved is listed without waiting for a write.\n *\n * A missing, unreadable or malformed document reads as nothing stored — the\n * store starts empty rather than the page breaking — and the next write\n * replaces it. The format is `{ instances, preferences }`, the one the\n * compensation console wrote under `wow-compensation-dashboard:views` before\n * it moved to the view store server.\n */\nexport function localStorageSnapshot(\n key: string,\n options: LocalStorageSnapshotOptions = {},\n): MemorySnapshot {\n const storage = options.storage ?? ambientStorage;\n const events =\n options.events === undefined ? ambientEvents() : options.events;\n return {\n load() {\n try {\n return parseState(storage().getItem(key));\n } catch {\n return undefined;\n }\n },\n save(state) {\n storage().setItem(key, JSON.stringify(state));\n },\n subscribe(listener) {\n if (!events) return () => {};\n const onStorage = (event: {\n key: string | null;\n storageArea?: unknown;\n }) => {\n // `null` is a `clear()`; another area (sessionStorage) is not ours.\n if (event.key !== null && event.key !== key) return;\n if (event.storageArea && event.storageArea !== readable(storage))\n return;\n listener();\n };\n events.addEventListener('storage', onStorage);\n return () => events.removeEventListener('storage', onStorage);\n },\n };\n}\n\nfunction ambientStorage(): KeptStorage {\n const storage = (globalThis as { localStorage?: KeptStorage }).localStorage;\n if (!storage) throw new Error('localStorage is not available');\n return storage;\n}\n\nfunction ambientEvents(): LocalStorageSnapshotOptions['events'] {\n const target = globalThis as Partial<\n NonNullable<LocalStorageSnapshotOptions['events']>\n >;\n return typeof target.addEventListener === 'function'\n ? (target as NonNullable<LocalStorageSnapshotOptions['events']>)\n : null;\n}\n\nfunction readable(storage: () => KeptStorage): KeptStorage | undefined {\n try {\n return storage();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The stored document, or `undefined` when it is not one. Only its outline\n * is checked here — an instance needs an id to be held by it; each config is\n * checked, and migrated, where every view out of a store is read.\n */\nfunction parseState(saved: string | null): MemoryState | undefined {\n if (!saved) return undefined;\n const state = JSON.parse(saved) as Partial<MemoryState> | null;\n if (\n !state ||\n typeof state !== 'object' ||\n !Array.isArray(state.instances) ||\n typeof state.preferences !== 'object' ||\n state.preferences === null ||\n Array.isArray(state.preferences)\n )\n return undefined;\n return {\n instances: state.instances.filter(isHeld),\n preferences: state.preferences,\n };\n}\n\nfunction isHeld(instance: unknown): instance is ViewInstance {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as { id?: unknown }).id === 'string'\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewPreferences,\n} from '../model/index.js';\n\n/**\n * The only port a backend must satisfy. Its failure type is `ViewStoreError`\n * from `model`, so both sides of the port speak it.\n *\n * Eight methods, and two a store may leave out (`changeAudience`, and\n * `permissions`, whose absence allows everything but `editSystem`); two\n * consistency rules: a write carries the revision it expects, and a retry\n * reuses its `requestId` so the server can recognise the same intent.\n *\n * Authorization, visibility filtering and deduplication belong to the server.\n * `permissions` only drives which buttons a UI enables.\n */\nexport interface ViewStore {\n /**\n * The definition's views this user sees, as summaries, **in a fixed\n * order**: the backend's system views first, as it declares them, then\n * the shared views, then the user's personal ones, each audience oldest\n * first (the order they were created in; a view moved to the other\n * audience keeps its place by age there). With no preferences, the first\n * of the list is the view that opens by default (`resolveDefault`), so\n * every store answers the same one.\n */\n list(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewInstanceSummary[]>;\n get(id: string, signal?: AbortSignal): Promise<ViewInstance>;\n /**\n * Creates a view for the scope `input` names. `scope: 'system'` creates a\n * **stored system view** (D81) — what 「发布为系统视图」 and 另存为 send\n * when the host grants `editSystem` — and answers it with `stored: true`;\n * a store that keeps no system views refuses it (`FORBIDDEN` or\n * `INVALID`). Publishing is a copy: the view it was made from is not\n * touched. The engine never sends `stored` itself; the store sets it.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance>;\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /**\n * Stores the title trimmed. A title blank once trimmed, or longer than\n * `MAX_VIEW_TITLE_LENGTH`, is refused as `INVALID` — so is one passed to\n * `create`, and a config of more than `MAX_VIEW_CONFIG_BYTES` passed to\n * `create` or `save`. The engine refuses both before sending; the store\n * keeps them for every other caller.\n */\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n delete(id: string, revision: string, context: WriteContext): Promise<void>;\n getPreferences(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewPreferences>;\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences>;\n /**\n * Moves a view to the other audience in place (设为共享/设为个人, D18\n * item 10): the id stays, so a board that shows it keeps showing it.\n *\n * Optional: a store without it has no such entry in the manager, and the\n * engine refuses the command before anything is sent\n * (`view.changeAudience.unsupported`). One that has it keeps the rules of\n * every other instance write — the expected `revision` (`CONFLICT`\n * carrying `instance`), a replayed `requestId` answering the first\n * outcome, a system view refused (`FORBIDDEN`) — a stored one too: a\n * system view never moves audience — a missing one\n * `NOT_FOUND` — and two of its own:\n *\n * - **No change is no write.** Asked for the audience the view already\n * has, it answers the view as it is, revision unmoved (after the\n * revision check, so a stale one still conflicts).\n * - **A view a shared board shows stays shared.** Made personal, it would\n * be blank on that board for every other reader, so the store refuses\n * it as `INVALID` with **`boards`, those boards' titles** as stored (a\n * title written as a key stays one): the engine says the refusal in\n * its own words around them (`view.changeAudience.invalid.shared-boards`),\n * so an adapter whose server answers with ids reads the titles. Only the\n * store sees every board.\n * Deleting such a view stays allowed (the panel alone breaks).\n */\n changeAudience?(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /** Synchronous, because the application fetched it before creating the engine. */\n permissions?(definitionId: string): ViewPermissions;\n}\n\n/**\n * One logical write. A retry after a timeout reuses the same `requestId` and\n * the same payload, which is what lets a server deduplicate it.\n */\nexport interface WriteContext {\n requestId: string;\n signal?: AbortSignal;\n}\n\n/** What the current user may do with one definition's views. */\nexport interface ViewPermissions {\n createPersonal: boolean;\n createShared: boolean;\n reorder: boolean;\n setDefault: boolean;\n /**\n * Whether this user edits the definition's **stored** system views\n * (`stored: true`) and creates new ones (`create({ scope: 'system' })`,\n * 「发布为系统视图」), D81. **Absent is false** — unlike everything else\n * here, where silence allows: a system view reaches every user, so only a\n * host that says so opens it, and a store without `permissions` does not.\n * When true, the `instance(id)` answer below applies to a stored system\n * view (save, rename, delete); a system view never moves audience, and\n * one declared in code or in the backend's configuration stays read-only.\n */\n editSystem?: boolean;\n instance(id: string): InstancePermissions;\n}\n\nexport interface InstancePermissions {\n save: boolean;\n rename: boolean;\n delete: boolean;\n /**\n * Whether the view may be moved to the other audience. Absent reads as\n * allowed — silence is not a refusal, as with the rest — and moving it\n * also asks the create permission of the audience it goes to\n * (`createShared` to share it, `createPersonal` to take it back).\n */\n changeAudience?: boolean;\n}\n\n/** An empty preference record, which is what an untouched definition has. */\nexport function emptyPreferences(): ViewPreferences {\n return { order: [], defaultInstanceId: null, revision: '0' };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n audienceOf,\n configBytes,\n isSystemInstanceId,\n isSystemScope,\n MAX_VIEW_CONFIG_BYTES,\n MAX_VIEW_TITLE_LENGTH,\n titleProblem,\n toSummary,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewInstanceSummary,\n type ViewPreferences,\n} from '../model/index.js';\nimport {\n emptyPreferences,\n type ViewPermissions,\n type ViewStore,\n type WriteContext,\n} from './ViewStore.js';\n\nexport interface MemoryViewStoreOptions {\n instances?: ViewInstance[];\n preferences?: Record<string, ViewPreferences>;\n permissions?: (definitionId: string) => ViewPermissions;\n /** Lets an example keep its data across reloads; not a second store. */\n snapshot?: MemorySnapshot;\n}\n\n/**\n * Where a `MemoryViewStore` keeps its state between page loads: the whole\n * state, read and written as one document, synchronously.\n *\n * The store reads it when it is made, again before every write, and again\n * whenever `subscribe` says another writer changed it, so every write is\n * checked against what is stored now rather than what this store last saw\n * (see `MemoryViewStore`). `load` answers `undefined` for nothing readable,\n * and the store then keeps what it holds.\n *\n * `save` throws when the state could not be kept — storage full, blocked,\n * refused. The store then undoes the write in memory and rejects it with a\n * `ViewStoreError` (`UNAVAILABLE`), so nobody is told a view was saved that\n * the next page load will not have.\n */\nexport interface MemorySnapshot {\n load(): MemoryState | undefined;\n save(state: MemoryState): void;\n /** Tells the store that another writer changed the state; answers the unsubscribe. */\n subscribe?(listener: () => void): () => void;\n}\n\nexport interface MemoryState {\n instances: ViewInstance[];\n preferences: Record<string, ViewPreferences>;\n}\n\n/**\n * The one implementation this package ships: a synchronous map behind the\n * port, for tests, examples and query-only use.\n *\n * It keeps the two consistency rules honest rather than convenient. A write\n * with a stale revision conflicts, and a replayed `requestId` returns the\n * first outcome instead of writing twice, so code written against it behaves\n * the same against a real backend — as do the port's list order and the\n * server's limits on a title and a config, which it refuses as the server\n * does (`INVALID`).\n *\n * System views come two ways (D81). One seeded with `scope: 'system'` and\n * no `stored` is a configured one, as the backend's configuration serves\n * it: every write to it is refused (`FORBIDDEN`). One created with\n * `scope: 'system'` — 「发布为系统视图」 — or seeded with `stored: true` is\n * a stored one: saved, renamed and deleted like a shared view, never moved\n * to another audience (`FORBIDDEN`). Like the server, the store asks no\n * permission of its own; `editSystem` is the host's to grant and the\n * engine's to ask.\n *\n * With a snapshot, several stores may share one stored state — two tabs over\n * one `localStorage`. The rule between them is the backend's: **re-read, then\n * compare revisions, one instance (or one definition's preferences) at a\n * time.** Before every write the store reloads the stored state, so a write\n * merges into what the other writer left — a board created in one tab\n * survives a reorder in the other, and ids never collide — and a write whose\n * `revision` the other writer has already moved past is refused as\n * `CONFLICT`, carrying what is stored, as any stale write is. Nothing is ever\n * overwritten because this store's copy was old. A write the snapshot could\n * not keep is undone and rejected as `UNAVAILABLE`: it did not land, so a\n * retry under the same `requestId` is safe.\n */\nexport class MemoryViewStore implements ViewStore {\n private readonly instances = new Map<string, ViewInstance>();\n private readonly preferences = new Map<string, ViewPreferences>();\n /** Outcome per logical instance write, so a retry is idempotent. */\n private readonly outcomes = new Map<string, ViewInstance | null>();\n /** The same rule for preferences, whose outcome is no instance. */\n private readonly preferenceOutcomes = new Map<string, ViewPreferences>();\n private readonly snapshot?: MemorySnapshot;\n readonly permissions?: (definitionId: string) => ViewPermissions;\n private sequence = 0;\n\n constructor(options: MemoryViewStoreOptions = {}) {\n // Left undefined when the caller declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n this.snapshot = options.snapshot;\n\n const restored = options.snapshot?.load();\n this.restore({\n instances: restored?.instances ?? options.instances ?? [],\n preferences: restored?.preferences ?? options.preferences ?? {},\n });\n options.snapshot?.subscribe?.(() => this.reload());\n }\n\n /**\n * In the port's order: system, shared, personal, each oldest first. The\n * map keeps insertion order — the order views were created or seeded in,\n * which a change of audience does not move — and the sort is stable.\n */\n list(definitionId: string): Promise<ViewInstanceSummary[]> {\n const summaries = [...this.instances.values()]\n .filter(instance => instance.definitionId === definitionId)\n .map(toSummary)\n .sort((a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope]);\n return Promise.resolve(summaries);\n }\n\n get(id: string): Promise<ViewInstance> {\n const instance = this.instances.get(id);\n return instance\n ? Promise.resolve(copy(instance))\n : Promise.reject(new ViewStoreError('NOT_FOUND', `No such view: ${id}`));\n }\n\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n const refused = titleRefusal(input.title) ?? configRefusal(input.config);\n if (refused) return Promise.reject(refused);\n this.reload();\n\n // Seeded instances occupy ids too, so the counter walks past anything\n // already taken rather than overwriting it.\n let id: string;\n do {\n this.sequence += 1;\n id = `${input.definitionId}-${this.sequence}`;\n } while (this.instances.has(id));\n if (isSystemInstanceId(id))\n return Promise.reject(\n new ViewStoreError('INVALID', `Reserved id namespace: ${id}`),\n );\n\n // `stored` is the store's to say, never the caller's: a system view\n // created here is one it keeps, and nothing else is one.\n const given = copy(input);\n delete given.stored;\n const instance: ViewInstance = {\n ...given,\n title: input.title.trim(),\n id,\n revision: '1',\n ...(isSystemScope(input.scope) ? { stored: true as const } : {}),\n };\n this.instances.set(id, instance);\n return this.commit(context, instance, () => this.instances.delete(id));\n }\n\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, config: copy(config) }),\n configRefusal(config),\n );\n }\n\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, title: title.trim() }),\n titleRefusal(title),\n );\n }\n\n /**\n * The port's in-place audience change: personal and shared swap, the id\n * and everything else stay. Asked for the audience the view already has,\n * it answers the view unchanged — no revision spent, nothing written — and\n * remembers that answer under the `requestId` like any other outcome.\n * A view a shared (or system) board shows is refused as `INVALID` when it\n * would become personal, `boards` naming those boards by title. A system\n * view, stored or not, never moves (`FORBIDDEN`).\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(id, revision, context, current => {\n if (isSystemScope(current.scope))\n return new ViewStoreError('FORBIDDEN', 'System views stay system');\n if (audienceOf(current.scope) === audience) return null;\n if (audience === 'personal') {\n const boards = this.sharedBoardsShowing(id);\n if (boards.length > 0)\n return new ViewStoreError(\n 'INVALID',\n `Shared dashboards show view ${id}: ${boards.join(', ')}`,\n { boards },\n );\n }\n return { ...current, scope: audience };\n });\n }\n\n delete(id: string, revision: string, context: WriteContext): Promise<void> {\n if (this.outcomes.has(context.requestId)) return Promise.resolve();\n this.reload();\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n // Deleting a configured system view is refused exactly as overwriting\n // one is: it is declared in code or by operations, and no user write\n // reaches it. A stored one is deleted like a shared view (unpublished).\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n this.instances.delete(id);\n const refused = this.persist(() => this.instances.set(id, current));\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, null);\n return Promise.resolve();\n }\n\n getPreferences(definitionId: string): Promise<ViewPreferences> {\n return Promise.resolve(\n this.preferences.get(definitionId) ?? emptyPreferences(),\n );\n }\n\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences> {\n // A replay answers with the outcome the first attempt produced, as every\n // other write does: a retry after a lost answer is the same logical\n // write, and reporting a conflict for it would be a lie.\n const replayed = this.preferenceOutcomes.get(context.requestId);\n if (replayed) return Promise.resolve(replayed);\n this.reload();\n\n const held = this.preferences.get(definitionId);\n const current = held ?? emptyPreferences();\n if (current.revision !== preferences.revision)\n return Promise.reject(\n new ViewStoreError(\n 'CONFLICT',\n `Preferences for ${definitionId} changed`,\n { preferences: current },\n ),\n );\n\n const next: ViewPreferences = {\n ...preferences,\n revision: nextRevision(current.revision),\n };\n this.preferences.set(definitionId, next);\n const refused = this.persist(() =>\n held\n ? this.preferences.set(definitionId, held)\n : this.preferences.delete(definitionId),\n );\n if (refused) return Promise.reject(refused);\n this.preferenceOutcomes.set(context.requestId, next);\n return Promise.resolve(next);\n }\n\n /**\n * One instance write: replay, the refusal of its input (`refused`, as the\n * server validates a command before it reaches the view), re-read, the\n * three refusals every instance write shares, then `change`. It may answer\n * `null` for a write that changes nothing — the view is answered as it is\n * and the revision is not spent — or a `ViewStoreError` for a refusal of\n * its own.\n */\n private update(\n id: string,\n revision: string,\n context: WriteContext,\n change: (current: ViewInstance) => ViewInstance | ViewStoreError | null,\n refused?: ViewStoreError,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n if (refused) return Promise.reject(refused);\n this.reload();\n\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n const changed = change(current);\n if (changed instanceof ViewStoreError) return Promise.reject(changed);\n if (changed === null) {\n this.outcomes.set(context.requestId, current);\n return Promise.resolve(copy(current));\n }\n const next: ViewInstance = {\n ...changed,\n revision: nextRevision(current.revision),\n };\n this.instances.set(id, next);\n return this.commit(context, next, () => this.instances.set(id, current));\n }\n\n /**\n * The titles of the boards everyone sees that show `id` in a panel — the\n * reference the dashboard kernel's `coversScope` guards from the board's\n * side. Read off the stored configs as the untrusted JSON they are: the\n * store may import nothing but the model.\n */\n private sharedBoardsShowing(id: string): string[] {\n const boards: string[] = [];\n for (const instance of this.instances.values()) {\n const { config } = instance;\n if (\n config.kind !== 'dashboard' ||\n audienceOf(instance.scope) !== 'shared'\n )\n continue;\n const panels: unknown = config.panels;\n if (Array.isArray(panels) && panels.some(panel => shows(panel, id)))\n boards.push(instance.title);\n }\n return boards;\n }\n\n private expect(\n current: ViewInstance,\n revision: string,\n ): ViewStoreError | undefined {\n return current.revision === revision\n ? undefined\n : new ViewStoreError(\n 'CONFLICT',\n `View ${current.id} moved to revision ${current.revision}`,\n { instance: current },\n );\n }\n\n private commit(\n context: WriteContext,\n instance: ViewInstance,\n undo: () => void,\n ): Promise<ViewInstance> {\n const refused = this.persist(undo);\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, instance);\n return Promise.resolve(copy(instance));\n }\n\n /**\n * Hands the state to the snapshot. When it could not be kept, the change\n * just made is undone — memory goes back to what is stored — and the\n * refusal is answered, so the write rejects rather than being reported as\n * saved. No outcome is remembered for it, so a retry writes again.\n */\n private persist(undo: () => void): ViewStoreError | undefined {\n if (!this.snapshot) return undefined;\n try {\n this.snapshot.save({\n instances: [...this.instances.values()].map(instance => copy(instance)),\n preferences: Object.fromEntries(this.preferences),\n });\n return undefined;\n } catch (error) {\n undo();\n return new ViewStoreError(\n 'UNAVAILABLE',\n `The view store could not keep this write: ${reasonOf(error)}`,\n { storage: true },\n );\n }\n }\n\n /**\n * Takes the stored state as it is now, when there is one to read: before a\n * write, so the write is checked against it, and when another writer says\n * it changed. Nothing readable leaves what the store holds as it is.\n */\n private reload(): void {\n const stored = this.snapshot?.load();\n if (stored) this.restore(stored);\n }\n\n private restore(state: MemoryState): void {\n this.instances.clear();\n this.preferences.clear();\n for (const instance of state.instances)\n this.instances.set(instance.id, copy(instance));\n for (const [definitionId, preferences] of Object.entries(state.preferences))\n this.preferences.set(definitionId, preferences);\n }\n}\n\n/**\n * Whether a stored panel references the saved view `id`, by any of the\n * three members the server reads (`ViewConfigs.PANEL_REFERENCES`, and\n * `DashboardPanel`): the view it shows (`instanceId`, unless the board owns\n * the view, `owned`), the view 「在工作台中打开」 opens (`opens`), and the\n * one a press opens (`click.instanceId`).\n */\nfunction shows(panel: unknown, id: string): boolean {\n if (typeof panel !== 'object' || panel === null) return false;\n const { instanceId, owned, opens, click } = panel as {\n instanceId?: unknown;\n owned?: unknown;\n opens?: unknown;\n click?: unknown;\n };\n if (owned === undefined && instanceId === id) return true;\n if (opens === id) return true;\n return (\n typeof click === 'object' &&\n click !== null &&\n (click as { instanceId?: unknown }).instanceId === id\n );\n}\n\n/** A system view no write reaches: configured, not one this store keeps. */\nfunction readOnlySystem(instance: ViewInstance): boolean {\n return isSystemScope(instance.scope) && instance.stored !== true;\n}\n\n/** System views first, then shared, then personal: the port's list order. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstance['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/**\n * The revision after `current`. Revisions are opaque to the port, and a host\n * may seed any string; one this store did not write as a count (`'ops-1'`)\n * starts the count again at `'1'`, which it can never have been, so a write\n * against it still conflicts. A count goes on counting.\n */\nfunction nextRevision(current: string): string {\n return /^(0|[1-9]\\d{0,14})$/.test(current)\n ? String(Number(current) + 1)\n : '1';\n}\n\n/** A title the server refuses (`ViewConfigs.requireTitle`), in its words. */\nfunction titleRefusal(title: string): ViewStoreError | undefined {\n switch (titleProblem(title)) {\n case 'empty':\n return new ViewStoreError('INVALID', \"A view's title must not be blank.\");\n case 'too-long':\n return new ViewStoreError(\n 'INVALID',\n `A view's title is longer than ${MAX_VIEW_TITLE_LENGTH} characters.`,\n );\n default:\n return undefined;\n }\n}\n\n/** A config larger than the server keeps, in its words. */\nfunction configRefusal(config: ViewConfig): ViewStoreError | undefined {\n const bytes = configBytes(config);\n return bytes > MAX_VIEW_CONFIG_BYTES\n ? new ViewStoreError(\n 'INVALID',\n `A view's config is ${bytes} bytes; the limit is ${MAX_VIEW_CONFIG_BYTES}.`,\n )\n : undefined;\n}\n\n/** What a refusal said — a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n\n/**\n * A structural copy, so nothing a caller holds is the object the store keeps.\n * A config handed in or read back is a plain JSON tree, and a caller editing\n * one it still has a reference to must not change what is stored.\n */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n"],"mappings":";;;;AAmCA,SAAgBS,GACdC,GACAC,GAC8B;CAC9B,IAAID,MAAS,IAAO;CACpB,IAAMG,KAAYC,MAChBA,EAAMJ,KAAKK,aAAa,KAAQ,OAAQD,EAAMJ,KAAKK,YAAY,CAAC,GAC5DC,IAAkD;EACtDN,MAAMA,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E;CACrEqE,QAAQ;CACRC,QAAQ;CACRC,UAAU;AACZ;AAQA,SAAS3B,EAAahB,GAAyB;CAC7C,OAAO,sBAAsB4C,KAAK5C,CAAO,IACrC6C,OAAOC,OAAO9C,CAAO,IAAI,CAAC,IAC1B;AACN;AAGA,SAASd,EAAaC,GAA2C;CAC/D,QAAQ7D,EAAa6D,CAAK,GAA1B;EACE,KAAK,SACH,OAAO,IAAI3D,EAAe,WAAW,mCAAmC;EAC1E,KAAK,YACH,OAAO,IAAIA,EACT,WACA,+CACF;EACF,SACE;CACJ;AACF;AAGA,SAAS4D,EAAcC,GAAgD;CACrE,IAAM0D,IAAQ9H,EAAYoE,CAAM;CAChC,OAAO0D,IAAAA,SACH,IAAIvH,EACF,WACA,sBAAsBuH,EAAK,uBAAwB3H,EAAqB,EAC1E,IACAuG,KAAAA;AACN;AAGA,SAASK,GAASD,GAAwB;CACxC,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAEiB,SAAMC,eAAYlB;EAC1B,IAAI,OAAOkB,KAAY,UACrB,OAAO,OAAOD,KAAS,WAAW,GAAGA,EAAI,IAAKC,MAAYA;CAC9D;CACA,OAAOJ,OAAOd,CAAK;AACrB;AAOA,SAAStD,EAAQyE,GAAa;CAC5B,OAAOE,gBAAgBF,CAAK;AAC9B"}
1
+ {"version":3,"file":"index.js","names":["QueryModelDescriptor","AnalysisCapability","AnalysisSpec","FieldAnalysisSpec","Issue","OpenCapabilities","issue","describedAnalysis","BuiltField","analysisPlan","spec","fields","undefined","narrowed","entry","analysis","plan","NonNullable","elements","own","described","children","entries","Record","child","one","field","name","buildAnalysis","descriptor","findings","map","what","push","FieldDescriptor","QueryModelDescriptor","FieldDefinition","FieldKindId","FieldOption","Issue","PagingMode","issue","describedField","DescribedField","FieldSpec","OptionSpec","FieldBuild","descriptor","paging","findings","BuiltField","field","described","spec","sensitive","children","found","code","params","Record","severity","buildFields","listed","Readonly","scope","build","Object","entries","flatMap","key","given","label","built","buildField","path","undefined","search","searchField","push","raw","fieldDescriptor","canonical","kind","kindOf","name","labelOf","comparable","sorts","sort","cursor","paged","sortsByDefault","sortable","operators","offered","operatorsOffered","operator","has","summary","functions","aggregate","fn","includes","options","optionsOf","deprecated","message","elements","some","element","map","entry","elementTitle","cell","timePrecision","assign","more","fields","searchFields","mode","searchMode","own","find","relative","slice","length","variants","values","variant","aliases","enum","temporal","semantic","type","types","description","ReadonlySet","Set","filter","add","listedOptions","value","option","known","Map","String","said","get","Array","isArray","keys","Exclude","QueryModelDescriptor","DataViewDefinition","FieldDefinition","Issue","PagingMode","RecordCapability","issue","analysisPlan","buildAnalysis","buildFields","BuiltField","narrowDefinition","constructible","builtinFieldKinds","FieldKindRegistry","DefineViewSpec","defineView","descriptor","spec","options","DefineViewOptions","findings","record","recordOf","fields","undefined","paging","definition","id","title","kind","source","map","entry","field","recordNoun","fieldGroups","plan","analysis","timeField","views","sort","flatMap","given","described","sortable","name","operators","openComparisons","withSnapshotComparisons","kinds","Set","version","open","scope","children","path","own","narrowed","ReadonlySet","index","cut","next","has","elements","PAGING","Readonly","Record","PAGED","CURSOR","offered","mode","includes","push","rowKey","identity","layouts","ViewInstance","MemorySnapshot","MemoryState","LocalStorageSnapshotOptions","storage","getItem","key","setItem","value","events","addEventListener","type","listener","event","storageArea","removeEventListener","KeptStorage","ReturnType","NonNullable","localStorageSnapshot","options","ambientStorage","undefined","ambientEvents","load","parseState","save","state","JSON","stringify","subscribe","onStorage","readable","globalThis","localStorage","Error","target","Partial","saved","parse","Array","isArray","instances","preferences","filter","isHeld","instance","id","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","ViewStore","list","definitionId","signal","AbortSignal","Promise","get","id","create","input","Omit","context","WriteContext","save","config","revision","rename","title","delete","getPreferences","setPreferences","preferences","changeAudience","audience","permissions","ViewPermissions","requestId","createPersonal","createShared","reorder","setDefault","editSystem","instance","InstancePermissions","emptyPreferences","order","defaultInstanceId","audienceOf","configBytes","isSystemInstanceId","isSystemScope","MAX_VIEW_CONFIG_BYTES","MAX_VIEW_TITLE_LENGTH","titleProblem","toSummary","ViewStoreError","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","emptyPreferences","ViewPermissions","ViewStore","WriteContext","MemoryViewStoreOptions","instances","preferences","Record","permissions","definitionId","snapshot","MemorySnapshot","load","MemoryState","save","state","subscribe","listener","MemoryViewStore","Map","outcomes","preferenceOutcomes","sequence","constructor","options","restored","restore","reload","list","Promise","summaries","values","filter","instance","map","sort","a","b","AUDIENCE_RANK","scope","resolve","get","id","copy","reject","create","input","Omit","context","replayed","requestId","refused","titleRefusal","title","configRefusal","config","has","given","stored","trim","revision","const","set","commit","delete","update","current","rename","changeAudience","audience","boards","sharedBoardsShowing","length","join","readOnlySystem","conflict","expect","persist","getPreferences","setPreferences","held","next","nextRevision","change","changed","kind","panels","Array","isArray","some","panel","shows","push","undefined","undo","Object","fromEntries","error","reasonOf","storage","clear","entries","instanceId","owned","opens","click","Readonly","system","shared","personal","test","String","Number","bytes","name","message","value","T","structuredClone","VIEW_STORE_ERROR_CODES","isReferenceFilterValue","withOutOfScope","isSystemInstanceId","clampPage","isSafeContentUrl","removeAt","analysisProbeLimit","NUMERIC_TYPES","familyOf","ANALYSIS_DATE_DIFF_UNITS","validatePanelClick","createFieldKindRegistry","isGroupItem","metricMeasures","fieldAliasSegment","expressionFieldsOf","filterStoredValue","ViewCommandError","isFilterLeaf","DELETION_STATES","metricReferenceText","DEFAULT_TEMPORAL","withSmooth","CHART_TYPES","crossFilterChoices","mergeFilters","dateFieldKind","chartUnfit","FIELD_TONES","CHART_FAMILIES","METRIC_HEADLINES","takesGroup","isViewWriteError","isSimpleTree","isDeletionState","chartPickerGroups","FIELD_CELL_IDS","withStagesFrom","MAX_MOVING_WINDOW","setPanelClick","walkFilter","resolveDateTimeRange","formulaFormat","TEMPORAL_TYPES","DERIVED_FORMAT_STYLES","defaultFilters","readValue","MAX_RELATIVE_DATE_AMOUNT","innermostElement","numberFormatOf","maxSortFields","panelFilterTree","isKnownEditorInput","validateViewConfigBase","readsAsItsField","isFieldName","wallClockAt","isValueMetric","filtersOf","walkFilterShape","booleanFieldKind","metricFieldOf","TIME_PRECISIONS","FIELD_METRIC_TYPES","filterCondition","say","isDurationFilterValue","relativeFields","DEFAULT_APPROXIMATE_METRICS","pageSummaries","clicksFilter","withFieldKinds","RELATIVE_DATE_UNITS","outOfScopeNames","summaryFunctionsOf","validateRecord","bindingsOf","filterIndexes","arrayFieldKind","metricFormat","aggregationFunctionsOf","MAX_DERIVED_DECIMALS","filterControlValue","sameFilterNode","isValidTimeZone","compileAnalysis","STRING_COMPARISONS","seriesMark","ANALYSIS_DATE_UNITS","FILTER_TYPE_OPERATOR","sameFilterTree","periodOf","compileAnalysisTotals","SUMMARY_FUNCTIONS","valueLabelsOn","ANALYSIS_PRESENTATION_MEMBERS","ONE_DAY_PRESETS","negateAt","dateTimeFieldKind","fitCharts","MAX_NUMERIC_SCALE","PEAKS_ONLY_FROM","REFERENCE_STATISTICS","urlPlaceholders","updateAt","resolveDateTimeBound","TEMPORAL_FIELD_KIND_IDS","isAdditiveMetric","DATE_PART_DOMAINS","admitFilters","withText","unknownOrOutside","isApproximate","isPresentationMember","isRootFilterIssue","describeFilter","metricFunctionOf","currencyPathOf","dateDiffUnitsOf","filterEditor","isFilterGroup","variantGroups","isFormula","DEFAULT_STRING_COMPARISON","withSlot","CHART_FAMILY","boardValueChoices","isViewCommandError","isNegation","impliedDeletion","CHART_PICKER_ORDER","FIELDLESS_FIELD_KIND_IDS","withStageOrder","MAX_CHART_LEVELS","pressableGroups","issue","DATE_TIME_PRESETS","analysisScope","isFieldlessKind","freeAlias","isBlankFilterValue","isBlankLeafValue","validateDataConfigBase","momentMetrics","isDateCell","bucketRange","groupFieldsOf","filterValueIssues","operatorsOf","DURATION_COMPARISONS","elementFilterFields","isSingleStringField","groupKeyText","isOneDayValue","textKeyOf","isNumberRange","relativeTree","SYSTEM_INSTANCE_ID_SEPARATOR","projectSummaries","isContentPanel","text","relativeName","SYSTEM_INSTANCE_ID_PREFIX","projectRecord","isOrderedRange","scopePrefix","approximateMetrics","recordValue","isOwnedPanel","durationFrom","numberFieldKind","derivedText","isFilterGroupOperator","optionTabs","filterTypeOf","validateTimeGrouping","describePresence","tabsOf","nearestPageSize","DASHBOARD_FILTER_KINDS","describedField","insertAt","elementFields","formulaMetric","DATE_SUMMARY_FUNCTIONS","withMovedTo","CARTESIAN_MISSING","mergeGlobalFilter","compileRecord","validateChart","MAX_VIEW_TITLE_LENGTH","limitBounds","DASHBOARD_PRESENTATION_MEMBERS","coversScope","compileFilter","summaryAlias","projectAnalysis","audienceOf","MAX_DASHBOARD_TABS","addTab","isBlankFilter","cursorPaging","isViewPanel","ViewStoreError","parseSystemInstanceId","BUILTIN_FIELD_KINDS","rowCurrency","configBytes","isPercentStacked","MAX_HEADING_LENGTH","moveTab","countLeaves","referenceFieldKind","derivedMetric","FILTER_GROUP_OPERATORS","offersStacking","boardWidth","validateFilterFields","conditions","searchFieldKind","OPERATOR_SIGN","toSummary","offersPercentStack","PANEL_PRESENTATION_MEMBERS","validateTabs","compilePresence","pagedPaging","referencedInstance","MAX_TIMER_DELAY_MS","comboMark","columnPinned","constructible","removeConditionAt","asksForWhole","SEARCH_MODES","peaksOnlyLabels","ANALYSIS_DATE_PARTS","nodeAt","readInstant","shapeChart","METADATA_FIELD_KIND_IDS","chartMarks","ANALYSIS_AUTO_RUN_MEMBERS","validateBoardClick","compileSummaries","measureColumns","VIEW_AUDIENCES","DASHBOARD_WIDTHS","validateDashboard","conditionOf","stringFieldKind","EXPRESSION_OPERATORS","titleProblem","isStacked","MAX_PANEL_LINKS","renameTab","validateFilter","pageAfterShrink","panelsOf","isViewStoreError","RECORD_PRESENTATION_MEMBERS","narrowDefinition","describePresenceParts","validateAnalysis","CODE_REVISION","DASHBOARD_FILTER_TYPES","clearFilter","builtinFieldKinds","metricCondition","isSystemScope","isSmooth","MAX_MARKDOWN_LENGTH","removeTab","writeValue","isDateTimeFilterValue","qualify","temporalOf","cardField","clickOf","PRESENCE_OPERATORS","pageWindow","presentationMembersOf","DEFAULT_RUNTIME_LIMITS","comboAxis","columnHidden","describedAnalysis","actions","isPresenceOperator","FIRST_PAGE","isChartColor","MAX_VIEW_CONFIG_BYTES","DASHBOARD_GRID_COLUMNS","isExecutableFilter","lastPageInWindow","panelTab","periodRollover","systemInstanceId","recordProjection","momentColumns","VIEW_SCOPES","MAX_DASHBOARD_FILTERS","validateLayout","emptyFilter","METADATA_FIELD_KINDS","durationMetric","BUILTIN_FIELD_KIND_IDS","stacks","boardCondition","ViewWriteError","isFilterNode","deletionFieldKind","wordReferences","EPOCH_TIME_UNITS","withStacked","DERIVED_KINDS","fillUrl","validateDefinition","isEmptyFilter","elementMatchFieldKind","isDuration","DEFAULT_SEARCH_MODE","withPercentStack","CHART_COLOR_SLOTS","boardFilterChoices","filterFields","enumFieldKind","expressionText","CURRENCY_CODE_PATTERN","stageValues","sameFilterType","mapGlobalFilter","EDITOR_INPUTS","groupJoinWord","metricMeasure","epochUnitOf","datePartsOf","filterOperatorOf","setPresentation","leadMetric","setFilterMultiple","drillConditions","wireableFields","narrowsTo","addFilter","nextExpansion","renameFilter","withoutLevelsFrom","removeFixedScope","withLevel","autoBindings","duplicatePanel","firstMetric","addPanel","DEFAULT_PERCENTILE","bindPanel","focusOn","referToSaved","groupableFields","editContent","groupFacts","filterReach","groupFor","setFilterOptions","drillGroups","setFilterRequired","retypeFilter","setTimeGrouping","setBoardWidth","summaryOf","filtersOnTab","splitBy","defaultRuntimeEnvironment","levelLabel","removeFilter","withElements","compactTab","aliasOf","wiredOptions","DEFAULT_MISSING_KEY","defaultPanelSize","defaultAnalysisConfig","renamePanel","metricWithCondition","removePanel","metricOfSummary","replacePanelView","summaryChoices","VIEW_KINDS","havingRows","isRecordRuntime","valueCandidateField","freeSpot","recommendDateUnit","isExportCancelledError","valueCandidatesConfig","placePanel","defaultRecordConfig","reorderPanel","switchChartType","STACKED_COLUMNS","recordCapabilityOf","reorderPanelIn","unmarkedErrors","HAVING_OPERATORS","withRootSearch","emptyDashboardConfig","readValueCandidates","fitsGrid","setFilterOneDay","setFilterDefault","fitChartSlots","placePanelIn","searchFieldOf","withLayouts","hasResult","VALUE_CANDIDATE_OPERATORS","bottomOf","ExportCancelledError","valueCandidateLimit","grownLayout","rootSearch","stackedLayout","movePanelToTab","groupOfType","ViewEngine","narrowValueCandidates","compactLayout","valueCandidateNarrowing","overlaps","hasAsked","VALUE_CANDIDATE_LIMIT","arrangePanel","detailSections","readingOrder","autoRunMembers","withHavingRows","moveFilter","nextLevel","ALWAYS_VISIBLE","resultSpan","presentationMembers","rangeSpan","unbindPanels","drillFilter","draftedClick","valueSourceKey","CSV_BOM","serializeCsv","clickDraftOf","withBoard","fieldGroups","boardValueSources","mappedValues","clickDraftGaps","urlFillable","CLICK_GO_KINDS","bucketChange","analysisPlan","spec","narrowed","entry","plan","fields","own","entries","child","one","buildAnalysis","descriptor","findings","field","found","code","params","severity","buildFields","listed","key","given","built","buildField","scope","build","path","searchField","described","raw","fieldDescriptor","kind","kindOf","labelOf","comparable","sorts","sortsByDefault","offered","operatorsOffered","operator","functions","fn","options","optionsOf","children","element","search","name","relative","variants","variant","temporal","types","listedOptions","values","value","option","known","said","defineView","record","recordOf","definition","analysis","sort","operators","openComparisons","withSnapshotComparisons","cut","index","next","open","PAGING","mode","paging","localStorageSnapshot","storage","ambientStorage","events","ambientEvents","parseState","state","onStorage","event","readable","listener","target","saved","isHeld","instance","emptyPreferences","MemoryViewStore","restored","summaries","definitionId","AUDIENCE_RANK","a","b","id","copy","replayed","context","refused","titleRefusal","input","configRefusal","revision","current","config","title","audience","boards","readOnlySystem","conflict","held","preferences","nextRevision","changed","change","panels","shows","panel","undo","error","reasonOf","stored","owned","instanceId","opens","click","bytes","message"],"sources":["../src/runtime/define/analysis.ts","../src/runtime/define/fields.ts","../src/runtime/define/defineView.ts","../src/store/localStorageSnapshot.ts","../src/store/ViewStore.ts","../src/store/MemoryViewStore.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The analyses of a `defineView` definition: which fields analyse and how\n * the host narrows each is the host's (the plan, `OpenCapabilities`); what\n * each path offers is its source's. Built here over the snapshot — what a\n * source with no descriptor runs on — and read again over a source's own\n * descriptor when it narrows (`reopened`). A narrowing beyond what the\n * snapshot grants is a warning, not an error: another store may grant it.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport type {\n AnalysisCapability,\n AnalysisSpec,\n FieldAnalysisSpec,\n Issue,\n OpenCapabilities,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { describedAnalysis } from '../../capabilities/open.js';\nimport type { BuiltField } from './fields.js';\n\n/** Which fields analyse, and the host's narrowing of each; `undefined` for none. */\nexport function analysisPlan(\n spec: AnalysisSpec | false | undefined,\n fields: readonly BuiltField[],\n): OpenCapabilities['analysis'] {\n if (spec === false) return undefined;\n const narrowed = (entry: BuiltField): FieldAnalysisSpec | null =>\n entry.spec.analysis === false ? null : (entry.spec.analysis ?? {});\n const plan: NonNullable<OpenCapabilities['analysis']> = {\n spec: spec ?? {},\n fields: {},\n elements: {},\n };\n for (const entry of fields) {\n const own = entry.described ? narrowed(entry) : null;\n if (!own) continue;\n if (entry.children) {\n const entries: Record<string, FieldAnalysisSpec> = {};\n for (const child of entry.children) {\n const one = narrowed(child);\n if (one) entries[child.field.name] = one;\n }\n (plan.elements as Record<string, typeof entries>)[entry.field.name] =\n entries;\n } else\n (plan.fields as Record<string, FieldAnalysisSpec>)[entry.field.name] =\n own;\n }\n return plan;\n}\n\n/** The plan's analyses over the snapshot, what it asks beyond said as warnings. */\nexport function buildAnalysis(\n plan: OpenCapabilities['analysis'],\n fields: readonly BuiltField[],\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): AnalysisCapability | undefined {\n if (!plan) return undefined;\n return describedAnalysis(\n plan,\n fields.map(entry => entry.field),\n descriptor,\n (field, what) =>\n findings.push(\n field === null\n ? issue(\n 'definition.analysis.wider',\n ['analysis'],\n { what },\n 'warning',\n )\n : issue(\n 'definition.field.analysis-wider',\n ['analysis'],\n { field, what },\n 'warning',\n ),\n ),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A field as `defineView` builds it (host-integration.md 3): its kind, its\n * values and whether it sorts are the descriptor's; its label, its order,\n * its cell and what it narrows are the host's. The operators are left to\n * the kind unless the host narrows them — the engine cuts them to the\n * descriptor in force whenever a view runs (N5), so a list copied here\n * would only go stale.\n */\n\nimport type {\n FieldDescriptor,\n QueryModelDescriptor,\n} from '@ahoo-wang/wow-client';\nimport type {\n FieldDefinition,\n FieldKindId,\n FieldOption,\n Issue,\n PagingMode,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport {\n describedField,\n type DescribedField,\n} from '../../capabilities/match.js';\nimport type { FieldSpec, OptionSpec } from './spec.js';\n\n/** What building the fields reads, and where it says what it found. */\ninterface FieldBuild {\n descriptor: QueryModelDescriptor;\n paging: PagingMode;\n findings: Issue[];\n}\n\n/** One built field and what it is over, for the analyses to read. */\nexport interface BuiltField {\n field: FieldDefinition;\n described: DescribedField | null;\n spec: FieldSpec;\n /** Whether the value is sensitive: masked, so never grouped or measured. */\n sensitive: boolean;\n /** An array's entries, built as its fields are. */\n children?: BuiltField[];\n}\n\nconst found = (\n code: string,\n params: Record<string, string>,\n severity: Issue['severity'] = 'error',\n): Issue => issue(code, ['fields'], params, severity);\n\n/** The fields listed, built in the order listed; one the descriptor lacks is left out. */\nexport function buildFields(\n listed: Readonly<Record<string, FieldSpec | string>>,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField[] {\n return Object.entries(listed).flatMap(([key, given]) => {\n const spec: FieldSpec =\n typeof given === 'string' ? { label: given } : given;\n const built = buildField(key, spec, scope, build);\n return built ? [built] : [];\n });\n}\n\nfunction buildField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField | null {\n const { descriptor, findings } = build;\n const path = scope === undefined ? key : `${scope}.${key}`;\n if (spec.search) return searchField(key, spec, scope, build);\n\n const described = describedField(descriptor, path, scope);\n if (!described) {\n findings.push(found('definition.field.undescribed', { field: path }));\n return null;\n }\n const raw = fieldDescriptor(descriptor, described.canonical ?? path, scope);\n const kind = spec.kind ?? kindOf(raw, described, spec);\n if (kind === null) {\n findings.push(found('definition.field.kind-unknown', { field: path }));\n return null;\n }\n const field: FieldDefinition = {\n name: key,\n label: labelOf(spec, raw, path, findings),\n kind,\n };\n const comparable = described.comparable !== false;\n\n // An entry's field is read inside its record, not what records are\n // ordered by: offered as a sort only where the host asks.\n const sorts =\n comparable &&\n (build.paging === 'cursor' ? described.sort.cursor : described.sort.paged);\n const sortsByDefault = sorts && scope === undefined;\n if (spec.sortable === true && !sorts)\n findings.push(\n found('definition.field.sort-wider', { field: path }, 'warning'),\n );\n if (sorts && (spec.sortable ?? sortsByDefault)) field.sortable = true;\n\n if (spec.operators) {\n const offered = operatorsOffered(descriptor, described, path);\n for (const operator of spec.operators)\n if (!offered.has(operator))\n findings.push(\n found(\n 'definition.field.operator-wider',\n { field: path, operator },\n 'warning',\n ),\n );\n field.operators = spec.operators;\n } else if (!comparable) field.operators = [];\n\n if (spec.summary) {\n const functions: readonly string[] = described.aggregate?.functions ?? [];\n for (const fn of spec.summary)\n if (fn !== 'COUNT' && !functions.includes(fn))\n findings.push(\n found(\n 'definition.field.summary-wider',\n { field: path, fn },\n 'warning',\n ),\n );\n field.summary = spec.summary;\n }\n\n const options = optionsOf(spec, described, path, findings);\n if (options) field.options = options;\n\n if (described.deprecated) {\n if (!spec.deprecated)\n findings.push(\n found(\n 'definition.field.deprecated',\n { field: path, message: described.deprecated.message ?? '' },\n 'warning',\n ),\n );\n field.deprecated = spec.deprecated ?? described.deprecated;\n }\n\n let children: BuiltField[] | undefined;\n if (spec.elements) {\n if (!descriptor.elements.some(element => element.path === path))\n findings.push(found('definition.field.not-elements', { field: path }));\n children = buildFields(spec.elements, path, build);\n field.elements = children.map(entry => entry.field);\n }\n if (spec.elementTitle !== undefined) field.elementTitle = spec.elementTitle;\n if (spec.cell !== undefined) field.cell = spec.cell;\n if (spec.timePrecision !== undefined)\n field.timePrecision = spec.timePrecision;\n Object.assign(field, spec.more);\n return {\n field,\n described,\n spec,\n sensitive: described.sensitive === true,\n ...(children ? { children } : {}),\n };\n}\n\n/** A search box: its fields must be paths the descriptor has. */\nfunction searchField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField {\n const search = spec.search ?? { fields: [] };\n // An entry's search names its fields within the entry (N4).\n for (const name of search.fields) {\n const path = scope === undefined ? name : `${scope}.${name}`;\n if (!describedField(build.descriptor, path, scope))\n build.findings.push(\n found('definition.field.undescribed', { field: path }),\n );\n }\n const field: FieldDefinition = {\n name: key,\n label: spec.label ?? key,\n kind: 'search',\n searchFields: search.fields,\n };\n if (search.mode) field.searchMode = search.mode;\n return { field, described: null, spec, sensitive: false };\n}\n\n/** The descriptor's own entry for a path, for what `describedField` leaves out. */\nfunction fieldDescriptor(\n descriptor: QueryModelDescriptor,\n path: string,\n scope: string | undefined,\n): FieldDescriptor | undefined {\n const own = descriptor.fields.find(\n entry => entry.path === path && entry.scope === scope,\n );\n if (own || scope === undefined) return own;\n // A variant's fields are listed relative to the element, by path or alias,\n // as `describedField` reads them.\n const relative = path.slice(scope.length + 1);\n const variants = descriptor.variants;\n if (variants?.element !== scope) return undefined;\n return variants.values\n .flatMap(variant => variant.fields)\n .find(\n entry =>\n entry.path === relative || (entry.aliases ?? []).includes(relative),\n );\n}\n\n/** The kind the descriptor says a path is; `null` where it says none. */\nfunction kindOf(\n raw: FieldDescriptor | undefined,\n described: DescribedField,\n spec: FieldSpec,\n): FieldKindId | null {\n if (spec.elements) return 'elementMatch';\n if (described.enum || spec.options) return 'enum';\n const temporal = described.semantic?.type;\n if (temporal === 'TEMPORAL_DATE') return 'date';\n if (temporal === 'TEMPORAL_EPOCH' || temporal === 'TEMPORAL_FORMATTED')\n return 'datetime';\n const types: readonly string[] = raw?.types ?? [];\n if (types.length !== 1) return null;\n switch (types[0]) {\n case 'BOOLEAN':\n return 'boolean';\n case 'INTEGER':\n case 'DECIMAL':\n return 'number';\n case 'STRING':\n return 'string';\n default:\n return null;\n }\n}\n\n/**\n * The host's word, else the domain's description, else the path — the two\n * fallbacks said, since a reader would see a program's word.\n */\nfunction labelOf(\n spec: FieldSpec,\n raw: FieldDescriptor | undefined,\n path: string,\n findings: Issue[],\n): string {\n if (spec.label !== undefined) return spec.label;\n findings.push(found('definition.field.unlabelled', { field: path }, 'note'));\n return raw?.description ?? path;\n}\n\n/**\n * The comparisons a path admits: its own operators, and a match over its\n * entries where it is an element the model filters by (capabilities.md,\n * `ELEMENT_MATCH` comes from `elements[]`).\n */\nfunction operatorsOffered(\n descriptor: QueryModelDescriptor,\n described: DescribedField,\n path: string,\n): ReadonlySet<string> {\n const offered = new Set(described.operators);\n if (descriptor.elements.some(entry => entry.path === path && entry.filter))\n offered.add('ELEMENT_MATCH');\n return offered;\n}\n\n/**\n * A category's values: the host's listed first, in its order and words,\n * then the rest of the descriptor's under their descriptions; one the host\n * hides left out. Where the descriptor lists none the host's list is the\n * whole of it.\n */\nfunction optionsOf(\n spec: FieldSpec,\n described: DescribedField,\n path: string,\n findings: Issue[],\n): FieldOption[] | undefined {\n const listed = listedOptions(spec.options);\n const values = described.enum;\n if (!values)\n return spec.options\n ? listed.flatMap(([value, given]) =>\n given === false ? [] : [option(value, given)],\n )\n : undefined;\n const known = new Map(values.map(entry => [String(entry.value), entry]));\n const said = new Set<string>();\n const options: FieldOption[] = [];\n for (const [value, given] of listed) {\n const key = String(value);\n const entry = known.get(key);\n if (!entry) {\n findings.push(\n found('definition.option.undescribed', { field: path, value: key }),\n );\n continue;\n }\n said.add(key);\n if (given !== false) options.push(option(entry.value, given));\n }\n for (const entry of values)\n if (!said.has(String(entry.value)))\n options.push({\n value: entry.value as FieldOption['value'],\n label: entry.description ?? String(entry.value),\n });\n return options;\n}\n\n/**\n * The host's values in the order written: a list as it is, a record in its\n * own order — which JavaScript puts integer-like keys first in, so a\n * category of numbers is written as a list.\n */\nfunction listedOptions(\n given: FieldSpec['options'],\n): (readonly [unknown, OptionSpec])[] {\n if (!given) return [];\n if (Array.isArray(given)) return given as (readonly [unknown, OptionSpec])[];\n // Own keys only: a value named like a prototype member is a value.\n return Object.keys(given).map(key => [\n key,\n (given as Readonly<Record<string, OptionSpec>>)[key],\n ]);\n}\n\nfunction option(\n value: unknown,\n given: Exclude<OptionSpec, false>,\n): FieldOption {\n return typeof given === 'string'\n ? { value: value as FieldOption['value'], label: given }\n : { value: value as FieldOption['value'], ...given };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport type {\n DataViewDefinition,\n FieldDefinition,\n Issue,\n PagingMode,\n RecordCapability,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { analysisPlan, buildAnalysis } from './analysis.js';\nimport { buildFields, type BuiltField } from './fields.js';\nimport { narrowDefinition } from '../../capabilities/index.js';\nimport { constructible } from '../../capabilities/analysis.js';\nimport {\n builtinFieldKinds,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport type { DefineViewSpec } from './spec.js';\n\n/**\n * A data definition built from its source's descriptor (host-integration.md\n * 3, D67): the descriptor gives the facts — which paths there are, what\n * each is, what it sorts and feeds — as an upper bound, and `spec` picks,\n * names and narrows within it. A field not listed does not appear. A path\n * or a value the descriptor lacks is an error admission reports\n * (`DataViewDefinition.described`), never a throw: a definition wrong in\n * one place still loads, and says where. A capability asked beyond the\n * snapshot is a warning: what a path sorts and aggregates by is the\n * store's, and another store may grant it.\n *\n * Facts — paths, kinds, values, sensitivity, the entries of an array —\n * are the snapshot's. Capabilities are not baked in: where the host\n * narrows nothing the definition takes whatever its source grants, and\n * where it narrows, its subset of that (`DefinitionDescribed.open`,\n * filled by the narrowing from the source's descriptor). A source with\n * no descriptor runs on the snapshot's.\n *\n * `descriptor` is the snapshot committed beside the definition (Q2): the\n * definition is built at once, when the module loads, and a test builds\n * the same one. The descriptor the source answers at run time narrows it\n * again, as any definition is (N5).\n *\n * The result is an ordinary definition: nothing past this function knows\n * how it was written, and one written in full by hand is still one.\n */\nexport function defineView(\n descriptor: QueryModelDescriptor,\n spec: DefineViewSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const findings: Issue[] = [];\n const record = recordOf(spec, descriptor, findings);\n const fields = buildFields(spec.fields, undefined, {\n descriptor,\n paging: record?.paging ?? 'paged',\n findings,\n });\n const definition: DataViewDefinition = {\n id: spec.id,\n title: spec.title,\n kind: 'data',\n source: spec.source,\n fields: fields.map(entry => entry.field),\n };\n if (spec.recordNoun !== undefined) definition.recordNoun = spec.recordNoun;\n if (spec.fieldGroups) definition.fieldGroups = spec.fieldGroups;\n if (record) definition.record = record;\n const plan = analysisPlan(spec.analysis, fields);\n const analysis = buildAnalysis(plan, fields, descriptor, findings);\n // A snapshot with no metric at all offers no analyses; a source that\n // grants some fills them in (`reopened`) rather than the definition\n // being refused for one store's word.\n if (analysis && constructible(analysis)) definition.analysis = analysis;\n if (spec.timeField !== undefined) definition.timeField = spec.timeField;\n if (spec.views) definition.views = spec.views;\n // What compares, sorts and aggregates is the store's: left to the source\n // where the host did not narrow it, filled from its descriptor when it\n // narrows (`reopened`), the snapshot's written here for a source that\n // has none.\n const sort = fields.flatMap(({ field, spec: given, described }) =>\n described && given.sortable !== false ? [field.name] : [],\n );\n const operators = openComparisons(fields);\n definition.fields = withSnapshotComparisons(\n definition.fields,\n narrowDefinition(definition, descriptor, options.kinds ?? builtinFieldKinds)\n .definition.fields,\n new Set(operators),\n );\n definition.described = {\n version: descriptor.version,\n findings,\n open: { sort, operators, ...(plan ? { analysis: plan } : {}) },\n };\n return definition;\n}\n\n/**\n * The fields whose comparisons the host left open, by path: every field\n * but one whose operators the host wrote, one that compares nothing (a\n * confidential value), and a search box.\n */\nfunction openComparisons(\n fields: readonly BuiltField[],\n scope?: string,\n): string[] {\n return fields.flatMap(({ field, spec, children }) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n // A search box is the host's to ask for, as written operators are: on\n // a source with no descriptor it is offered as declared, and a source\n // that says whether it searches narrows it.\n const own =\n spec.operators === undefined &&\n field.operators === undefined &&\n field.kind !== 'search'\n ? [path]\n : [];\n return [...own, ...openComparisons(children ?? [], path)];\n });\n}\n\n/**\n * The fields with the snapshot's comparisons written on each one left\n * open: the operators the narrowing against it keeps on each path, so a\n * source with no descriptor offers what the snapshot's store does, and no\n * more.\n */\nfunction withSnapshotComparisons(\n fields: readonly FieldDefinition[],\n narrowed: readonly FieldDefinition[],\n open: ReadonlySet<string>,\n scope?: string,\n): FieldDefinition[] {\n return fields.map((field, index) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n const cut = narrowed[index];\n let next = field;\n if (open.has(path) && cut?.operators !== undefined)\n next = { ...next, operators: cut.operators };\n if (field.elements)\n next = {\n ...next,\n elements: withSnapshotComparisons(\n field.elements,\n cut?.elements ?? [],\n open,\n path,\n ),\n };\n return next;\n });\n}\n\n/**\n * What `defineView` needs beyond the snapshot and the host's choices: the\n * field kinds the host registers (`ViewEngineOptions.kinds`) — the snapshot's\n * comparisons are written on a field of a host's own kind only when its\n * kind is known here, since it is built before any engine is. Left out,\n * the built-in kinds.\n */\nexport interface DefineViewOptions {\n kinds?: FieldKindRegistry;\n}\n\n/** The descriptor's paging modes, as a definition names them. */\nconst PAGING: Readonly<Record<string, PagingMode>> = {\n PAGED: 'paged',\n CURSOR: 'cursor',\n};\n\n/**\n * Records: the host's choices over the descriptor's identity and paging —\n * paged where the model pages, else by cursor — shown as a table unless the\n * host says otherwise. A paging the model does not offer is asked beyond it.\n */\nfunction recordOf(\n spec: DefineViewSpec,\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): RecordCapability | undefined {\n if (spec.record === false) return undefined;\n const given = spec.record ?? {};\n const offered = descriptor.record.paging.flatMap(mode =>\n PAGING[mode] ? [PAGING[mode]] : [],\n );\n const paging =\n given.paging ?? (offered.includes('paged') ? 'paged' : 'cursor');\n if (!offered.includes(paging))\n findings.push(\n issue(\n 'definition.record.paging-wider',\n ['record', 'paging'],\n { paging },\n 'warning',\n ),\n );\n return {\n ...given,\n rowKey: given.rowKey ?? descriptor.record.identity,\n paging,\n layouts: given.layouts ?? ['table'],\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ViewInstance } from '../model/index.js';\nimport type { MemorySnapshot, MemoryState } from './MemoryViewStore.js';\n\n/**\n * Where a `localStorageSnapshot` reads and writes. Both are structural, so\n * this layer names no DOM type, and a test hands in a storage of its own.\n */\nexport interface LocalStorageSnapshotOptions {\n /**\n * The storage, asked for at each read and write rather than once, so a\n * browser that refuses it (private mode, blocked site data) is a refused\n * read or write rather than a failure to make the store. Defaults to\n * `globalThis.localStorage`.\n */\n storage?: () => {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n };\n /**\n * Where another tab's change is announced as a `storage` event. Defaults to\n * `globalThis` — the window — when it has `addEventListener`; `null` listens\n * nowhere, and a write still re-reads what is stored first.\n */\n events?: {\n addEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n removeEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n } | null;\n}\n\ntype KeptStorage = ReturnType<\n NonNullable<LocalStorageSnapshotOptions['storage']>\n>;\n\n/**\n * A `MemoryViewStore` snapshot kept in `localStorage` under `key`: the whole\n * store as one JSON document, `{ instances, preferences }`. For development\n * and single-user hosts until a real backend holds the views (phase 6); it\n * is one browser's, not a second store.\n *\n * Two things a browser does to such a document are the store's to answer,\n * and this is the design (decided 2026-09-28):\n *\n * - **A write storage refuses is a failed write.** `save` throws what\n * `setItem` threw (a full quota, blocked storage), and the store undoes the\n * write and rejects it as `UNAVAILABLE` — which the engine reports to the\n * environment's `onError` as a `store` failure and the UI shows as a save\n * whose outcome needs a retry, the error marked `storage` so the line\n * says the browser's storage is full or turned off rather than that the\n * result never came back. It never pretends a view was kept.\n * - **Tabs do not overwrite each other.** The stamps are the revisions the\n * stored state already carries, one per instance and one per definition's\n * preferences. The store re-reads this document before every write and\n * checks the write's revision against it, so a write merges instance by\n * instance into what another tab stored, and one based on a revision that\n * tab has moved past is a `CONFLICT`, the same flow a stale write in one\n * tab already takes. A `storage` event for `key` reloads the store, so\n * what another tab saved is listed without waiting for a write.\n *\n * A missing, unreadable or malformed document reads as nothing stored — the\n * store starts empty rather than the page breaking — and the next write\n * replaces it. The format is `{ instances, preferences }`, the one the\n * compensation console wrote under `wow-compensation-dashboard:views` before\n * it moved to the view store server.\n */\nexport function localStorageSnapshot(\n key: string,\n options: LocalStorageSnapshotOptions = {},\n): MemorySnapshot {\n const storage = options.storage ?? ambientStorage;\n const events =\n options.events === undefined ? ambientEvents() : options.events;\n return {\n load() {\n try {\n return parseState(storage().getItem(key));\n } catch {\n return undefined;\n }\n },\n save(state) {\n storage().setItem(key, JSON.stringify(state));\n },\n subscribe(listener) {\n if (!events) return () => {};\n const onStorage = (event: {\n key: string | null;\n storageArea?: unknown;\n }) => {\n // `null` is a `clear()`; another area (sessionStorage) is not ours.\n if (event.key !== null && event.key !== key) return;\n if (event.storageArea && event.storageArea !== readable(storage))\n return;\n listener();\n };\n events.addEventListener('storage', onStorage);\n return () => events.removeEventListener('storage', onStorage);\n },\n };\n}\n\nfunction ambientStorage(): KeptStorage {\n const storage = (globalThis as { localStorage?: KeptStorage }).localStorage;\n if (!storage) throw new Error('localStorage is not available');\n return storage;\n}\n\nfunction ambientEvents(): LocalStorageSnapshotOptions['events'] {\n const target = globalThis as Partial<\n NonNullable<LocalStorageSnapshotOptions['events']>\n >;\n return typeof target.addEventListener === 'function'\n ? (target as NonNullable<LocalStorageSnapshotOptions['events']>)\n : null;\n}\n\nfunction readable(storage: () => KeptStorage): KeptStorage | undefined {\n try {\n return storage();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The stored document, or `undefined` when it is not one. Only its outline\n * is checked here — an instance needs an id to be held by it; each config is\n * checked, and migrated, where every view out of a store is read.\n */\nfunction parseState(saved: string | null): MemoryState | undefined {\n if (!saved) return undefined;\n const state = JSON.parse(saved) as Partial<MemoryState> | null;\n if (\n !state ||\n typeof state !== 'object' ||\n !Array.isArray(state.instances) ||\n typeof state.preferences !== 'object' ||\n state.preferences === null ||\n Array.isArray(state.preferences)\n )\n return undefined;\n return {\n instances: state.instances.filter(isHeld),\n preferences: state.preferences,\n };\n}\n\nfunction isHeld(instance: unknown): instance is ViewInstance {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as { id?: unknown }).id === 'string'\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewPreferences,\n} from '../model/index.js';\n\n/**\n * The only port a backend must satisfy. Its failure type is `ViewStoreError`\n * from `model`, so both sides of the port speak it.\n *\n * Eight methods, and two a store may leave out (`changeAudience`, and\n * `permissions`, whose absence allows everything but `editSystem`); two\n * consistency rules: a write carries the revision it expects, and a retry\n * reuses its `requestId` so the server can recognise the same intent.\n *\n * Authorization, visibility filtering and deduplication belong to the server.\n * `permissions` only drives which buttons a UI enables.\n */\nexport interface ViewStore {\n /**\n * The definition's views this user sees, as summaries, **in a fixed\n * order**: the backend's system views first, as it declares them, then\n * the shared views, then the user's personal ones, each audience oldest\n * first (the order they were created in; a view moved to the other\n * audience keeps its place by age there). With no preferences, the first\n * of the list is the view that opens by default (`resolveDefault`), so\n * every store answers the same one.\n */\n list(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewInstanceSummary[]>;\n get(id: string, signal?: AbortSignal): Promise<ViewInstance>;\n /**\n * Creates a view for the scope `input` names. `scope: 'system'` creates a\n * **stored system view** (D81) — what 「发布为系统视图」 and 另存为 send\n * when the host grants `editSystem` — and answers it with `stored: true`;\n * a store that keeps no system views refuses it (`FORBIDDEN` or\n * `INVALID`). Publishing is a copy: the view it was made from is not\n * touched. The engine never sends `stored` itself; the store sets it.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance>;\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /**\n * Stores the title trimmed. A title blank once trimmed, or longer than\n * `MAX_VIEW_TITLE_LENGTH`, is refused as `INVALID` — so is one passed to\n * `create`, and a config of more than `MAX_VIEW_CONFIG_BYTES` passed to\n * `create` or `save`. The engine refuses both before sending; the store\n * keeps them for every other caller.\n */\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n delete(id: string, revision: string, context: WriteContext): Promise<void>;\n getPreferences(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewPreferences>;\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences>;\n /**\n * Moves a view to the other audience in place (设为共享/设为个人, D18\n * item 10): the id stays, so a board that shows it keeps showing it.\n *\n * Optional: a store without it has no such entry in the manager, and the\n * engine refuses the command before anything is sent\n * (`view.changeAudience.unsupported`). One that has it keeps the rules of\n * every other instance write — the expected `revision` (`CONFLICT`\n * carrying `instance`), a replayed `requestId` answering the first\n * outcome, a system view refused (`FORBIDDEN`) — a stored one too: a\n * system view never moves audience — a missing one\n * `NOT_FOUND` — and two of its own:\n *\n * - **No change is no write.** Asked for the audience the view already\n * has, it answers the view as it is, revision unmoved (after the\n * revision check, so a stale one still conflicts).\n * - **A view a shared board shows stays shared.** Made personal, it would\n * be blank on that board for every other reader, so the store refuses\n * it as `INVALID` with **`boards`, those boards' titles** as stored (a\n * title written as a key stays one): the engine says the refusal in\n * its own words around them (`view.changeAudience.invalid.shared-boards`),\n * so an adapter whose server answers with ids reads the titles. Only the\n * store sees every board.\n * Deleting such a view stays allowed (the panel alone breaks).\n */\n changeAudience?(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /** Synchronous, because the application fetched it before creating the engine. */\n permissions?(definitionId: string): ViewPermissions;\n}\n\n/**\n * One logical write. A retry after a timeout reuses the same `requestId` and\n * the same payload, which is what lets a server deduplicate it.\n */\nexport interface WriteContext {\n requestId: string;\n signal?: AbortSignal;\n}\n\n/** What the current user may do with one definition's views. */\nexport interface ViewPermissions {\n createPersonal: boolean;\n createShared: boolean;\n reorder: boolean;\n setDefault: boolean;\n /**\n * Whether this user edits the definition's **stored** system views\n * (`stored: true`) and creates new ones (`create({ scope: 'system' })`,\n * 「发布为系统视图」), D81. **Absent is false** — unlike everything else\n * here, where silence allows: a system view reaches every user, so only a\n * host that says so opens it, and a store without `permissions` does not.\n * When true, the `instance(id)` answer below applies to a stored system\n * view (save, rename, delete); a system view never moves audience, and\n * one declared in code or in the backend's configuration stays read-only.\n */\n editSystem?: boolean;\n instance(id: string): InstancePermissions;\n}\n\nexport interface InstancePermissions {\n save: boolean;\n rename: boolean;\n delete: boolean;\n /**\n * Whether the view may be moved to the other audience. Absent reads as\n * allowed — silence is not a refusal, as with the rest — and moving it\n * also asks the create permission of the audience it goes to\n * (`createShared` to share it, `createPersonal` to take it back).\n */\n changeAudience?: boolean;\n}\n\n/** An empty preference record, which is what an untouched definition has. */\nexport function emptyPreferences(): ViewPreferences {\n return { order: [], defaultInstanceId: null, revision: '0' };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n audienceOf,\n configBytes,\n isSystemInstanceId,\n isSystemScope,\n MAX_VIEW_CONFIG_BYTES,\n MAX_VIEW_TITLE_LENGTH,\n titleProblem,\n toSummary,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewInstanceSummary,\n type ViewPreferences,\n} from '../model/index.js';\nimport {\n emptyPreferences,\n type ViewPermissions,\n type ViewStore,\n type WriteContext,\n} from './ViewStore.js';\n\nexport interface MemoryViewStoreOptions {\n instances?: ViewInstance[];\n preferences?: Record<string, ViewPreferences>;\n permissions?: (definitionId: string) => ViewPermissions;\n /** Lets an example keep its data across reloads; not a second store. */\n snapshot?: MemorySnapshot;\n}\n\n/**\n * Where a `MemoryViewStore` keeps its state between page loads: the whole\n * state, read and written as one document, synchronously.\n *\n * The store reads it when it is made, again before every write, and again\n * whenever `subscribe` says another writer changed it, so every write is\n * checked against what is stored now rather than what this store last saw\n * (see `MemoryViewStore`). `load` answers `undefined` for nothing readable,\n * and the store then keeps what it holds.\n *\n * `save` throws when the state could not be kept — storage full, blocked,\n * refused. The store then undoes the write in memory and rejects it with a\n * `ViewStoreError` (`UNAVAILABLE`), so nobody is told a view was saved that\n * the next page load will not have.\n */\nexport interface MemorySnapshot {\n load(): MemoryState | undefined;\n save(state: MemoryState): void;\n /** Tells the store that another writer changed the state; answers the unsubscribe. */\n subscribe?(listener: () => void): () => void;\n}\n\nexport interface MemoryState {\n instances: ViewInstance[];\n preferences: Record<string, ViewPreferences>;\n}\n\n/**\n * The one implementation this package ships: a synchronous map behind the\n * port, for tests, examples and query-only use.\n *\n * It keeps the two consistency rules honest rather than convenient. A write\n * with a stale revision conflicts, and a replayed `requestId` returns the\n * first outcome instead of writing twice, so code written against it behaves\n * the same against a real backend — as do the port's list order and the\n * server's limits on a title and a config, which it refuses as the server\n * does (`INVALID`).\n *\n * System views come two ways (D81). One seeded with `scope: 'system'` and\n * no `stored` is a configured one, as the backend's configuration serves\n * it: every write to it is refused (`FORBIDDEN`). One created with\n * `scope: 'system'` — 「发布为系统视图」 — or seeded with `stored: true` is\n * a stored one: saved, renamed and deleted like a shared view, never moved\n * to another audience (`FORBIDDEN`). Like the server, the store asks no\n * permission of its own; `editSystem` is the host's to grant and the\n * engine's to ask.\n *\n * With a snapshot, several stores may share one stored state — two tabs over\n * one `localStorage`. The rule between them is the backend's: **re-read, then\n * compare revisions, one instance (or one definition's preferences) at a\n * time.** Before every write the store reloads the stored state, so a write\n * merges into what the other writer left — a board created in one tab\n * survives a reorder in the other, and ids never collide — and a write whose\n * `revision` the other writer has already moved past is refused as\n * `CONFLICT`, carrying what is stored, as any stale write is. Nothing is ever\n * overwritten because this store's copy was old. A write the snapshot could\n * not keep is undone and rejected as `UNAVAILABLE`: it did not land, so a\n * retry under the same `requestId` is safe.\n */\nexport class MemoryViewStore implements ViewStore {\n private readonly instances = new Map<string, ViewInstance>();\n private readonly preferences = new Map<string, ViewPreferences>();\n /** Outcome per logical instance write, so a retry is idempotent. */\n private readonly outcomes = new Map<string, ViewInstance | null>();\n /** The same rule for preferences, whose outcome is no instance. */\n private readonly preferenceOutcomes = new Map<string, ViewPreferences>();\n private readonly snapshot?: MemorySnapshot;\n readonly permissions?: (definitionId: string) => ViewPermissions;\n private sequence = 0;\n\n constructor(options: MemoryViewStoreOptions = {}) {\n // Left undefined when the caller declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n this.snapshot = options.snapshot;\n\n const restored = options.snapshot?.load();\n this.restore({\n instances: restored?.instances ?? options.instances ?? [],\n preferences: restored?.preferences ?? options.preferences ?? {},\n });\n options.snapshot?.subscribe?.(() => this.reload());\n }\n\n /**\n * In the port's order: system, shared, personal, each oldest first. The\n * map keeps insertion order — the order views were created or seeded in,\n * which a change of audience does not move — and the sort is stable.\n */\n list(definitionId: string): Promise<ViewInstanceSummary[]> {\n const summaries = [...this.instances.values()]\n .filter(instance => instance.definitionId === definitionId)\n .map(toSummary)\n .sort((a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope]);\n return Promise.resolve(summaries);\n }\n\n get(id: string): Promise<ViewInstance> {\n const instance = this.instances.get(id);\n return instance\n ? Promise.resolve(copy(instance))\n : Promise.reject(new ViewStoreError('NOT_FOUND', `No such view: ${id}`));\n }\n\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n const refused = titleRefusal(input.title) ?? configRefusal(input.config);\n if (refused) return Promise.reject(refused);\n this.reload();\n\n // Seeded instances occupy ids too, so the counter walks past anything\n // already taken rather than overwriting it.\n let id: string;\n do {\n this.sequence += 1;\n id = `${input.definitionId}-${this.sequence}`;\n } while (this.instances.has(id));\n if (isSystemInstanceId(id))\n return Promise.reject(\n new ViewStoreError('INVALID', `Reserved id namespace: ${id}`),\n );\n\n // `stored` is the store's to say, never the caller's: a system view\n // created here is one it keeps, and nothing else is one.\n const given = copy(input);\n delete given.stored;\n const instance: ViewInstance = {\n ...given,\n title: input.title.trim(),\n id,\n revision: '1',\n ...(isSystemScope(input.scope) ? { stored: true as const } : {}),\n };\n this.instances.set(id, instance);\n return this.commit(context, instance, () => this.instances.delete(id));\n }\n\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, config: copy(config) }),\n configRefusal(config),\n );\n }\n\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, title: title.trim() }),\n titleRefusal(title),\n );\n }\n\n /**\n * The port's in-place audience change: personal and shared swap, the id\n * and everything else stay. Asked for the audience the view already has,\n * it answers the view unchanged — no revision spent, nothing written — and\n * remembers that answer under the `requestId` like any other outcome.\n * A view a shared (or system) board shows is refused as `INVALID` when it\n * would become personal, `boards` naming those boards by title. A system\n * view, stored or not, never moves (`FORBIDDEN`).\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(id, revision, context, current => {\n if (isSystemScope(current.scope))\n return new ViewStoreError('FORBIDDEN', 'System views stay system');\n if (audienceOf(current.scope) === audience) return null;\n if (audience === 'personal') {\n const boards = this.sharedBoardsShowing(id);\n if (boards.length > 0)\n return new ViewStoreError(\n 'INVALID',\n `Shared dashboards show view ${id}: ${boards.join(', ')}`,\n { boards },\n );\n }\n return { ...current, scope: audience };\n });\n }\n\n delete(id: string, revision: string, context: WriteContext): Promise<void> {\n if (this.outcomes.has(context.requestId)) return Promise.resolve();\n this.reload();\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n // Deleting a configured system view is refused exactly as overwriting\n // one is: it is declared in code or by operations, and no user write\n // reaches it. A stored one is deleted like a shared view (unpublished).\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n this.instances.delete(id);\n const refused = this.persist(() => this.instances.set(id, current));\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, null);\n return Promise.resolve();\n }\n\n getPreferences(definitionId: string): Promise<ViewPreferences> {\n return Promise.resolve(\n this.preferences.get(definitionId) ?? emptyPreferences(),\n );\n }\n\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences> {\n // A replay answers with the outcome the first attempt produced, as every\n // other write does: a retry after a lost answer is the same logical\n // write, and reporting a conflict for it would be a lie.\n const replayed = this.preferenceOutcomes.get(context.requestId);\n if (replayed) return Promise.resolve(replayed);\n this.reload();\n\n const held = this.preferences.get(definitionId);\n const current = held ?? emptyPreferences();\n if (current.revision !== preferences.revision)\n return Promise.reject(\n new ViewStoreError(\n 'CONFLICT',\n `Preferences for ${definitionId} changed`,\n { preferences: current },\n ),\n );\n\n const next: ViewPreferences = {\n ...preferences,\n revision: nextRevision(current.revision),\n };\n this.preferences.set(definitionId, next);\n const refused = this.persist(() =>\n held\n ? this.preferences.set(definitionId, held)\n : this.preferences.delete(definitionId),\n );\n if (refused) return Promise.reject(refused);\n this.preferenceOutcomes.set(context.requestId, next);\n return Promise.resolve(next);\n }\n\n /**\n * One instance write: replay, the refusal of its input (`refused`, as the\n * server validates a command before it reaches the view), re-read, the\n * three refusals every instance write shares, then `change`. It may answer\n * `null` for a write that changes nothing — the view is answered as it is\n * and the revision is not spent — or a `ViewStoreError` for a refusal of\n * its own.\n */\n private update(\n id: string,\n revision: string,\n context: WriteContext,\n change: (current: ViewInstance) => ViewInstance | ViewStoreError | null,\n refused?: ViewStoreError,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n if (refused) return Promise.reject(refused);\n this.reload();\n\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n const changed = change(current);\n if (changed instanceof ViewStoreError) return Promise.reject(changed);\n if (changed === null) {\n this.outcomes.set(context.requestId, current);\n return Promise.resolve(copy(current));\n }\n const next: ViewInstance = {\n ...changed,\n revision: nextRevision(current.revision),\n };\n this.instances.set(id, next);\n return this.commit(context, next, () => this.instances.set(id, current));\n }\n\n /**\n * The titles of the boards everyone sees that show `id` in a panel — the\n * reference the dashboard kernel's `coversScope` guards from the board's\n * side. Read off the stored configs as the untrusted JSON they are: the\n * store may import nothing but the model.\n */\n private sharedBoardsShowing(id: string): string[] {\n const boards: string[] = [];\n for (const instance of this.instances.values()) {\n const { config } = instance;\n if (\n config.kind !== 'dashboard' ||\n audienceOf(instance.scope) !== 'shared'\n )\n continue;\n const panels: unknown = config.panels;\n if (Array.isArray(panels) && panels.some(panel => shows(panel, id)))\n boards.push(instance.title);\n }\n return boards;\n }\n\n private expect(\n current: ViewInstance,\n revision: string,\n ): ViewStoreError | undefined {\n return current.revision === revision\n ? undefined\n : new ViewStoreError(\n 'CONFLICT',\n `View ${current.id} moved to revision ${current.revision}`,\n { instance: current },\n );\n }\n\n private commit(\n context: WriteContext,\n instance: ViewInstance,\n undo: () => void,\n ): Promise<ViewInstance> {\n const refused = this.persist(undo);\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, instance);\n return Promise.resolve(copy(instance));\n }\n\n /**\n * Hands the state to the snapshot. When it could not be kept, the change\n * just made is undone — memory goes back to what is stored — and the\n * refusal is answered, so the write rejects rather than being reported as\n * saved. No outcome is remembered for it, so a retry writes again.\n */\n private persist(undo: () => void): ViewStoreError | undefined {\n if (!this.snapshot) return undefined;\n try {\n this.snapshot.save({\n instances: [...this.instances.values()].map(instance => copy(instance)),\n preferences: Object.fromEntries(this.preferences),\n });\n return undefined;\n } catch (error) {\n undo();\n return new ViewStoreError(\n 'UNAVAILABLE',\n `The view store could not keep this write: ${reasonOf(error)}`,\n { storage: true },\n );\n }\n }\n\n /**\n * Takes the stored state as it is now, when there is one to read: before a\n * write, so the write is checked against it, and when another writer says\n * it changed. Nothing readable leaves what the store holds as it is.\n */\n private reload(): void {\n const stored = this.snapshot?.load();\n if (stored) this.restore(stored);\n }\n\n private restore(state: MemoryState): void {\n this.instances.clear();\n this.preferences.clear();\n for (const instance of state.instances)\n this.instances.set(instance.id, copy(instance));\n for (const [definitionId, preferences] of Object.entries(state.preferences))\n this.preferences.set(definitionId, preferences);\n }\n}\n\n/**\n * Whether a stored panel references the saved view `id`, by any of the\n * three members the server reads (`ViewConfigs.PANEL_REFERENCES`, and\n * `DashboardPanel`): the view it shows (`instanceId`, unless the board owns\n * the view, `owned`), the view 「在工作台中打开」 opens (`opens`), and the\n * one a press opens (`click.instanceId`).\n */\nfunction shows(panel: unknown, id: string): boolean {\n if (typeof panel !== 'object' || panel === null) return false;\n const { instanceId, owned, opens, click } = panel as {\n instanceId?: unknown;\n owned?: unknown;\n opens?: unknown;\n click?: unknown;\n };\n if (owned === undefined && instanceId === id) return true;\n if (opens === id) return true;\n return (\n typeof click === 'object' &&\n click !== null &&\n (click as { instanceId?: unknown }).instanceId === id\n );\n}\n\n/** A system view no write reaches: configured, not one this store keeps. */\nfunction readOnlySystem(instance: ViewInstance): boolean {\n return isSystemScope(instance.scope) && instance.stored !== true;\n}\n\n/** System views first, then shared, then personal: the port's list order. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstance['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/**\n * The revision after `current`. Revisions are opaque to the port, and a host\n * may seed any string; one this store did not write as a count (`'ops-1'`)\n * starts the count again at `'1'`, which it can never have been, so a write\n * against it still conflicts. A count goes on counting.\n */\nfunction nextRevision(current: string): string {\n return /^(0|[1-9]\\d{0,14})$/.test(current)\n ? String(Number(current) + 1)\n : '1';\n}\n\n/** A title the server refuses (`ViewConfigs.requireTitle`), in its words. */\nfunction titleRefusal(title: string): ViewStoreError | undefined {\n switch (titleProblem(title)) {\n case 'empty':\n return new ViewStoreError('INVALID', \"A view's title must not be blank.\");\n case 'too-long':\n return new ViewStoreError(\n 'INVALID',\n `A view's title is longer than ${MAX_VIEW_TITLE_LENGTH} characters.`,\n );\n default:\n return undefined;\n }\n}\n\n/** A config larger than the server keeps, in its words. */\nfunction configRefusal(config: ViewConfig): ViewStoreError | undefined {\n const bytes = configBytes(config);\n return bytes > MAX_VIEW_CONFIG_BYTES\n ? new ViewStoreError(\n 'INVALID',\n `A view's config is ${bytes} bytes; the limit is ${MAX_VIEW_CONFIG_BYTES}.`,\n )\n : undefined;\n}\n\n/** What a refusal said — a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n\n/**\n * A structural copy, so nothing a caller holds is the object the store keeps.\n * A config handed in or read back is a plain JSON tree, and a caller editing\n * one it still has a reference to must not change what is stored.\n */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n"],"mappings":";;;;AAmCA,SAAgBS,GACdC,GACAC,GAC8B;CAC9B,IAAID,MAAS,IAAO;CACpB,IAAMG,KAAYC,MAChBA,EAAMJ,KAAKK,aAAa,KAAQ,OAAQD,EAAMJ,KAAKK,YAAY,CAAC,GAC5DC,IAAkD;EACtDN,MAAMA,KAAQ,CAAC;EACfC,QAAQ,CAAC;EACTO,UAAU,CAAC;CACb;CACA,KAAK,IAAMJ,KAASH,GAAQ;EAC1B,IAAMQ,IAAML,EAAMM,YAAYP,EAASC,CAAK,IAAI;EAChD,IAAKK,GACL;OAAIL,EAAMO,UAAU;IAClB,IAAMC,IAA6C,CAAC;IACpD,KAAK,IAAME,KAASV,EAAMO,UAAU;KAClC,IAAMI,IAAMZ,EAASW,CAAK;KAC1B,AAAIC,MAAKH,EAAQE,EAAME,MAAMC,QAAQF;IACvC;IACA,EAAMP,SAA4CJ,EAAMY,MAAMC,QAC5DL;GACJ,OACE,EAAMX,OAA6CG,EAAMY,MAAMC,QAC7DR;EAAAA;CACN;CACA,OAAOH;AACT;AAGA,SAAgBY,GACdZ,GACAL,GACAkB,GACAC,GACgC;CAChC,IAAKd,GACL,OAAOT,GACLS,GACAL,EAAOoB,KAAIjB,MAASA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