Full Code of zaidka/genieacs for AI

master 7546ab833a99 cached
187 files
1.6 MB
486.3k tokens
1209 symbols
1 requests
Download .txt
Showing preview only (1,750K chars total). Download the full file or copy to clipboard to get everything.
Repository: zaidka/genieacs
Branch: master
Commit: 7546ab833a99
Files: 187
Total size: 1.6 MB

Directory structure:
gitextract_j_xjh90s/

├── .gitignore
├── .prettierignore
├── AGENTS.md
├── ARCHITECTURE.md
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── bin/
│   ├── genieacs-cwmp.ts
│   ├── genieacs-ext.ts
│   ├── genieacs-fs.ts
│   ├── genieacs-nbi.ts
│   └── genieacs-ui.ts
├── build/
│   ├── assets.ts
│   ├── build.ts
│   ├── generate-fonts.sh
│   ├── lint.ts
│   ├── spellcheck-dict.pws
│   ├── spellcheck.sh
│   └── test.ts
├── docs/
│   ├── .readthedocs.yaml
│   ├── administration-faq.rst
│   ├── api-reference.rst
│   ├── conf.py
│   ├── cpe-authentication.rst
│   ├── environment-variables.rst
│   ├── ext-sample.js
│   ├── extensions.rst
│   ├── https.rst
│   ├── index.rst
│   ├── installation-guide.rst
│   ├── provisions.rst
│   ├── requirements.txt
│   ├── roles-and-permissions.rst
│   └── virtual-parameters.rst
├── eslint.config.mjs
├── lib/
│   ├── api-functions.ts
│   ├── auth.ts
│   ├── bundle-views.ts
│   ├── cache.ts
│   ├── cluster.ts
│   ├── common/
│   │   ├── authorizer.ts
│   │   ├── debounce.ts
│   │   ├── errors.ts
│   │   ├── expression/
│   │   │   ├── evaluate.ts
│   │   │   ├── normalize.ts
│   │   │   ├── pagination.ts
│   │   │   ├── parser.ts
│   │   │   └── synth.ts
│   │   ├── expression.ts
│   │   ├── memoize.ts
│   │   ├── path-set.ts
│   │   ├── path.ts
│   │   └── yaml.ts
│   ├── config.ts
│   ├── connection-request.ts
│   ├── cwmp/
│   │   ├── db.ts
│   │   └── local-cache.ts
│   ├── cwmp.ts
│   ├── db/
│   │   ├── db.ts
│   │   ├── synth.ts
│   │   ├── types.ts
│   │   └── util.ts
│   ├── debug.ts
│   ├── default-provisions.ts
│   ├── device.ts
│   ├── extensions.ts
│   ├── forwarded.ts
│   ├── fs.ts
│   ├── gpn-heuristic.ts
│   ├── init.ts
│   ├── instance-set.ts
│   ├── local-cache.ts
│   ├── lock.ts
│   ├── logger.ts
│   ├── nbi.ts
│   ├── ping.ts
│   ├── query.ts
│   ├── sandbox.ts
│   ├── scheduling.ts
│   ├── server.ts
│   ├── session.ts
│   ├── soap.ts
│   ├── types.ts
│   ├── ui/
│   │   ├── api.ts
│   │   ├── db.ts
│   │   └── local-cache.ts
│   ├── ui.ts
│   ├── util.ts
│   ├── versioned-map.ts
│   ├── xml-parser.ts
│   └── xmpp-client.ts
├── npm-shrinkwrap.json
├── package.json
├── seed/
│   ├── bootstrap.js
│   ├── datamodel-explorer.jsx
│   ├── default.js
│   ├── device-page-tr098.jsx
│   ├── device-page-tr181.jsx
│   ├── device-page.jsx
│   ├── icon.jsx
│   ├── inform.js
│   ├── instance-table.jsx
│   ├── overview-page.jsx
│   ├── parameter.jsx
│   ├── pie-chart.jsx
│   ├── provisions.d.ts
│   ├── summon-button.jsx
│   ├── tags.jsx
│   ├── tsconfig.json
│   └── views.d.ts
├── test/
│   ├── auth.ts
│   ├── db.ts
│   ├── device.ts
│   ├── mocks/
│   │   └── store.ts
│   ├── pagination.ts
│   ├── path-set.ts
│   ├── path.ts
│   ├── ping.ts
│   ├── reactive-store.ts
│   ├── signals.ts
│   ├── synth.ts
│   ├── util.ts
│   ├── xml-parser.ts
│   ├── yaml-tests.json
│   └── yaml.ts
├── tsconfig.json
└── ui/
    ├── app.ts
    ├── autocomplete-compnent.ts
    ├── change-password-component.ts
    ├── code-editor-component.ts
    ├── codemirror-loader.ts
    ├── components/
    │   ├── all-parameters.ts
    │   ├── container.ts
    │   ├── device-actions.ts
    │   ├── device-faults.ts
    │   ├── device-link.ts
    │   ├── loading.ts
    │   ├── overview-dot.ts
    │   ├── parameter-list.ts
    │   ├── parameter-table.ts
    │   ├── parameter.ts
    │   ├── ping.ts
    │   ├── summon-button.ts
    │   └── tags.ts
    ├── components.ts
    ├── config-functions.ts
    ├── config-page.ts
    ├── config.ts
    ├── css/
    │   └── app.css
    ├── datalist.ts
    ├── device-page.ts
    ├── devices-page.ts
    ├── drawer-component.ts
    ├── dynamic-loader.ts
    ├── error-page.ts
    ├── faults-page.ts
    ├── files-page.ts
    ├── filter-component.ts
    ├── index-table-component.ts
    ├── layout.tsx
    ├── login-page.tsx
    ├── long-text-component.ts
    ├── notifications.ts
    ├── overlay.ts
    ├── overview-page.ts
    ├── permissions-page.ts
    ├── pie-chart-component.ts
    ├── presets-page.ts
    ├── provisions-page.ts
    ├── put-form-component.ts
    ├── reactive-store.ts
    ├── signals.ts
    ├── skewed-date.ts
    ├── smart-query.ts
    ├── store.ts
    ├── tailwind-utility-components.ts
    ├── task-queue.ts
    ├── timeago.ts
    ├── ui-config-component.ts
    ├── users-page.ts
    ├── views-bundle-placeholder.ts
    ├── views-page.ts
    ├── views.ts
    ├── virtual-parameters-page.ts
    ├── wizard-page.ts
    └── yaml-loader.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*~
node_modules
dist
docs/_build


================================================
FILE: .prettierignore
================================================
dist
npm-shrinkwrap.json


================================================
FILE: AGENTS.md
================================================
# AGENTS.md — GenieACS

GenieACS is a TR-069 Auto Configuration Server for remote management of CPE
devices (routers, modems, gateways). TypeScript codebase compiled with esbuild,
backed by MongoDB.

## Architecture Overview

Four services share a single MongoDB instance:

- **CWMP** (port 7547) — TR-069 protocol handler; manages device sessions
- **NBI** (port 7557) — Northbound REST API for external consumers
- **FS** (port 7567) — File server for firmware/config (GridFS-backed)
- **UI** (port 3000) — Web interface (Koa backend + Mithril.js SPA frontend)

Key subsystems: expression engine (`lib/common/expression/`) compiles a
Lisp-like DSL used for queries, config, and authorization; session engine
(`lib/session.ts`) drives CWMP interactions via declarations rather than
imperative RPCs; sandbox (`lib/sandbox.ts`) runs user-defined provision scripts
in `vm.Script` with deterministic replay.

Read `ARCHITECTURE.md` for a full map of the codebase when working on unfamiliar
areas. It covers service boundaries, the expression pipeline, the path system,
the CWMP session state machine, the database layer, and architectural
invariants.

## Project Structure

- `lib/` — Core server-side logic
- `lib/common/` — Shared code (runs in both Node.js and browser)
- `lib/db/` — MongoDB database layer
- `lib/ui/` — UI backend helpers
- `ui/` — Frontend SPA (Mithril.js)
- `bin/` — Service entry points (5 executables)
- `build/` — Build scripts (esbuild pipeline)
- `test/` — Unit tests (node:test)
- `docs/` — User docs (Sphinx/reStructuredText)
- `public/` — Static assets (favicon, logo)

## Build / Lint / Test Commands

```bash
npm run build # Production build (esbuild pipeline -> dist/)
NODE_ENV=development npm run build # Dev build (no minification)
npm run lint # Prettier + ESLint + tsc --noEmit in parallel
npm test # Compile tests with esbuild, run with node --test
```

### Running a Single Test File

```bash
esbuild --log-level=warning --bundle --platform=node --target=node18 \
  --packages=external --sourcemap=inline --outdir=test test/path.ts \
  && node --test --enable-source-maps test/path.js \
  && rm test/path.js
```

### Running a Single Test Case

```bash
esbuild --log-level=warning --bundle --platform=node --target=node18 \
  --packages=external --sourcemap=inline --outdir=test test/path.ts \
  && node --test --enable-source-maps --test-name-pattern="^parse$" test/path.js \
  && rm test/path.js
```

### Lint Sub-commands

```bash
prettier --prose-wrap always --write .
eslint 'bin/*.ts' 'lib/**/*.ts' 'ui/**/*.ts' 'test/**/*.ts' 'build/**/*.ts'
tsc --noEmit
```

## Before Committing

Read `CONTRIBUTING.md` and ensure your changes comply with it. In particular:

- Run `npm run lint` and `npm test` and fix any failures.
- Follow the code style, naming, import, and comment conventions documented
  there.
- Use the Conventional Commits format for commit messages.


================================================
FILE: ARCHITECTURE.md
================================================
# Architecture

This document describes the high-level architecture of GenieACS. If you want to
familiarize yourself with the codebase, you are in the right place.

## Bird's Eye View

GenieACS is a TR-069 Auto Configuration Server (ACS). It manages CPE devices
(routers, modems, gateways) using the CWMP protocol (TR-069). The system
consists of four network-facing services that share a MongoDB database:

```
                  +------------+
  CPE Devices --->| CWMP (7547)|-+
                  +------------+ |
                  +-----------+  |     +---------+
  CPE Devices --->| FS (7567) |--+---->| MongoDB |
                  +-----------+  |     +---------+
                  +-----------+  |
  OSS / Scripts ->| NBI (7557)|--+
                  +-----------+  |
                  +-----------+  |
  Administrators->| UI (3000) |--+
                  +-----------+
```

- **CWMP** -- The core TR-069 protocol server. CPE devices connect here to
  report their state and receive configuration instructions via SOAP/XML over
  HTTP.
- **NBI** -- Northbound Interface. A REST API for external systems (OSS/BSS,
  scripts, automation) to manage devices, tasks, presets, and configuration
  programmatically.
- **FS** -- File Server. Serves firmware images and configuration files to CPE
  devices during download operations.
- **UI** -- Web interface. A Koa-based backend serving a Mithril.js single-page
  application for administrators to browse devices, manage configuration, and
  trigger operations.

All four services follow the same process model: a primary process forks
configurable worker processes via Node.js `cluster` (see `cluster.ts`). Workers
connect to MongoDB and start an HTTP(S) server.

## Code Map

```
bin/                        Service entry points (5 executables)
lib/                        All backend logic
  common/                   Shared utilities (expression engine, Path, errors)
    expression.ts           Expression class hierarchy (base + subclasses)
    expression/             Expression parser, evaluator, normalizer, minimizer
  cwmp/                     CWMP-service-specific DB and caching
  db/                       Database layer (MongoDB collections, query synthesis)
  ui/                       UI-service-specific API, DB, and caching
  types/                    (empty, reserved)
ui/                         Frontend SPA (Mithril.js)
  components/               Reusable UI components (parameter, tags, ping, etc.)
  css/                      Stylesheets (vanilla CSS)
  icons/                    SVG icons (compiled into a sprite)
test/                       Unit tests (Node.js native test runner)
build/                      Build scripts (esbuild-based)
public/                     Static assets (logo, favicon)
```

### Entry Points (`bin/`)

Each file in `bin/` bootstraps one service. They are structurally identical:
initialize logging, read config, fork workers in the primary process, connect to
MongoDB and start the HTTP server in each worker.

- `genieacs-cwmp.ts` -- CWMP service. Unique in that it disables HTTP keep-alive
  (`keepAliveTimeout: 0`) and provides custom `onConnection` / `onClientError`
  hooks for TR-069 session lifecycle management.
- `genieacs-nbi.ts` -- NBI service. Straightforward REST API server.
- `genieacs-fs.ts` -- File server. The leanest service; does not use the
  extensions subsystem.
- `genieacs-ui.ts` -- UI service. Wraps the Koa application as the HTTP
  listener.
- `genieacs-ext.ts` -- **Not a service.** This is a child process worker spawned
  by the extensions subsystem. It communicates with its parent via IPC,
  executing user-defined extension scripts in isolation.

### The Expression System (`lib/common/expression.ts`, `lib/common/expression/`)

The `Expression` class (defined in `lib/common/expression.ts`) is the most
important abstraction in the codebase. It uses a typed class hierarchy:
`Expression.Literal` (wraps `string | number | boolean | null`),
`Expression.Parameter` (wraps a `Path`), `Expression.Binary` (operator +
left/right), `Expression.Unary` (operator + operand), `Expression.FunctionCall`
(name + args), and `Expression.Conditional` (condition/then/otherwise). For
example, in the SQL-like text syntax:

```
Device.ModelName = "BrandX" AND Events.Inform > 1000
```

Expressions are used pervasively:

- **Query/filter language** -- Database queries for devices, faults, presets,
  etc. are all represented as expressions and compiled to MongoDB filters.
- **Configuration values** -- Config entries and preset preconditions are
  expressions, enabling dynamic evaluation.
- **Authorization** -- Permission filters and validators are expressions.
- **Pagination cursors** -- Keyset pagination boundaries are expressed as filter
  expressions.

The expression pipeline flows through four modules:

1. `parser.ts` -- Parses a SQL-like text syntax into the AST using a hand-rolled
   recursive descent parser with a `Cursor`-based scanner. Also provides
   `stringifyExpression()` for serialization. The `map()` / `mapAsync()`
   tree-walking primitives are abstract methods on the `Expression` class, and
   `stringify()` is now `Expression.toString()`.
2. `normalize.ts` -- Algebraic normalization using exact rational polynomial
   arithmetic over native `bigint` values. The `Polynomial` class extends
   `Expression` as an intermediate representation. Ensures equivalent
   expressions have the same canonical form (e.g., `a + 2 > b` and `a > b - 2`
   normalize identically).
3. `synth.ts` -- Boolean logic minimization via the Espresso algorithm
   (espresso-iisojs). Converts expressions to minimal sum-of-products form with
   three-valued logic (true/false/null). Handles domain-specific constraints
   like comparison ordering and LIKE pattern relationships.
4. `evaluate.ts` -- Runtime evaluation. The `reduce()` function evaluates
   operators on literal values and supports partial evaluation (returns a
   reduced expression if some values are unknown). Parameter resolution is
   handled by the `Expression.evaluate()` method (in `lib/common/expression.ts`)
   which calls `reduce()` after mapping children via a user-supplied callback.

`pagination.ts` implements cursor-based pagination by generating filter
expressions from sort-key bookmarks.

### The Path System (`lib/common/path.ts`, `lib/common/path-set.ts`)

`Path` represents a TR-069 parameter path (e.g., `Device.WiFi.SSID.1.Name`).
Paths can contain wildcards (`*`) and alias expressions (`[key:value]`) for
query-based addressing.

Key design decisions:

- **Cached** -- `Path.parse()` caches instances in a two-generation LRU cache
  rotated every 120 seconds. The constructor is public (used directly by the
  parser and by methods like `slice()`, `concat()`, and `stripAlias()`).
- **Bitmask encoding** -- The `wildcard` and `alias` fields are bitfields for
  O(1) segment-type checking. This limits paths to 32 segments. A `colon` field
  tracks the number of attribute path segments (after a `:` separator), enabling
  `paramLength` and `attrLength` accessors.
- **Immutable** -- Segment arrays are `Object.freeze()`-d.

`PathSet` is a multi-indexed collection of paths supporting pattern-matching
queries. It maintains separate `paramSegmentIndex` and `attrSegmentIndex` arrays
(one `Map<string, Set<Path>>` per position), plus a `stringIndex` map. The
`find()` method takes bitmasks to control which segments require exact matches
vs. wildcard compatibility, then uses set intersection across the smallest index
sets. A higher-level `findCompat()` method computes the appropriate bitmasks for
superset/subset matching.

### CWMP Protocol Layer (`lib/cwmp.ts`, `lib/soap.ts`, `lib/xml-parser.ts`)

`xml-parser.ts` is a custom single-pass XML parser (no DOM). It scans
character-by-character with bitwise state flags, building a tree of elements
with namespace support. Does not support CDATA.

`soap.ts` handles both parsing CPE SOAP messages and generating ACS SOAP
responses. It dispatches on the SOAP body's method name to type-specific parsers
for Inform, TransferComplete, GetParameterNamesResponse, etc. Supports CWMP
versions 1.0 through 1.4.

`cwmp.ts` is the HTTP-level CWMP request handler. It manages the session state
machine:

1. **State 0** -- Expects an Inform. Authenticates the device (Basic or Digest
   auth, configurable via expression). Acquires a distributed lock. Loads device
   data from MongoDB. Sends InformResponse.
2. **State 1** -- Waits for the CPE to send an empty POST (ready for ACS RPCs).
   Processes any TransferComplete messages.
3. **State 2** -- The ACS drives RPCs (GetParameterNames, GetParameterValues,
   SetParameterValues, AddObject, DeleteObject, Download, Reboot, FactoryReset).
   The CPE responds to each.

Session persistence across TCP disconnects: when a socket closes mid-session,
the entire `SessionContext` is serialized to Redis (the MongoDB `cache`
collection) and restored when the CPE reconnects (identified by a session
cookie).

### Session Engine (`lib/session.ts`)

The session engine implements the **declaration-driven data fetching** pattern.
Rather than issuing RPCs imperatively, provisions create `Declaration` objects
stating what paths and attributes they need to read or write. The engine then:

1. Processes all declarations into a `SyncState` -- a structured plan of which
   parameters to refresh, which values to set, which instances to create/delete,
   etc.
2. Generates the minimal set of CWMP RPCs needed to fulfill the plan.
3. After each RPC response, updates `DeviceData` and re-evaluates.
4. Iterates until all declarations are satisfied.

The preset system (`applyPresets` in `cwmp.ts`) implements a policy engine:
presets are rules with precondition expressions that, when matched, contribute
provisions to the session. After provisions execute, if device data changed,
presets are re-evaluated (up to 4 cycles to prevent infinite loops).

### Provisions and Virtual Parameters

**Provisions** are the unit of configuration intent. Built-in provisions
(`default-provisions.ts`) include `refresh`, `value`, `tag`, `reboot`, `reset`,
`download`, and `instances`. Custom provisions are user-defined JavaScript
scripts stored in the `provisions` MongoDB collection.

**Virtual parameters** are scripts that present computed/derived values as if
they were real device parameters under the `VirtualParameters.*` namespace. They
run in two phases: a "get" phase reads real parameters and returns a computed
value; a "set" phase translates a desired value into real parameter changes.
Virtual parameters can reference other virtual parameters (up to depth 8).

### Sandbox (`lib/sandbox.ts`)

The sandbox provides a secure execution environment for provision and virtual
parameter scripts using `vm.Script` with a 50ms timeout. It uses a
**replay-based execution model**:

1. A script runs and calls `declare()` to request data.
2. When `commit()` is called, the script throws a sentinel symbol and exits.
3. The engine fetches the requested data via CWMP RPCs.
4. The script is **re-run from the beginning** with the fetched data available.
5. Earlier `declare()` calls return cached results; the script progresses
   further.
6. This repeats until the script completes without throwing.

The sandbox API: `declare(path, timestamps, values)` returns a
`ParameterWrapper` proxy; `clear(path, timestamp, attributes)` invalidates
cached data; `ext(...args)` calls external extensions (results are cached per
revision to survive replays); `commit()` explicitly triggers a fetch cycle.
`Math.random()` is replaced with a seeded PRNG for determinism.

### Device Data Model (`lib/types.ts`, `lib/device.ts`)

`DeviceData` is the in-memory working copy of a device's parameter tree during a
session:

- `paths: PathSet` -- All known parameter paths.
- `timestamps: VersionedMap<Path, number>` -- When each path was last refreshed.
- `attributes: VersionedMap<Path, Attributes>` -- Per-path attributes (object,
  writable, value, notification, accessList), each paired with a timestamp.
- `trackers` / `changes` -- Change tracking for re-evaluation.

`VersionedMap` (in `versioned-map.ts`) provides multi-revision snapshots,
enabling the sandbox replay model where scripts may be re-run at different
revision levels.

`device.ts` handles setting and clearing parameter data with invariant
enforcement (e.g., if `value` is set, `object` is forced to 0; parent paths are
ensured to exist). The `unpack()` function resolves wildcards and alias paths
against concrete device data.

### NBI (`lib/nbi.ts`)

A raw Node.js HTTP listener (no framework) with regex-based URL routing.
Endpoints include CRUD for presets, provisions, virtual parameters, objects, and
files; device task management (with optional synchronous execution via
connection request); fault management; generic collection querying; and ping.

The NBI uses MongoDB-style JSON queries directly. For the `devices` collection,
`query.ts` expands user-friendly queries by auto-appending `._value` to
parameter paths and generating multi-type interpretations (string, number, date,
regex) for filter values.

### File Server (`lib/fs.ts`)

A minimal HTTP file server reading from MongoDB GridFS. Supports GET/HEAD with
full HTTP caching (ETag, Last-Modified, If-None-Match, If-Modified-Since) and
Range requests (HTTP 206) for partial content downloads. Files are cached
in-memory via memoization.

### UI Backend (`lib/ui.ts`, `lib/ui/`)

A Koa application with JWT authentication, role-based authorization, and a rich
CRUD API under `/api/`. The root route serves an HTML shell that bootstraps the
Mithril.js SPA with injected config, user info, and hashed asset filenames.

`lib/ui/api.ts` defines generic CRUD endpoints for all resource types (devices,
presets, provisions, files, config, users, permissions, faults, tasks) with
authorization checks at every level. Specialized endpoints handle file
upload/download, synchronous task execution, tag management, password changes,
and CSV export.

`lib/ui/db.ts` translates between the UI's flat parameter representation and
MongoDB's nested document structure. The `flattenDevice()` function is the key
transformation: it recursively walks the nested device document and produces a
flat key-value map with colon-delimited attribute keys (e.g.,
`"Device.WiFi.SSID.1.Name" -> value`,
`"Device.WiFi.SSID.1.Name:type" -> "xsd:string"`,
`"Device.WiFi.SSID.1.Name:writable" -> true`). The `FlatDevice` type is
`Record<string, Value>` where `Value = string | number | boolean | null`.

`lib/ui/local-cache.ts` caches permissions, users, and config in-process with
hash-based revision tracking. The `getConfig()` function uses typed overloads --
it takes a typed default value (`string`, `number`, or `boolean`) and an
expression evaluation callback, returning a value of the same type as the
default.

### Database Layer (`lib/db/`)

`db/db.ts` is the single entry point to MongoDB. It manages 14 collections:

| Collection          | Purpose                          |
| ------------------- | -------------------------------- |
| `devices`           | CPE device parameter trees       |
| `presets`           | Configuration rules              |
| `provisions`        | Provision scripts                |
| `virtualParameters` | Virtual parameter scripts        |
| `objects`           | Generic objects                  |
| `tasks`             | Queued device management tasks   |
| `faults`            | Error records with retry state   |
| `operations`        | In-flight async operations       |
| `files` (GridFS)    | Firmware images and config files |
| `permissions`       | RBAC rules                       |
| `users`             | User accounts                    |
| `config`            | Key-value configuration          |
| `cache`             | Distributed cache (TTL index)    |
| `locks`             | Distributed locks (TTL index)    |

`db/synth.ts` is the sophisticated expression-to-MongoDB query compiler. It
normalizes expressions, converts them to a Boolean satisfiability representation
using the `Clause` hierarchy, minimizes via Espresso, and emits MongoDB
`$and`/`$or`/`$not` filter objects. This is used by the UI backend.

`cwmp/db.ts` handles CWMP-specific persistence: loading the nested device
document into `DeviceData` (`fetchDevice`), diffing changes back into MongoDB
update operations (`saveDevice`), and managing faults, tasks, and operations.

### Query Systems

There are two separate query paths:

1. **NBI queries** (`lib/query.ts`) -- Processes MongoDB-style JSON queries from
   external API consumers. Expands parameter names, generates multi-type value
   interpretations, and passes through to MongoDB directly.

2. **UI/Expression queries** (`lib/db/synth.ts`) -- Compiles the internal
   expression language into optimized MongoDB filters via Boolean minimization.
   This is the more sophisticated path, used by the UI backend.

### Frontend (`ui/`)

A Mithril.js SPA with hash-based routing (`#!/`). Key modules:

- `app.ts` -- Route definitions. The `pagify()` function wraps each page into a
  `RouteResolver` that handles initialization, error boundaries, and data
  fulfillment.
- `layout.ts` -- Top-level layout (header, navigation, content, overlay).
- `store.ts` -- Centralized data store. Implements a query-based reactive cache
  with deduplication and incremental fetching. The `fulfill()` method (called
  after every render) batches pending queries, computes filter diffs via
  `unionDiff()`, and fetches only missing data. Connection monitoring polls
  every 3 seconds for server health, clock skew, and config changes.
- `components.ts` -- Component registry with a context propagation system. The
  proxied `m()` function resolves string component names and the `m.context()`
  API passes data (like the current device object) down the component tree
  without explicit prop threading.
- `smart-query.ts` -- Translates user-friendly `Label: value` searches into
  filter expressions with type-aware matching (string, number, timestamp, MAC
  address, tag).
- `task-queue.ts` -- Two-stage task pipeline: staging (user configures tasks)
  then queue (tasks are committed and executed via the backend).
- `dynamic-loader.ts` -- Lazy loading of heavy libraries (CodeMirror, YAML) via
  dynamic `import()`.

### Build System (`build/`)

The build is a self-bootstrapping esbuild pipeline (`npm run build` pipes
`build/build.ts` through esbuild then node). It produces:

- **Backend binaries** -- 5 entry points bundled for Node.js 12+ with shebang
  banners, executable permissions, and `.js` extension stripped.
- **Frontend bundle** -- `ui/app.ts` bundled for browsers (ESM, code-split) with
  content-hashed filenames.
- **CSS** -- `ui/css/app.css` bundled and minified with content-hashed output.
- **SVG sprite** -- All icons in `ui/icons/` optimized via SVGO and combined
  into a single sprite.

`build/assets.ts` is a compile-time bridge: at rest it contains placeholder
filenames; during build, the `assetsPlugin` replaces them with actual
content-hashed names so both backend and frontend reference the correct assets.

Build metadata includes the date and a hash derived from the git state, appended
to the package version.

## Cross-Cutting Concerns

### Multi-Level Caching

```
memoize.ts         In-process function cache (2-4 min, two-generation rotation)
     |
local-cache.ts     In-process snapshot cache (5s refresh, hash-based revisions)
     |
cache.ts           MongoDB-backed distributed cache (configurable TTL)
     |
MongoDB            TTL index auto-expiration
```

Each service has its own `local-cache` that periodically checks the distributed
cache for staleness. Distributed locks (`lock.ts`) coordinate rebuilds so only
one worker does the expensive computation.

### Configuration (`lib/config.ts`)

Three-tier priority: CLI args > environment variables (`GENIEACS_*`) > config
file (`config.json`) > defaults. Supports per-device overrides by appending
`-OUI-ProductClass-SerialNumber` to option names.

### Distributed Locking (`lib/lock.ts`)

MongoDB-based mutual exclusion using upsert + duplicate key detection. TTL
indexes prevent deadlocks from crashed processes. Clock skew tolerance of 30
seconds.

### Authentication

- **CWMP devices** -- HTTP Basic or Digest auth, configurable per-device via
  expressions (`auth.ts`).
- **UI users** -- JWT tokens in cookies. Passwords hashed with PBKDF2-SHA512
  (10000 iterations). Role-based authorization via `Authorizer` with
  expression-based filters and validators.

### Connection Requests (`lib/connection-request.ts`)

Three methods to ask a CPE device to initiate a CWMP session:

- **HTTP** -- Standard TR-069 connection request with Digest/Basic auth.
- **UDP** -- For NAT traversal (STUN-based) with HMAC-SHA1 signed messages.
- **XMPP** -- TR-069 Annex K via a full XMPP client (`xmpp-client.ts`).

### Extensions (`lib/extensions.ts`)

User-defined scripts executed in long-lived child processes (`genieacs-ext.ts`)
communicating via IPC. Processes are lazily spawned per script name and reused.
Each request gets a unique ID; responses are matched by ID with a configurable
timeout.

### Logging (`lib/logger.ts`)

Dual-stream structured logging (application + access logs). Supports simple and
JSON formats, systemd journal integration, and automatic log rotation detection.
Protocol traces can be written to a debug file in YAML or JSON format
(`debug.ts`).

### Three-Valued Logic

The system consistently implements SQL-style three-valued logic
(true/false/null). This is visible in expression evaluation, the `Clause`
hierarchy's separate true/false/null methods, and the 2-bit minterm encoding in
the Boolean minimizer. NULL means "unknown" and propagates through operations
following SQL semantics.

## Architectural Invariants

- **The expression system does not depend on any service-specific code.** The
  `lib/common/expression/` modules are pure and shared across all services.

- **The sandbox is deterministic across replays.** `Math.random()` is seeded
  from the device ID, `Date.now()` is controlled, and extension results are
  cached. A script re-run with the same inputs produces the same outputs.

- **Services share no in-process state.** All cross-process coordination goes
  through MongoDB (the `cache` and `locks` collections). Each worker process is
  independent.

- **Device data is never mutated in place during a session.** `VersionedMap`
  provides revision-based snapshots. The sandbox writes to new revisions;
  earlier revisions remain readable for re-evaluation.

- **CWMP session exclusivity.** A distributed lock (`cwmp_session_<deviceId>`)
  ensures only one session exists per device at a time. The lock is refreshed
  periodically and released at session end.

- **The UI backend never queries MongoDB with raw user input.** All queries go
  through the expression-to-MongoDB compiler (`db/synth.ts`), which validates
  and normalizes expressions before generating filters.


================================================
FILE: CHANGELOG.md
================================================
# Change Log

## 1.2.14 (2026-03-12)

- Prevent UI crash when a malformed URL is sent to the server.

- Fix potential edge-case bugs in expression evaluation and session
  serialization.

## 1.2.13 (2024-06-06)

- Increase connection timeout for UI and NBI from 30 to 120 seconds to avoid
  timeouts when running unindexed queries in large deployments.

- Fix race condition causing 503 error when deleting multiple faults at once.

- Fix some UI config options not being evaluated as dynamic expressions.

- Fix an issue where certain edge-case query expressions were not being
  correctly converted to MongoDB queries, resulting in inaccurate search
  results.

## 1.2.12 (2024-03-28)

- Fix broken XMPP support in the previous release.

- Fix regression causing CSV downloads to be buffered in memory before being
  streamed to the client.

## 1.2.11 (2024-03-21)

- Resolved an issue from the previous release that caused incompatibility with
  Node.js versions 12 through 15.

## 1.2.10 (2024-03-18)

- Add support for XMPP connection requests. Use the environment variables
  `XMPP_JID` and `XMPP_PASSWORD` to configure the XMPP connection for the ACS.

- The environment variables `CWMP_SSL_CERT` and `CWMP_SSL_KEY`, as well as their
  counterparts for UI, NBI, and FS, now accept PEM-encoded certificates and keys
  in addition to file paths.

- The UI no longer requires users to refresh the page after modifying presets,
  provisions, or virtual parameters. Refreshing is now only necessary for
  changes to users, permissions, or UI configurations.

- Improved conversion of GenieACS expressions into MongoDB queries for more
  optimized queries and better index utilization.

- Refactor UI pagination and sorting to fix issues from the previous approach,
  especially with sorting by rapidly changing parameters such as 'last inform'
  time.

- The file server now supports HEAD requests, the Range header, and conditional
  requests.

- Addressed an issue causing file server disconnections for slow clients over
  HTTPS.

- Fix bug preventing users from changing their own passwords.

- Introduced a new 'locks' collection for database locking, replacing the
  previous use of the 'cache' collection for this purpose.

- Various other minor fixes and enhancements.

## 1.2.9 (2022-08-22)

- New config option `cwmp.skipRootGpn` to enable a workaround for some
  problematic CPEs that reject GPN requests on data model root.
- Stream query results and CSV downloads as data becomes available instead of
  buffering the entire response.
- Log HTTP/HTTPS client errors in debug log.
- Fix occasional lock expired errors after updating presets, etc.
- Fix bug where queries containing `<>` operator may return incorrect results.
- Fix a performance hit caused by DB calls containing the entire CPE data model
  rather then just the updated parameters.
- Fix bug where tags containing special characters are saved in their encoded
  form when set via a Provision script.
- Fix issue causing invalid `xsd:dateTime` values to be saved in DB as `NaN`
  rather than maintain the original string value.
- Fix bug using `$regex` operator with a numeric or a datetime string.
- Fix ping not working on certain platforms.
- Ping requests are now authenticated.
- Fix error when the `FORWARDED_HEADER` environment variable contains IPv4 CIDR
  while the listening interface is IPv6 and vice versa.
- Fix false warning "unexpected parameter in response" showing in
  `genieacs-cwmp` logs.
- Other minor fixes and stability improvements.

## 1.2.8 (2021-10-27)

- Fix a remote code execution security vulnerability in genieacs-ui.
- All UI components can now be configured using fully dynamic expressions.
  Previously some component types only accept fixed string values as properties.
- The `container` UI component can now be configured with an `element` property
  that's either a string or a nested pair of `tag` and `attributes` properties.
  The various attributes under the `attributes` property can now make use of a
  new function `ENCODEURICOMPONENT()` to facilitate creating custom hyperlinks
  in the UI.
- Improve sorting buttons' behavior in the device listing page and other pages.
  Sorting by multiple columns should now feel more intuitive.
- Support the modulo (%) operator in expressions.
- Fix a regression in the previous release where the config option 'ui.pageSize'
  no longer works.
- Fix process crash when a CPE sends an unsupported ACS method.

## 1.2.7 (2021-09-18)

- Fix regression causing frequent invalid session errors.
- Fix regression breaking digest authentication in connection requests.

## 1.2.6 (2021-09-16)

- New config option `cwmp.downloadSuccessOnTimeout` to enable a workaround for
  CPEs that neglect to send a TransferComplete message after a successful
  download.
- Display a progress bar when uploading new files.
- Default to dual stack interface binding (i.e. `::` instead of `0.0.0.0`).
  Unless the binding interface is explicitly set, this will cause IPv4 addresses
  in the logs to be displayed as IPv4-mapped IPv6 addresses (e.g.
  `::ffff:127.0.0.1` instead of `127.0.0.1`).
- Detect and correct for client side (browser) clock skew that would otherwise
  alter the numbers in the pie charts.
- Various improvements relating to dealing with buggy TR-069 client
  implementations.
- Fix a bug causing "lock expired" exceptions when a CWMP session remains open
  for a very long time due to slow clients.
- Fix metadata of uploaded files going missing due to nginx stripping away what
  it considers to be invalid headers. The nginx directive
  `ignore_invalid_headers` is no longer required.
- Fix crash when a CPE is assigned a tag containing a dot.
- Fix bug preventing the user from closing the preset pop-up after being
  presented with unsupported preset message.
- Fix exceptions raised from ext scripts manifesting as timeout faults.
- Fix download getting triggered repeatedly when the value passed to `Download`
  parameter is greater than the current timestamp.
- Fix crash when passing invalid attributes to `declare`.
- Fix crash in NBI when pushing tasks to non-existing devices.
- Fix crash in NBI when passing invalid JSON to various API endpoints.
- Fix crash when the output from `ping` command cannot be parsed in some rare
  edge cases.
- A number of other fixes and stability improvements.

## 1.2.5 (2021-03-12)

- Support specifying custom types when uploading files.
- Fix JS compatibility issue with Safari browser.

## 1.2.4 (2021-02-24)

- The data model state of a CPE is no longer forgotten after unsuccessful
  session termination (e.g. timeout). This addresses a number of undesired side
  effects that arise when a CPE does not terminate the session properly.
- Executing tasks that take a long time to complete (e.g. refreshing the entire
  data model) no longer shows a timeout error while the task is still being
  processed.
- New function `ROUND()` available to expressions. It works similar to the
  function by the same name in SQLite and PostgreSQL.
- Log access events for `genieacs-nbi` service.
- Pipe stdout/stderr from extension scripts to the `genieacs-cwmp` process log.
- Parameter values of type `xsd:dateTime` are now displayed in the UI and CSV
  downloads as a date string rather than a numeric value.
- Add file download link in the files listing page.
- Display spinner loading animation throughout the UI.
- Display GenieACS version and build number underneath the logo.
- New option to specify how many parameters are displayed at a time in the
  all-parameters component. Simply set `limit` property in the component config.
- Reduce overly strong Brotli compression level which was causing significant
  page load slowdown when Brotli is used.
- Retire dump-data-model tool. `genieacs-sim` can now use a CSV file as its data
  model.
- Reduce the number of concurrent database connections from each process.
- Remove dependency on 'hostInfo' MongoDB command which is a privileged action.
  It is now possible to use shared MongoDB instances with limited privileged.
- Fix bug in NBI where querying files returns 404 error.
- Fix ping not working for devices with an IPv6 address.
- Fix an elusive memory leak in `genieacs-fs` that slowly eats up memory and can
  go unnoticed for long periods of time.
- Fix a rare edge case where a `declare()` call to set a parameter value may not
  work as intended if the parameter was originally received as part of the
  Inform message.
- A number of other fixes and stability improvements.

## 1.2.3 (2020-10-26)

- New config option 'cwmp.skipWritableCheck' for when some CPEs incorrectly
  report writable parameters as non-writable. When set to true, the scripts will
  no longer respect the 'writable' attribute of the CPE parameters and will send
  a SetParamteerValues, AddObject, or DeleteObject request anyway.
- Tags no longer restrict what characters are allowed. Any character other than
  alphanumeric characters, hyphen, or underscore is now encoded in the data
  model (i.e. Tags.\<tag>) using its hex value preceded by "0x".
- Ask for a confirmation before closing a pop-up dialog with unsaved changes.
- Better XML validation to avoid crashes caused by invalid CPE requests.
- Fix confusing 404 error message when the user attempts to modify a resource
  when they don't have the necessary permissions.
- Fix a rare issue where genieacs-cwmp stops accepting new connections after
  running for a few weeks.
- Fix exception when IS NULL operator is used in certain situations.

## 1.2.2 (2020-10-03)

- Added button to push files to selected devices from device listing page.
- A few minor UI improvements.
- Fix exception that can happen and persist after a Download request.
- Fix validation bug preventing running refreshObject task on data model root.
- Fix invalid arguments fault in refresh preset configuration when upgrading
  from v1.1.

## 1.2.1 (2020-09-08)

- Fix bug causing faults to not be displayed in the UI.
- Fix bug where deleting objects does not get reflected immediately in the UI.
- Improve conversion between filters written in the expression format and
  MongoDB queries. There should now be fewer edge cases where the two are not
  equisatisfiable.

## 1.2.0 (2020-09-01)

- Support GetParameterAttributes and SetParameterAttributes TR-069 methods.
- Support CASE statement and COALESCE function in expressions.
- Provision arguments can now be a list of expressions that are dynamically
  evaluated.
- Support Forwarded HTTP header to display in the logs the correct IP of CPEs
  behind a reverse proxy. Must be configured using FORWARDED_HEADER option.
- Config expressions can now access all available device parameters, not only
  serial number, product class, and OUI.
- Use relative URLs throughout the UI to allow serving from a subdirectory using
  a reverse proxy.
- Make Date.parse() and Date.UTC() available to provision scripts.
- libxmljs has been entirely removed in favor of our bespoke XML parser.
- Removed the config option CWMP_KEEP_ALIVE_TIMEOUT. SESSION_TIMEOUT is now used
  to determine the TCP connection timeout.
- The all-parameters component now limits the number of parameters displayed for
  better performance.
- The process genieacs-cwmp is now much less likely to throw exceptions as a
  result of invalid requests from CPE.
- A large number of bug fixes and stability improvements.

## 1.2.0-beta.0 (2019-07-30)

- A brand new UI superseding genieacs-gui.
- New initialization wizard on first run.
- New expression/query language used in search filters and preset preconditions.
- CPE -> ACS authentication is now supported.
- New config option (CWMP_KEEP_ALIVE_TIMEOUT) to specify how long to wait for a
  reply from the CPE before closing the TCP connection.
- Debug logging has been reimplemented utilizing YAML format for logs.
- Handle 9005 faults (Invalid Parameter Name) gracefully by attempting to
  rediscover the path of the missing parameter recursively.
- declare() statements not followed by an explicit commit() are now deferred
  until all currently active scripts have been executed.
- FS_HOSTNAME now defaults to the server's hostname or IP.
- The API now validates the structure of task objects before saving.
- New XML parser implementation for better performance. You can revert to the
  old parser by enabling the config option XML_LIBXMLJS. Requires Node.js v11 or
  v10.
- Performance optimizations. While performance has improved for the majority of
  use cases, there may be situations where performance has degraded. It's
  recommended to revisit your hardware requirements.
- Connection request authentication no longer uses 'auth.js' file. Instead, the
  connection request authentication behavior can now be customized using an
  'expression'.
- The config file (config.json) has been deprecated. System configuration (e.g.
  listen ports, worker count) are now recommended to be passed as environment.
  variables. Other general configuration options are stored in the database so
  as to not require service restart for changes to take effect.
- Optional redis dependency has been removed completely.
- Tags now allow only alphanumeric characters and underscore.
- Supported versions of Node.js and MongoDB are 10.x and up and 2.6 and up
  respectively.

## 1.1.3 (2018-10-23)

- New config option (MAX_COMMIT_ITERATIONS) to avoid max commit iterations
  faults for more complex scripts.
- Support base64 and hexBinary parameter types.
- Strict parsing of number values in queries (e.g. "123abc" no longer accepted
  as 123).
- Mixing $ne and $not operators is not allowed. Now it throws an error instead
  of returning incorrect results.
- When a task expires, any associated fault is also deleted.
- API now accepts 'timeout' argument when posting a task.
- A number of stability fixes.

## 1.1.2 (2018-02-24)

- A large number of bug fixes as well as stability and performance improvements.
- Three security vulnerabilities disclosed by Maximilian Hils have been patched.
- New config option UDP_CONNECTION_REQUEST_PORT to specify binding port for UDP
  connection requests.
- New config option DATETIME_MILLISECONDS to strip milliseconds from dateTime
  values.
- New config option BOOLEAN_LITERAL to use 1/0 or true/false for boolean values.
- Parameter values that cannot be parsed according to the reported type now show
  a warning message.
- Virtual parameter scripts now use the variable 'args' instead of the special
  'TIMESTAMPS' and 'VALUES' variables. The content of the args array is:
  {declare timestamps}, {declare values}, {current timestamps}, {current
  values}.
- Virtual parameter value types are now inferred from the JavaScript type if the
  returned value attribute is not a value-type pair.
- Show a fault when a virtual parameter script doesn't return the required
  attributes.
- Redis is now optional (and disabled by default), reducing the complexity of
  scalable deployments.
- Better detection of cyclical presets resulting in fewer faults for complex
  provisioning scripts.
- Math.random() is now deterministic on per-device basis. A function has been
  added to allow specifying a seed value (e.g. Math.random.seed(Date.now())).
- Overload spikes are now handled gracefully by refusing to accept new sessions
  temporarily when under abnormal load.
- Added log messages for session timeouts, connection drops, and XML parsing
  errors.
- Date.now() now takes an optional argument to specify "time steps" (in
  milliseconds). This can be used to ensure a group of parameters are all
  refreshed at the same time intervals.
- Only the non-default configuration options are now logged at process start.
- Faults caused by errors from extensions now show a cleaner stack trace.
- Exit main process if there are too many worker crashes (e.g. when DB is down).
- Updated dependencies and included a lockfile to ensure installations get the
  exact dependencies it was tested against.

## 1.1.1 (2017-03-23)

- Avoid crashing when connection request credentials are missing.
- Show a warning instead of crashing when failing to parse parameter values
  according to the expected value type.
- Add missing "Registered" event.
- Fix bug where in certain cases many more instances than declared are created.
- Fix parameter discovery bug when declared path timestamp is 1 or is not set.
- Fix preset precondition failing when testing against datetime parameters and
  certain other parameters like \_deviceId.\_ProductClass.

## 1.1.0 (2017-03-10)

- Provisions enable implementing dynamic device configuration or complex device
  provisioning work flow using arbitrary scripts.
- Virtual parameters are user-defined parameters whose values are evaluated from
  a custom script.
- Extensions are sandboxed Node.js scripts that are accessible from provision
  and virtual parameter scripts to facilitate integration with external
  entities.
- Support for UDP/STUN based connection requests for reaching devices behind NAT
  (TR-069 Annex G).
- Presets can now be scheduled using a cron-like expression.
- Presets can now be tied to specific device events (e.g. boot).
- Presets precondition queries no longer support "\$or" or other MongoDB logical
  operators.
- Faults are no longer a part of tasks but are now first class objects.
- Presets are now assigned to channels. A fault in one channel only blocks
  presets in that channel.
- New API CRUD functions for provisions, virtual parameters, and faults.
- New config options for XML output.
- API responses now include "GenieACS-Version" header.
- Graceful shutdown when receiving SIGINT and SIGTERM events.
- Support SSL intermediate certificate chains.
- Supported Node.js versions are 6.x and 7.x.
- Supported MongoDB versions are 2.6 through 3.4.
- Expect performance differences due to major under the hood changes. Some
  operations are faster and some are slower. Overall performance is improved.
- GenieACS will no longer fetch the entire device data model upon first contact
  but will instead only fetch the parameters it needs to fulfill the presets.
- Logs have been overhauled and split into two streams: process log (stderr) and
  access log (stdout). Also added config options to dump logs to files rather
  than standard streams.
- Connection request authentication credentials are picked up from the device
  data model if available. config/auth.js is still supported as a fallback and
  now supports an optional callback argument.
- Custom commands have been removed. Use virtual parameters and/or extensions.
- Aliases and value normalizers (config/parameters.json) have been removed. Use
  virtual parameters.
- The API /devices/<device_id>/preset has been removed.
- Rarely used RequestDownload method no longer supported.
- The TR-069 client simulator has moved to its own repo at
  https://github.com/zaidka/genieacs-sim


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to GenieACS

## Questions and Support

Please use the [forum](https://forum.genieacs.com) for questions, help requests,
and general discussion. GitHub Issues are reserved for confirmed bug reports.

## Issues

We use GitHub Issues to track bugs. When filing a bug report:

- Provide a clear description of the problem.
- Include steps to reproduce the issue.
- Note the GenieACS version, Node.js version, and MongoDB version.
- Include relevant log output if applicable.

If you face interoperability issues with a CPE, it is more often than not a
device-specific issue. Please consult the [forum](https://forum.genieacs.com)
before opening an Issue.

## Pull Requests

Pull requests are welcome. For bug fixes, go ahead and open a PR directly. For
new features or significant changes, please discuss in the
[forum](https://forum.genieacs.com) first to ensure alignment with the project's
direction.

When submitting a PR:

- Keep changes focused. One PR should address one concern.
- Run `npm run lint` and `npm test` before submitting.
- Update documentation in `docs/` if your change affects user-facing behavior.
- Add tests where appropriate (see [Testing](#testing)).
- Write a clear PR description explaining what the change does and why.

## Code Style

### Naming Conventions

- **Variables and functions**: `camelCase`
- **Classes**: `PascalCase`
- **Interfaces and type aliases**: `PascalCase`, without an `I` or `T` prefix
- **Module-level constants**: `UPPER_SNAKE_CASE`
- **Private class members**: prefixed with underscore (`_name`, `_cache`)

Choose descriptive, meaningful names. A longer clear name is better than a short
ambiguous one.

### Imports

Organize imports in three groups, in this order:

1. Node.js built-in modules, using the `node:` prefix
2. External packages
3. Local project modules

Use `.ts` extensions for all local imports.

```typescript
import { readFileSync } from "node:fs";
import * as http from "node:http";

import { Collection } from "mongodb";

import { connect, disconnect } from "./db.ts";
import Path from "./common/path.ts";
```

### Functions and Exports

Use the `function` keyword for all named and exported function declarations.
Arrow functions should only be used for callbacks and short inline expressions.

```typescript
// Named/exported functions use function keyword
export function processRequest(req: Request): Response {
  // ...
}

// Arrow functions for callbacks
items.filter((item) => item.active);
promise.then((result) => {
  // ...
});
```

### TypeScript

- All function declarations must have explicit return types. This is enforced by
  ESLint.
- Using `any` is permitted where full typing would be impractical, but prefer
  more specific types when reasonable.
- Prefer `Record<string, T>` over `{ [key: string]: T }` for mapped types.
- Use type assertions (`as`) sparingly and only when you have stronger type
  knowledge than the compiler.

### Comments

Code should be self-documenting. Use comments sparingly and only when the "why"
is not obvious from the code itself. When you do comment, use inline `//` style.

Do not use JSDoc (`/** */`) or block comments (`/* */`).

```typescript
// Good: explains a non-obvious reason
// Escapes everything except alphanumerics and underscore
function escapeRegExp(str: string): string {
  /* ... */
}

// Good: links to an external reference
// Source: http://stackoverflow.com/a/6969486

// Good: flags a known limitation
// TODO support "MD5-sess" algorithm directive

// Bad: restates what the code does
// Loop through each item and increment the counter
for (const item of items) {
  counter++;
}
```

### Error Handling

Use `== null` (not `=== null || === undefined`) for null/undefined checks.
ESLint is configured to allow this.

## Testing

### When to Write Tests

Tests are most valuable for pure logic: parsers, data transformations,
algorithms, and utility functions where inputs and outputs are well defined. A
regression test accompanying a bug fix is also worthwhile to prevent the same
issue from resurfacing.

Not every change needs a test. Use judgment and consider the likelihood and cost
of breakage. Avoid writing tests that duplicate coverage already provided by
existing tests, and resist the urge to test trivial code just for the sake of
coverage numbers.

### Conventions

Tests use the Node.js built-in test runner (`node:test`) and assertion module
(`node:assert`). No external test libraries or mocking frameworks are used.

```typescript
import test from "node:test";
import assert from "node:assert";

void test("parseValue returns correct type for integer strings", () => {
  const result = parseValue("42");
  assert.strictEqual(result, 42);
});

void test("parseValue throws on invalid input", () => {
  assert.throws(() => parseValue(""), new Error("empty value"));
});
```

Key conventions:

- Prefix `test()` calls with `void` to satisfy the `no-floating-promises` lint
  rule.
- Keep tests flat. Do not nest `describe` blocks.
- Use descriptive test names that state what is being tested and the expected
  outcome.
- Use `assert.strictEqual()` for value comparisons and
  `assert.deepStrictEqual()` for objects and arrays.

Test files live in the `test/` directory and are named after the module they
test (e.g. `test/path.ts` tests `lib/common/path.ts`).

## Dependencies

This project deliberately keeps its dependency footprint small. Before adding a
new dependency:

- Prefer Node.js built-in APIs when they can do the job.
- Consider whether the functionality is simple enough to implement directly.
- Justify the addition in your PR description.

Do not add development tool dependencies (linter plugins, editor integrations,
etc.) without prior discussion.

## File Organization

| Directory     | Contents                                     |
| ------------- | -------------------------------------------- |
| `lib/`        | Core server-side application code            |
| `lib/common/` | Code shared between server and browser       |
| `lib/db/`     | Database layer (MongoDB)                     |
| `lib/ui/`     | UI backend helpers                           |
| `ui/`         | Frontend code (Mithril.js SPA)               |
| `bin/`        | Service entry points                         |
| `build/`      | Build tooling                                |
| `test/`       | Test files                                   |
| `docs/`       | User documentation (Sphinx/reStructuredText) |
| `public/`     | Static assets (favicon, logo)                |

Place new code in the directory that matches its purpose. Server-side logic
belongs in `lib/`, code that must run in both Node.js and the browser belongs in
`lib/common/`, and frontend-only code belongs in `ui/`.

## Documentation

User documentation lives in the `docs/` directory as reStructuredText files
built with Sphinx and published to
[docs.genieacs.com](https://docs.genieacs.com).

When your change affects user-facing behavior:

- Update the relevant documentation in `docs/`.
- If adding a new feature, consider whether it warrants a new page or a section
  in an existing page.
- Keep documentation concise and practical. Match the existing tone: direct,
  factual, no filler.

Documentation changes should be included in the same PR as the code change, not
submitted separately.

### ARCHITECTURE.md

`ARCHITECTURE.md` describes the high-level architecture of the project: the
service boundaries, major subsystems, data flow, and key invariants. It is aimed
at contributors who need a mental map of the codebase.

This file has a different update cadence than `docs/`. It should be revisited a
few times a year rather than kept in lockstep with every code change. When you
do update it, follow these principles:

- **Only describe things that are unlikely to change frequently.** Module
  responsibilities, service boundaries, key data structures, and architectural
  invariants belong here. Implementation details, function signatures, and
  config option lists do not.
- **Name important files, modules, and types but do not link them.** Links go
  stale. Encourage the reader to use symbol search to find named entities; this
  also helps them discover related, similarly named things.
- **Keep it short.** Every recurring contributor will read it. A shorter
  document is less likely to become stale and more likely to be maintained.
- **Describe the "what" and "where", not the "how".** This is a map of the
  country, not an atlas of its states. Pull detailed explanations into inline
  code comments or separate documents.
- **Call out architectural invariants explicitly.** Important invariants are
  often expressed as the _absence_ of something (e.g., "the expression system
  does not depend on service-specific code") and are hard to discover by reading
  code alone.

## Git Workflow

### Commit Messages

This project follows the
[Conventional Commits](https://www.conventionalcommits.org/) format:

    <type>(<scope>): <subject>

    [optional body]

- Use the imperative mood, present tense: "Fix bug", not "Fixed bug" or "Fixes
  bug".
- Do not capitalize the first letter of the subject (the type prefix handles
  visual structure).
- Do not end the subject line with a period.
- Keep the subject line under 72 characters.
- When more context is helpful, add a body separated from the subject by a blank
  line, wrapped at 72 characters. The goal is to provide enough information for
  someone scanning the commit history to find a specific change (e.g. for
  troubleshooting or rebasing) or to draft changelog entries for a release.
  Don't be verbose, but don't be cryptic either.

#### Types

| Type       | When to use                                                                 |
| ---------- | --------------------------------------------------------------------------- |
| `fix`      | Bug fixes                                                                   |
| `feat`     | New features or capabilities                                                |
| `refactor` | Code restructuring with no behavior change                                  |
| `test`     | Adding or updating tests                                                    |
| `docs`     | Documentation changes (`docs/`, `CONTRIBUTING.md`, `README.md`)             |
| `build`    | Build system, dependencies, esbuild config, `package.json` scripts          |
| `chore`    | Maintenance tasks that don't fit above (`.gitignore`, tooling config, etc.) |

#### Scopes

Scope is optional. Use it when it adds useful context; omit it when the change
is cross-cutting or the subject already makes it obvious.

| Scope  | Covers                              |
| ------ | ----------------------------------- |
| `cwmp` | CWMP service (including extensions) |
| `nbi`  | Northbound REST API service         |
| `fs`   | File service                        |
| `ui`   | Web UI (frontend and backend)       |
| `db`   | Database layer                      |

If a change touches multiple scopes, either pick the primary one or omit the
scope entirely.

#### Examples

    feat(nbi): add bulk device delete endpoint
    fix(cwmp): handle missing ParameterKey in InformResponse
    refactor(db): replace raw queries with parameterized calls
    fix(ui): correct parameter table sort order
    test: add XML parser edge case coverage
    docs: update provisioning guide for new API
    build: upgrade esbuild to v0.20

    fix(cwmp): increase server timeout to 2 mins

    To allow enough time for running unindexed queries in large
    deployments.

### Branches

- `master` is the main development branch.
- Create a feature or fix branch for your work and open a PR against `master`.
- Use concise, descriptive branch names in lowercase with hyphens:
  `fix-race-condition`, `support-xmpp-requests`.

## Changelog

The changelog (`CHANGELOG.md`) is maintained for each release and is written for
users and system administrators, not developers.

- Write entries as clear, user-facing prose. Do not copy commit messages
  verbatim.
- Each entry should describe what changed and, when helpful, why it matters.
- Group entries under a version heading with the release date:
  `## 1.2.13 (2024-06-06)`.
- Start each entry with a verb: "Fix", "Add", "Improve", "Remove", etc.
- Include enough context that a user can understand the impact without reading
  the code.

You do not need to update the changelog in your PR. The maintainer will add
changelog entries during the release process.

## Contributor License Agreement

By submitting a pull request to this repository, you acknowledge that, while
maintaining copyright, you grant GenieACS Inc. a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable license to reproduce,
prepare derivative works of, publicly display, publicly perform, sublicense, and
distribute your contributions and such derivative works under the AGPLv3 license
or any other license terms, including, but not limited to, proprietary or
commercial license terms.

You confirm that you own or have rights to distribute and sublicense the source
code contained therein, and that your content does not infringe upon the
intellectual property rights of a third party.


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# GenieACS

**This is the development branch for GenieACS v1.3. It is unstable and not ready
for production use. For the latest stable release, see the
[v1.2 branch](https://github.com/genieacs/genieacs/tree/v1.2).**

GenieACS is a high performance Auto Configuration Server (ACS) for remote
management of TR-069 enabled devices. It utilizes a declarative and fault
tolerant configuration engine for automating complex provisioning scenarios at
scale. It's battle-tested to handle hundreds of thousands and potentially
millions of concurrent devices.

## Quick Start

Install [Node.js](http://nodejs.org/) and [MongoDB](http://www.mongodb.org/).
Refer to their corresponding documentation for installation instructions. The
supported versions are:

- Node.js: 12.3+
- MongoDB: 3.6+

Install GenieACS from NPM:

    sudo npm install -g genieacs

To build from source instead, clone this repo or download the source archive
then _cd_ into the source directory then run:

    npm install
    npm run build

Finally, run the following services (found under `./dist/bin/` if building from
source):

### genieacs-cwmp

This is the service that the CPEs will communicate with. It listens on port 7547
by default. Configure the ACS URL in your devices accordingly.

You may optionally use [genieacs-sim](https://github.com/genieacs/genieacs-sim)
as a dummy TR-069 simulator if you don't have a CPE at hand.

### genieacs-nbi

This is the northbound interface module. It exposes a REST API on port 7557 by
default. This one is only required if you have an external system integrating
with GenieACS using this API.

### genieacs-fs

This is the file server from which the CPEs will download firmware images and
such. It listens on port 7567 by default.

### genieacs-ui

This serves the web based user interface. It listens on port 3000 by default.
You must pass _--ui-jwt-secret_ argument to supply the secret key used for
signing browser cookies:

    genieacs-ui --ui-jwt-secret secret

The UI has plenty of configuration options. When you open GenieACS's UI in a
browser you'll be greeted with a database initialization wizard to help you
populate some initial configuration.

Visit [docs.genieacs.com](https://docs.genieacs.com) for more documentation and
a complete installation guide for production deployments.

## Support

The [forum](https://forum.genieacs.com) is a good place to get guidance and help
from the community. Head on over and join the conversation!

For commercial support options, please visit
[genieacs.com](https://genieacs.com/support/).

## License

Copyright 2013-2026 GenieACS Inc. GenieACS is released under the
[AGPLv3 license terms](https://raw.githubusercontent.com/genieacs/genieacs/master/LICENSE).


================================================
FILE: bin/genieacs-cwmp.ts
================================================
import * as config from "../lib/config.ts";
import * as logger from "../lib/logger.ts";
import * as cluster from "../lib/cluster.ts";
import * as server from "../lib/server.ts";
import * as cwmp from "../lib/cwmp.ts";
import * as db from "../lib/db/db.ts";
import * as extensions from "../lib/extensions.ts";
import { version as VERSION } from "../package.json";

logger.init("cwmp", VERSION);

const SERVICE_ADDRESS = config.get("CWMP_INTERFACE") as string;
const SERVICE_PORT = config.get("CWMP_PORT") as number;

function exitWorkerGracefully(): void {
  setTimeout(exitWorkerUngracefully, 5000).unref();
  Promise.all([
    db.disconnect(),
    extensions.killAll(),
    cluster.worker.disconnect(),
  ])
    .then(logger.close)
    .catch(exitWorkerUngracefully);
}

function exitWorkerUngracefully(): void {
  void extensions.killAll().finally(() => {
    process.exit(1);
  });
}

if (!cluster.worker) {
  const WORKER_COUNT = config.get("CWMP_WORKER_PROCESSES") as number;

  logger.info({
    message: `genieacs-cwmp starting`,
    pid: process.pid,
    version: VERSION,
  });

  cluster.start(WORKER_COUNT, SERVICE_PORT, SERVICE_ADDRESS);

  process.on("SIGINT", () => {
    logger.info({
      message: "Received signal SIGINT, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });

  process.on("SIGTERM", () => {
    logger.info({
      message: "Received signal SIGTERM, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });
} else {
  const key = config.get("CWMP_SSL_KEY") as string;
  const cert = config.get("CWMP_SSL_CERT") as string;

  const options = {
    port: SERVICE_PORT,
    host: SERVICE_ADDRESS,
    ssl: key && cert ? { key, cert } : null,
    onConnection: cwmp.onConnection,
    onClientError: cwmp.onClientError,
    timeout: 30000,
    keepAliveTimeout: 0,
    requestTimeout: cwmp.REQUEST_TIMEOUT,
  };

  // Need this for Node < 15
  process.on("unhandledRejection", (err) => {
    throw err;
  });

  process.on("uncaughtException", (err) => {
    if ((err as NodeJS.ErrnoException).code === "ERR_IPC_DISCONNECTED") return;
    logger.error({
      message: "Uncaught exception",
      exception: err,
      pid: process.pid,
    });
    server.stop(false).then(exitWorkerGracefully).catch(exitWorkerUngracefully);
  });

  const initPromise = db
    .connect()
    .then(() => {
      server.start(options, cwmp.listener);
    })
    .catch((err) => {
      setTimeout(() => {
        throw err;
      });
    });

  process.on("SIGINT", () => {
    void initPromise.finally(() => {
      server
        .stop(false)
        .then(exitWorkerGracefully)
        .catch(exitWorkerUngracefully);
    });
  });

  process.on("SIGTERM", () => {
    void initPromise.finally(() => {
      server
        .stop(false)
        .then(exitWorkerGracefully)
        .catch(exitWorkerUngracefully);
    });
  });
}


================================================
FILE: bin/genieacs-ext.ts
================================================
import { Fault } from "../lib/types.ts";

const jobs = new Set();
const fileName = process.argv[2];
let script;

function errorToFault(err: Error): Fault {
  if (!err) return null;

  if (!err.name) return { code: "ext", message: `${err}` };

  const fault: Fault = {
    code: `ext.${err.name}`,
    message: err.message,
    detail: {
      name: err.name,
      message: err.message,
    },
  };

  if (err.stack) {
    fault.detail["stack"] = err.stack;
    // Trim the stack trace
    const stackTrimIndex = fault.detail["stack"].match(
      /\s+at\s[^\s]+\s\(.*genieacs-ext:.+\)/,
    );
    if (stackTrimIndex) {
      fault.detail["stack"] = fault.detail["stack"].slice(
        0,
        stackTrimIndex.index,
      );
    }
  }

  return fault;
}

// Need this for Node < 15
process.on("unhandledRejection", (err) => {
  throw err;
});

process.on("uncaughtException", (err) => {
  const fault = errorToFault(err);
  jobs.forEach((jobId) => {
    process.send([jobId, fault, null]);
  });
  jobs.clear();
  process.disconnect();
});

process.on("message", (message) => {
  jobs.add(message[0]);

  if (!script) {
    const cwd = process.env["GENIEACS_EXT_DIR"];
    process.chdir(cwd);
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    script = require(`${cwd}/${fileName}`);
  }

  const funcName = message[1][0];

  if (!script[funcName]) {
    const fault = {
      code: "ext",
      message: `No such function '${funcName}' in extension '${fileName}'`,
    };
    process.send([message[0], fault, null]);
    return;
  }

  script[funcName](message[1].slice(1), (err, res) => {
    if (!jobs.delete(message[0])) return;

    process.send([message[0], errorToFault(err), res]);
  });
});

// Ignore SIGINT
process.on("SIGINT", () => {
  // Ignore
});


================================================
FILE: bin/genieacs-fs.ts
================================================
import * as config from "../lib/config.ts";
import * as logger from "../lib/logger.ts";
import * as cluster from "../lib/cluster.ts";
import * as server from "../lib/server.ts";
import { listener } from "../lib/fs.ts";
import * as db from "../lib/db/db.ts";
import { version as VERSION } from "../package.json";

logger.init("fs", VERSION);

const SERVICE_ADDRESS = config.get("FS_INTERFACE") as string;
const SERVICE_PORT = config.get("FS_PORT") as number;

function exitWorkerGracefully(): void {
  setTimeout(exitWorkerUngracefully, 5000).unref();
  Promise.all([db.disconnect(), cluster.worker.disconnect()])
    .then(logger.close)
    .catch(exitWorkerUngracefully);
}

function exitWorkerUngracefully(): void {
  process.exit(1);
}

if (!cluster.worker) {
  const WORKER_COUNT = config.get("FS_WORKER_PROCESSES") as number;

  logger.info({
    message: `genieacs-fs starting`,
    pid: process.pid,
    version: VERSION,
  });

  cluster.start(WORKER_COUNT, SERVICE_PORT, SERVICE_ADDRESS);

  process.on("SIGINT", () => {
    logger.info({
      message: "Received signal SIGINT, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });

  process.on("SIGTERM", () => {
    logger.info({
      message: "Received signal SIGTERM, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });
} else {
  const key = config.get("FS_SSL_KEY") as string;
  const cert = config.get("FS_SSL_CERT") as string;
  const options = {
    port: SERVICE_PORT,
    host: SERVICE_ADDRESS,
    ssl: key && cert ? { key, cert } : null,
    timeout: 30000,
  };

  // Need this for Node < 15
  process.on("unhandledRejection", (err) => {
    throw err;
  });

  process.on("uncaughtException", (err) => {
    if ((err as NodeJS.ErrnoException).code === "ERR_IPC_DISCONNECTED") return;
    logger.error({
      message: "Uncaught exception",
      exception: err,
      pid: process.pid,
    });
    server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
  });

  const initPromise = db
    .connect()
    .then(() => {
      server.start(options, listener);
    })
    .catch((err) => {
      setTimeout(() => {
        throw err;
      });
    });

  process.on("SIGINT", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });

  process.on("SIGTERM", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });
}


================================================
FILE: bin/genieacs-nbi.ts
================================================
import * as config from "../lib/config.ts";
import * as logger from "../lib/logger.ts";
import * as cluster from "../lib/cluster.ts";
import * as server from "../lib/server.ts";
import { listener } from "../lib/nbi.ts";
import * as db from "../lib/db/db.ts";
import * as extensions from "../lib/extensions.ts";
import { version as VERSION } from "../package.json";

logger.init("nbi", VERSION);

const SERVICE_ADDRESS = config.get("NBI_INTERFACE") as string;
const SERVICE_PORT = config.get("NBI_PORT") as number;

function exitWorkerGracefully(): void {
  setTimeout(exitWorkerUngracefully, 5000).unref();
  Promise.all([
    db.disconnect(),
    extensions.killAll(),
    cluster.worker.disconnect(),
  ])
    .then(logger.close)
    .catch(exitWorkerUngracefully);
}

function exitWorkerUngracefully(): void {
  void extensions.killAll().finally(() => {
    process.exit(1);
  });
}

if (!cluster.worker) {
  const WORKER_COUNT = config.get("NBI_WORKER_PROCESSES") as number;

  logger.info({
    message: `genieacs-nbi starting`,
    pid: process.pid,
    version: VERSION,
  });

  cluster.start(WORKER_COUNT, SERVICE_PORT, SERVICE_ADDRESS);

  process.on("SIGINT", () => {
    logger.info({
      message: "Received signal SIGINT, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });

  process.on("SIGTERM", () => {
    logger.info({
      message: "Received signal SIGTERM, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });
} else {
  const key = config.get("NBI_SSL_KEY") as string;
  const cert = config.get("NBI_SSL_CERT") as string;
  const options = {
    port: SERVICE_PORT,
    host: SERVICE_ADDRESS,
    ssl: key && cert ? { key, cert } : null,
    timeout: 120000,
  };

  // Need this for Node < 15
  process.on("unhandledRejection", (err) => {
    throw err;
  });

  process.on("uncaughtException", (err) => {
    if ((err as NodeJS.ErrnoException).code === "ERR_IPC_DISCONNECTED") return;
    logger.error({
      message: "Uncaught exception",
      exception: err,
      pid: process.pid,
    });
    server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
  });

  const initPromise = db
    .connect()
    .then(() => {
      server.start(options, listener);
    })
    .catch((err) => {
      setTimeout(() => {
        throw err;
      });
    });

  process.on("SIGINT", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });

  process.on("SIGTERM", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });
}


================================================
FILE: bin/genieacs-ui.ts
================================================
import * as config from "../lib/config.ts";
import * as logger from "../lib/logger.ts";
import * as cluster from "../lib/cluster.ts";
import * as server from "../lib/server.ts";
import { listener } from "../lib/ui.ts";
import * as extensions from "../lib/extensions.ts";
import * as db from "../lib/db/db.ts";
import { version as VERSION } from "../package.json";

logger.init("ui", VERSION);

const SERVICE_ADDRESS = config.get("UI_INTERFACE") as string;
const SERVICE_PORT = config.get("UI_PORT") as number;

function exitWorkerGracefully(): void {
  setTimeout(exitWorkerUngracefully, 5000).unref();
  Promise.all([
    db.disconnect(),
    extensions.killAll(),
    cluster.worker.disconnect(),
  ])
    .then(logger.close)
    .catch(exitWorkerUngracefully);
}

function exitWorkerUngracefully(): void {
  void extensions.killAll().finally(() => {
    process.exit(1);
  });
}

if (!cluster.worker) {
  const WORKER_COUNT = config.get("UI_WORKER_PROCESSES") as number;

  logger.info({
    message: `genieacs-ui starting`,
    pid: process.pid,
    version: VERSION,
  });

  cluster.start(WORKER_COUNT, SERVICE_PORT, SERVICE_ADDRESS);

  process.on("SIGINT", () => {
    logger.info({
      message: "Received signal SIGINT, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });

  process.on("SIGTERM", () => {
    logger.info({
      message: "Received signal SIGTERM, exiting",
      pid: process.pid,
    });

    cluster.stop();
  });
} else {
  const key = config.get("UI_SSL_KEY") as string;
  const cert = config.get("UI_SSL_CERT") as string;
  const options = {
    port: SERVICE_PORT,
    host: SERVICE_ADDRESS,
    ssl: key && cert ? { key, cert } : null,
    timeout: 120000,
  };

  // Need this for Node < 15
  process.on("unhandledRejection", (err) => {
    throw err;
  });

  process.on("uncaughtException", (err) => {
    if ((err as NodeJS.ErrnoException).code === "ERR_IPC_DISCONNECTED") return;
    logger.error({
      message: "Uncaught exception",
      exception: err,
      pid: process.pid,
    });
    server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
  });

  const initPromise = db
    .connect()
    .then(() => {
      server.start(options, async (req, res) => listener(req, res));
    })
    .catch((err) => {
      setTimeout(() => {
        throw err;
      });
    });

  process.on("SIGINT", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });

  process.on("SIGTERM", () => {
    void initPromise.finally(() => {
      server.stop().then(exitWorkerGracefully).catch(exitWorkerUngracefully);
    });
  });
}


================================================
FILE: build/assets.ts
================================================
export const APP_JS = "app.js";
export const APP_CSS = "app.css";
export const ICONS_SVG = "icons.svg";
export const LOGO_SVG = "logo.svg";
export const FAVICON_PNG = "favicon.png";


================================================
FILE: build/build.ts
================================================
import path from "node:path";
import fs from "node:fs";
import { createHash } from "node:crypto";
import { promisify } from "node:util";
import { exec } from "node:child_process";
import * as esbuild from "esbuild";
import { optimize } from "svgo";
import * as xmlParser from "../lib/xml-parser.ts";

const fsAsync = {
  readdir: promisify(fs.readdir),
  readFile: promisify(fs.readFile),
  writeFile: promisify(fs.writeFile),
  copyFile: promisify(fs.copyFile),
  rename: promisify(fs.rename),
  chmod: promisify(fs.chmod),
  lstat: promisify(fs.lstat),
  exists: promisify(fs.exists),
  rmdir: promisify(fs.rmdir),
  unlink: promisify(fs.unlink),
  mkdir: promisify(fs.mkdir),
};

const execAsync = promisify(exec);

const MODE = process.env["NODE_ENV"] || "production";

const INPUT_DIR = process.cwd();
const OUTPUT_DIR = path.join(INPUT_DIR, "dist");

async function rmDir(dirPath: string): Promise<void> {
  if (!(await fsAsync.exists(dirPath))) return;
  const files = await fsAsync.readdir(dirPath);

  for (const file of files) {
    const filePath = path.join(dirPath, file);
    if ((await fsAsync.lstat(filePath)).isDirectory()) await rmDir(filePath);
    else await fsAsync.unlink(filePath);
  }
  await fsAsync.rmdir(dirPath);
}

// For lockfileVersion = 1
function stripDevDeps(deps): void {
  if (!deps["dependencies"]) return;
  for (const [k, v] of Object.entries(deps["dependencies"])) {
    if (v["dev"]) delete deps["dependencies"][k];
    else stripDevDeps(v);
  }
  if (!Object.keys(deps["dependencies"]).length) delete deps["dependencies"];
}

// For lockfileVersion = 2
function stripDevDeps2(deps): void {
  if (!deps["packages"]) return;
  for (const [k, v] of Object.entries(deps["packages"])) {
    delete v["devDependencies"];
    if (v["dev"]) delete deps["packages"][k];
  }
}

function xmlTostring(xml): string {
  const children = [];
  for (const c of xml.children || []) children.push(xmlTostring(c));

  return xml.name === "root" && xml.bodyIndex === 0
    ? children.join("")
    : `<${xml.name} ${xml.attrs}>${children.join("")}</${xml.name}>`;
}

function assetHash(buffer: Buffer | string): string {
  return createHash("md5").update(buffer).digest("hex").slice(0, 8);
}

const ASSETS = {} as {
  APP_JS?: string;
  APP_CSS?: string;
  ICONS_SVG?: string;
  LOGO_SVG?: string;
  FAVICON_PNG?: string;
};

const assetsPlugin = {
  name: "assets",
  setup(build) {
    build.onLoad({ filter: /\/build\/assets.ts$/ }, () => {
      const lines = Object.entries(ASSETS).map(
        ([k, v]) => `export const ${k} = ${JSON.stringify(v)};`,
      );
      return { contents: lines.join("\n") };
    });
  },
} as esbuild.Plugin;

const seedPlugin = {
  name: "seed",
  setup(build) {
    build.onLoad({ filter: /\/seed\// }, (args) => {
      if (args.with?.["type"] !== "text") return undefined;
      let contents = fs.readFileSync(args.path, "utf8");
      // Strip TypeScript directives that are only needed for type-checking
      contents = contents.replace(/^\s*\/\/\s*@ts-.*\n/gm, "\n");
      return { contents, loader: "text" };
    });
  },
} as esbuild.Plugin;

const packageDotJsonPlugin = {
  name: "packageDotJson",
  setup(build) {
    const sourcePath = path.join(INPUT_DIR, "package.json");
    build.onResolve({ filter: /\/package.json$/ }, (args) => {
      const p = path.join(args.resolveDir, args.path);
      if (p !== sourcePath) return undefined;
      return { path: path.join(OUTPUT_DIR, "package.json") };
    });
  },
} as esbuild.Plugin;

const inlineDepsPlugin = {
  name: "inlineDeps",
  setup(build) {
    const deps = ["espresso-iisojs", "@codemirror", "mithril", "yaml"];
    const depFiles = new Set();
    build.onResolve({ filter: /^[^.]/ }, async (args) => {
      if (args.pluginData === "inlineDeps") return undefined;
      if (
        depFiles.has(args.importer) ||
        deps.some((d) => args.path.startsWith(d))
      ) {
        const res = await build.resolve(args.path, {
          importer: args.importer,
          namespace: args.namespace,
          resolveDir: args.resolveDir,
          kind: args.kind,
          with: args.with,
          pluginData: "inlineDeps",
        });
        depFiles.add(res.path);
        return res;
      }
      return { sideEffects: false, external: true };
    });
  },
} as esbuild.Plugin;

function generateSymbol(id: string, svgStr: string): string {
  const xml = xmlParser.parseXml(svgStr);
  const svg = xml.children[0];
  const svgAttrs = xmlParser.parseAttrs(svg.attrs);
  let viewBox = "";
  for (const a of svgAttrs) {
    if (a.name === "viewBox") {
      viewBox = `viewBox="${a.value}"`;
      break;
    }
  }
  const symbolBody = xml.children[0].children
    .map((c) => xmlTostring(c))
    .join("");
  return `<symbol id="icon-${id}" ${viewBox}>${symbolBody}</symbol>`;
}

async function getBuildMetadata(): Promise<string> {
  const date = new Date().toISOString().slice(2, 10).replaceAll("-", "");

  const [commit, diff, newFiles] = await Promise.all([
    execAsync("git rev-parse HEAD"),
    execAsync("git diff HEAD"),
    execAsync("git ls-files --others --exclude-standard"),
  ]).then((res) => res.map((r) => r.stdout.trim()));

  if (!diff && !newFiles) return date + commit.slice(0, 4);

  const hash = createHash("md5");
  hash.update(commit).update(diff).update(newFiles);
  for (const file of newFiles.split("\n").filter((f) => f))
    hash.update(await fsAsync.readFile(file));
  return date + hash.digest("hex").slice(0, 4);
}

async function init(): Promise<void> {
  const [buildMetadata, packageJsonFile, npmShrinkwrapFile] = await Promise.all(
    [
      getBuildMetadata(),
      fsAsync.readFile(path.join(INPUT_DIR, "package.json")),
      fsAsync.readFile(path.join(INPUT_DIR, "npm-shrinkwrap.json")),
    ],
  );

  const packageJson = JSON.parse(packageJsonFile.toString());
  delete packageJson["devDependencies"];
  delete packageJson["private"];
  delete packageJson["scripts"];
  packageJson["version"] = `${packageJson["version"]}+${buildMetadata}`;

  const npmShrinkwrap = JSON.parse(npmShrinkwrapFile.toString());
  npmShrinkwrap["version"] = packageJson["version"];
  stripDevDeps(npmShrinkwrap);
  stripDevDeps2(npmShrinkwrap);

  await rmDir(OUTPUT_DIR);

  await fsAsync.mkdir(OUTPUT_DIR);

  await Promise.all([
    fsAsync.mkdir(path.join(OUTPUT_DIR, "bin")),
    fsAsync.mkdir(path.join(OUTPUT_DIR, "public")),
    fsAsync.writeFile(
      path.join(OUTPUT_DIR, "package.json"),
      JSON.stringify(packageJson, null, 2),
    ),
    fsAsync.writeFile(
      path.join(OUTPUT_DIR, "npm-shrinkwrap.json"),
      JSON.stringify(npmShrinkwrap, null, 2),
    ),
  ]);
}

async function copyStatic(): Promise<void> {
  const files = [
    "LICENSE",
    "README.md",
    "CHANGELOG.md",
    "public/logo.svg",
    "public/favicon.png",
  ];

  const [logo, favicon] = await Promise.all([
    fsAsync.readFile(path.join(INPUT_DIR, "public/logo.svg")),
    fsAsync.readFile(path.join(INPUT_DIR, "public/favicon.png")),
  ]);

  ASSETS.LOGO_SVG = `logo-${assetHash(logo)}.svg`;
  ASSETS.FAVICON_PNG = `favicon-${assetHash(favicon)}.png`;

  const filenames = {} as Record<string, string>;
  filenames["public/logo.svg"] = path.join("public", ASSETS.LOGO_SVG);
  filenames["public/favicon.png"] = path.join("public", ASSETS.FAVICON_PNG);

  await Promise.all(
    files.map((f) =>
      fsAsync.copyFile(
        path.join(INPUT_DIR, f),
        path.join(OUTPUT_DIR, filenames[f] || f),
      ),
    ),
  );
}

async function generateCss(): Promise<void> {
  const tailwindPlugin = {
    name: "tailwind",
    setup(build) {
      build.onLoad({ filter: /\/ui\/css\/app.css$/ }, async (args) => {
        const res = await execAsync(`npx @tailwindcss/cli -i ${args.path}`);
        return { loader: "css", contents: res.stdout };
      });
    },
  } as esbuild.Plugin;

  const res = await esbuild.build({
    bundle: true,
    absWorkingDir: INPUT_DIR,
    minify: MODE === "production",
    sourcemap: "linked",
    sourcesContent: false,
    entryPoints: ["ui/css/app.css"],
    entryNames: "[dir]/[name]-[hash]",
    outfile: path.join(OUTPUT_DIR, "public/app.css"),
    plugins: [tailwindPlugin],
    loader: {
      ".woff2": "dataurl",
    },
    target: ["chrome111", "safari16.4", "firefox128"],
    metafile: true,
  });

  for (const [k, v] of Object.entries(res.metafile.outputs)) {
    if (v.entryPoint === "ui/css/app.css") {
      ASSETS.APP_CSS = path.relative(
        path.join(OUTPUT_DIR, "public"),
        path.join(INPUT_DIR, k),
      );
      break;
    }
  }
}

async function generateBackendJs(): Promise<void> {
  const services = [
    "genieacs-cwmp",
    "genieacs-ext",
    "genieacs-nbi",
    "genieacs-fs",
    "genieacs-ui",
  ];

  await esbuild.build({
    bundle: true,
    absWorkingDir: INPUT_DIR,
    minify: MODE === "production",
    define: {
      "process.env.NODE_ENV": JSON.stringify(MODE),
    },
    sourcemap: "inline",
    sourcesContent: false,
    platform: "node",
    target: "node12.13.0",
    packages: "external",
    banner: { js: "#!/usr/bin/env node" },
    entryPoints: services.map((s) => `bin/${s}.ts`),
    outdir: path.join(OUTPUT_DIR, "bin"),
    plugins: [packageDotJsonPlugin, assetsPlugin, seedPlugin],
  });

  for (const bin of services) {
    const p = path.join(OUTPUT_DIR, "bin", bin);
    await fsAsync.rename(`${p}.js`, p);
    // Mark as executable
    const mode = (await fsAsync.lstat(p)).mode;
    await fsAsync.chmod(p, mode | 73);
  }
}

async function generateFrontendJs(): Promise<void> {
  const res = await esbuild.build({
    bundle: true,
    absWorkingDir: INPUT_DIR,
    splitting: true,
    minify: MODE === "production",
    sourcemap: "linked",
    sourcesContent: false,
    platform: "browser",
    format: "esm",
    target: ["chrome111", "safari16.4", "firefox128"],
    entryPoints: ["ui/app.ts"],
    entryNames: "[dir]/[name]-[hash]",
    outdir: path.join(OUTPUT_DIR, "public"),
    plugins: [packageDotJsonPlugin, inlineDepsPlugin, assetsPlugin],
    metafile: true,
  });

  for (const [k, v] of Object.entries(res.metafile.outputs)) {
    for (const imp of v.imports)
      if (imp.external && imp.path !== "views-bundle")
        throw new Error(`External import found: ${imp.path}`);

    if (v.entryPoint === "ui/app.ts") {
      ASSETS.APP_JS = path.relative(
        path.join(OUTPUT_DIR, "public"),
        path.join(INPUT_DIR, k),
      );
    }
  }
}

async function generateIconsSprite(): Promise<void> {
  const symbols = [] as string[];
  const iconsDir = path.join(INPUT_DIR, "ui/icons");
  for (const file of await fsAsync.readdir(iconsDir)) {
    const id = path.parse(file).name;
    const filePath = path.join(iconsDir, file);
    const src = (await fsAsync.readFile(filePath)).toString();
    const { data } = await optimize(src, {
      plugins: [
        {
          name: "preset-default",
          params: {
            overrides: {
              removeViewBox: false,
            },
          },
        },
      ],
    });
    symbols.push(generateSymbol(id, data));
  }
  const data = `<svg xmlns="http://www.w3.org/2000/svg">${symbols.join(
    "",
  )}</svg>`;
  ASSETS.ICONS_SVG = `icons-${assetHash(data)}.svg`;
  await fsAsync.writeFile(
    path.join(OUTPUT_DIR, "public", ASSETS.ICONS_SVG),
    data,
  );
}

init()
  .then(() =>
    Promise.all([
      Promise.all([generateIconsSprite(), copyStatic()]).then(
        generateFrontendJs,
      ),
      generateCss(),
    ]).then(generateBackendJs),
  )
  .catch((err) => {
    process.stderr.write(err.stack + "\n");
  });


================================================
FILE: build/generate-fonts.sh
================================================
#!/bin/bash

cd "$(dirname "$0")"

declare -A FONTS=(
  [InterVariable]=https://rsms.me/inter/font-files/InterVariable.woff2
  [InterVariable-Italic]=https://rsms.me/inter/font-files/InterVariable-Italic.woff2
  [RobotoMono]=https://raw.githubusercontent.com/googlefonts/RobotoMono/main/fonts/variable/RobotoMono%5Bwght%5D.ttf
)

for name in "${!FONTS[@]}"
do
  url="${FONTS[$name]}"
  echo "Downloading $url"
  TMP=$(mktemp)
  curl "$url" -s --output "$TMP"
  pyftsubset "$TMP" --output-file="../ui/css/$name.woff2" --flavor=woff2 --unicodes="U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD" --layout-features+="tnum"
done


================================================
FILE: build/lint.ts
================================================
import { exec } from "node:child_process";
import { promisify } from "node:util";

const execPromise = promisify(exec);

async function runEslint(): Promise<string> {
  const CMD =
    "eslint 'bin/*.ts' 'lib/**/*.ts' 'ui/**/*.ts' 'test/**/*.ts' 'build/**/*.ts' 'seed/*'";
  const env = {
    ...(process.stdout.isTTY && { FORCE_COLOR: "1" }),
    ...process.env,
  };
  try {
    const { stdout, stderr } = await execPromise(CMD, { env });
    if (stderr) throw new Error(stderr);
    return stdout;
  } catch (err) {
    if (err.killed || err.signal || err.stderr || err.code !== 1) throw err;
    return err.stdout;
  }
}

async function runTsc(): Promise<string> {
  const CMD = "tsc --noEmit && tsc -p seed/tsconfig.json";
  const env = {
    ...(process.stdout.isTTY && { FORCE_COLOR: "1" }),
    ...process.env,
  };
  const { stdout, stderr } = await execPromise(CMD, { env });
  if (stderr) throw new Error(stderr);
  return stdout;
}

async function runPrettier(): Promise<string> {
  const CMD = "prettier --prose-wrap always --write .";
  const env = {
    ...(process.stdout.isTTY && { FORCE_COLOR: "1" }),
    ...process.env,
  };
  const { stdout, stderr } = await execPromise(CMD, { env });
  if (stderr) throw new Error(stderr);
  return stdout;
}

async function runAll(): Promise<void> {
  const prom1 = runPrettier();
  const prom2 = runEslint();
  const prom3 = runTsc();

  console.log(await prom1);
  console.log(await prom2);
  console.log(await prom3);
}

runAll().catch(console.error);


================================================
FILE: build/spellcheck-dict.pws
================================================
personal_ws-1.1 en 0
genieacs
GenieACS
javascript
sudo
config
cwmp
CPE
systemctl
nbi
CWMP
NBI
ACS
SSL
xsd
args
DeviceID
GENIEACS
env
param
arg
AUTH
igd
TCP
toctree
auth
EnvironmentFile
JSON
json
parameterValues
setParameterValues
stderr
stdout
attr
cfg
CPEs
ExecStart
faq
FileType
GenieACS's
JWT
maxdepth
npm
objectName
refreshObject
SerialNumber
systemd
usr
WantedBy
yaml
chown
Config
getParameterValues
https
InternetGatewayDevice
mkdir
OUI
sql
TODO
UDP
addObject
AGPLv
const
cpe
cron
deleteObject
FactoryReset
factoryReset
FileName
fileType
Github
hostname
HTTPS
jwt
latlong
NPM
oui
parameterNames
ProductClass
productClass
repo
SSID
sublicense
TLS
WANIPConnection
WPA
YourProvisionName
abc
Abdulla
accessors
AddObject
AddressingType
api
APIs
chmod
cwmp's
dateext
DATETIME
dateTime
datetime
declaratively
delaycompress
DeleteObject
deviceId
DHCP
dir
distro
equisatisfiable
ExternalIPAddress
failover
favor
func
GetParameterAttributes
getPassword
gte
gui
hexBinary
Hils
HOSTNAME
init
journalctl
journald
LastFileName
LastFileType
lastInform
LIBXMLJS
libxmljs
literalinclude
lockfile
logrotate
lte
mipsbe
normalizers
pre
quickstart
README
redis
reimplemented
RequestDownload
RESTful
rollout
sandboxed
scalable
SetParameterAttributes
SetParamteerValues
SIGINT
SIGTERM
skipWritableCheck
stringify
subdirectory
TargetFileName
useradd
VirtualParameters
vparam
xml
YAML
Zaid
cacheExpire
iss
http
statusCode
rawData
pos
Brotli
CSV
hostInfo
IPv
downloadSuccessOnTimeout
TransferComplete
nginx
ENCODEURICOMPONENT
pageSize
skipRootGpn
GPN
NaN
CIDR
XMPP
PEM
JID
unindexed


================================================
FILE: build/spellcheck.sh
================================================
#! /bin/sh

cd "$(dirname "$0")"

FILES=`ls ../docs/*.rst ../docs/*.js ../*.md`

for FILE in $FILES
do
    echo $FILE
    cat $FILE | aspell list --lang=en --add-extra-dicts=./spellcheck-dict.pws --ignore 2
    echo
done


================================================
FILE: build/test.ts
================================================
import path from "node:path";
import { readdir, readFile } from "node:fs/promises";

import * as esbuild from "esbuild";

const INPUT_DIR = process.cwd();

// Redirect ui/store.ts imports to test/mocks/store.ts
const mockStorePlugin: esbuild.Plugin = {
  name: "mock-store",
  setup(build) {
    const storePath = path.join(INPUT_DIR, "ui/store.ts");
    const mockStorePath = path.join(INPUT_DIR, "test/mocks/store.ts");

    build.onResolve({ filter: /\.\/store\.ts$/ }, (args) => {
      const resolved = path.join(args.resolveDir, args.path);
      if (resolved === storePath) {
        return { path: mockStorePath };
      }
      return undefined;
    });
  },
};

// Export private functions from reactive-store.ts for testing
const exportPrivateFunctionsPlugin: esbuild.Plugin = {
  name: "export-private-functions",
  setup(build) {
    const reactiveStorePath = path.join(INPUT_DIR, "ui/reactive-store.ts");

    build.onLoad({ filter: /reactive-store\.ts$/ }, async (args) => {
      if (args.path !== reactiveStorePath) return undefined;

      let contents = await readFile(args.path, "utf8");

      const exports = `
// Test-only exports (added by build/test.ts)
export { compareFunction as _testCompareFunction };
export { getObjectId as _testGetObjectId };
export { applyDefaultSort as _testApplyDefaultSort };
export { stores as _testStores };
export { getStore as _testGetStore };
export { ResourceStore as _testResourceStore };
`;
      contents += exports;

      return { contents, loader: "ts" };
    });
  },
};

async function buildTests(): Promise<void> {
  // Find all test files
  const testFiles = (await readdir(path.join(INPUT_DIR, "test")))
    .filter((f) => f.endsWith(".ts"))
    .map((f) => path.join("test", f));

  await esbuild.build({
    entryPoints: testFiles,
    bundle: true,
    platform: "node",
    target: "node18",
    packages: "external",
    sourcemap: "inline",
    outdir: "test",
    logLevel: "warning",
    plugins: [mockStorePlugin, exportPrivateFunctionsPlugin],
  });
}

buildTests().catch((err) => {
  process.stderr.write(err.stack + "\n");
  process.exit(1);
});


================================================
FILE: docs/.readthedocs.yaml
================================================
# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

version: 2

build:
  os: ubuntu-22.04
  tools:
    python: "3.12"

sphinx:
  configuration: docs/conf.py

formats: all

python:
  install:
    - requirements: docs/requirements.txt


================================================
FILE: docs/administration-faq.rst
================================================
.. _administration-faq:

Administration FAQ
==================

.. _administration-faq-duplicate-log-entries:

Duplicate log entries when using :func:`log()` function
-------------------------------------------------------

Because GenieACS uses a full fledged scripting language for device
configuration, the only way to guarantee that it has satisfied the 'desired
state' is by repeatedly executing the script until there's no more
discrepancies with the current device state. Though it may seem like this will
cause duplicate requests going to the device, this isn't actually the case
because device configuration are stated declaratively and that the scripts
themselves are pure functions in the context of a session (e.g. Date.now()
always returns the same value within the session).

To illustrate with an example, consider the following script:

.. code:: javascript

  log("Executing script");
  declare("Device.param", null, {value: 1});
  commit();
  declare("Device.param", null, {value: 2});

This will set the value of the 'Device.param' to 1, then to 2. Then as the
script is run again the value is set back to 1 and so on. A stable state will
never be reached so GenieACS will execute the script a few times until it gives
up and throws a fault. This is an edge case that should be avoided. A more
typical case is where the script is run once or twice. Essentially if an
execution doesn't result in any request to the CPE or a change in the data
model then a stable state is deemed to have been reached.

Configurations not pushed to device after factory reset
---------------------------------------------------------

After a device is reset to its factory default state, the cached data model in
GenieACS's database needs to be invalidated to force rediscovery. Ensure the
following lines are called on ``0 BOOTSTRAP`` event:

.. code:: javascript

  const now = Date.now();

  // Clear cached data model to force a refresh
  clear("Device", now);
  clear("InternetGatewayDevice", now);


Most device parameters are missing
----------------------------------

For performance reasons (server, client, and network), GenieACS by default only
fetches parts of the data model that are necessary to satisfy the declarations
in your provision scripts. Create declarations for any parameters you need
fetched by default.

If you're unsure and want to explore the available parameters exposed by the
device, refresh the root parameter (e.g. ``InternetGatewayDevice``) from
GenieACS's UI. You typically only need to do that one time for a given CPE
model.


================================================
FILE: docs/api-reference.rst
================================================
API Reference
=============

GenieACS exposes a rich RESTful API through its NBI component. This document
serves as a reference for the available APIs.

This API makes use of MongoDB's query language in some of its endpoints. Refer
to MongoDB's documentation for details.

.. note::

  The examples below use ``curl`` command for simplicity and ease of testing.
  Query parameters are URL-encoded, but the original pre-encoding values are
  shown for reference. These examples assume genieacs-nbi is running locally
  and listening on the default NBI port (7557).

.. warning::

  A common pitfall is not properly percent-encoding special characters in the
  device ID or query in the URL.

Endpoints
---------

GET /\<collection\>/?query=\<query\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Search for records in the database (e.g. devices, tasks, presets, files).
Returns a JSON representation of all items in the given collection that match
the search criteria.

*collection*: The data collection to search. Could be one of: tasks, devices,
presets, objects.

*query*: Search query. Refer to MongoDB queries for reference.

Examples
^^^^^^^^

- Find a device by its ID:

.. code:: javascript

  query = {"_id": "202BC1-BM632w-000000"}

.. code:: bash

  curl -i 'http://localhost:7557/devices/?query=%7B%22_id%22%3A%22202BC1-BM632w-000000%22%7D'

- Find a device by its MAC address:

.. code:: javascript

  query = {
    "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnection.1.MACAddress": "20:2B:C1:E0:06:65"
  }

.. code:: bash

  curl -i 'http://localhost:7557/devices/?query=%7B%22InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnection.1.MACAddress%22%3A%2220:2B:C1:E0:06:65%22%7D'

- Search for devices that have not initiated an inform in the last 7 days.

.. code:: javascript

  query = {
    "_lastInform": {
      "$lt" : "2017-12-11 13:16:23 +0000"
    }
  }

.. code:: bash

  curl -i 'http://localhost:7557/devices/?query=%7B%22_lastInform%22%3A%7B%22%24lt%22%3A%222017-12-11%2013%3A16%3A23%20%2B0000%22%7D%7D'

- Show pending tasks for a given device:

.. code:: javascript

  query = {"device": "202BC1-BM632w-000000"}

.. code:: bash

  curl -i 'http://localhost:7557/tasks/?query=%7B%22device%22%3A%22202BC1-BM632w-000000%22%7D'

- Return specific parameters for a given device:

.. code:: javascript

  query = {"_id": "202BC1-BM632w-000000"}

.. code:: bash

  curl -i 'http://localhost:7557/devices?query=%7B%22_id%22%3A%22202BC1-BM632w-000000%22%7D&projection=InternetGatewayDevice.DeviceInfo.ModelName,InternetGatewayDevice.DeviceInfo.Manufacturer'

The ``projection`` URL param is a comma-separated list of the parameters to receive.

POST /devices/\<device_id\>/tasks?[connection_request]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enqueue task(s) and optionally trigger a connection request to the device.
Refer to :ref:`tasks` section for information about the task object format.
Returns status code 200 if the tasks have been successfully executed, and 202
if the tasks have been queued to be executed at the next inform.

*device_id*: The ID of the device.

*connection_request*: Indicates that a connection request will be triggered to
execute the tasks immediately. Otherwise, the tasks will be queued and be
processed at the next inform.

The response body is the task object as it is inserted in the database. The
object will include ``_id`` property which you can use to look up the task
later.

Examples
^^^^^^^^

- Refresh all device parameters now:

.. code:: bash

  curl -i 'http://localhost:7557/devices/202BC1-BM632w-000000/tasks?connection_request' \
  -X POST \
  --data '{"name": "refreshObject", "objectName": ""}'

- Change WiFi SSID and password:

.. code:: javascript

  {
    "name": "setParameterValues",
    "parameterValues": [
      ["InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.SSID", "GenieACS", "xsd:string"],
      ["InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.PreSharedKey.1.PreSharedKey", "hello world", "xsd:string"]
    ]
  }

.. code:: bash

  curl -i 'http://localhost:7557/devices/202BC1-BM632w-000000/tasks?connection_request' \
  -X POST \
  --data '{"name":"setParameterValues", "parameterValues": [["InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.SSID", "GenieACS", "xsd:string"],["InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.PreSharedKey.1.PreSharedKey", "hello world", "xsd:string"]]}'

POST /tasks/\<task_id\>/retry
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Retry a faulty task at the next inform.

*task_id*: The ID of the task as returned by 'GET /tasks' request.

Example
^^^^^^^

.. code:: bash

  curl -i 'http://localhost:7557/tasks/5403908ef28ea3a25c138adc/retry' -X POST

DELETE /tasks/\<task_id\>
~~~~~~~~~~~~~~~~~~~~~~~~~

Delete the given task.

*task_id*: The ID of the task as returned by 'GET /tasks' request.

Example
^^^^^^^

.. code:: bash

  curl -i 'http://localhost:7557/tasks/5403908ef28ea3a25c138adc' -X DELETE

DELETE /faults/\<fault_id\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Delete the given fault.

*fault_id*: The ID of the fault as returned by 'GET /faults' request. The ID
format is "\<device_id\>:\<channel\>".

Example
^^^^^^^

.. code:: bash

  curl -i 'http://localhost:7557/faults/202BC1-BM632w-000000:default' -X DELETE

DELETE /devices/\<device_id\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Delete the given device from the database.

Example
^^^^^^^

.. code:: bash

  curl -X DELETE -i 'http://localhost:7557/devices/202BC1-BM632w-000001'

.. note::

  Note that the device will be registered again when/if it contacts the ACS
  again (e.g. on the next periodic inform).

POST /devices/\<device_id\>/tags/\<tag\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Assign a tag to a device. Has no effect if such tag already exists.

*device_id*: The ID of the device.

*tag*: The tag to be assigned.

Example
^^^^^^^

Assign the tag "testing" to a device:

.. code:: bash

  curl -i 'http://localhost:7557/devices/202BC1-BM632w-000000/tags/testing' -X POST

DELETE /devices/\<device_id\>/tags/\<tag\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Remove a tag from a device.

*device_id*: The ID of the device.

*tag*: The tag to be removed.

Example
^^^^^^^

Remove the tag "testing" from a device:

.. code:: bash

  curl -i 'http://localhost:7557/devices/202BC1-BM632w-000000/tags/testing' -X DELETE

PUT /presets/\<preset_name\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Create or update a preset. Returns status code 200 if the preset has been
added/updated successfully. The body of the request is a JSON representation of
the preset. Refer to :ref:`presets` section below for details about its format.

*preset_name*: The name of the preset.

Example
^^^^^^^

Create a preset to set 5 minutes inform interval for all devices tagged with
"test":

.. code:: javascript

  query = {
    "weight": 0,
    "precondition": "{\"_tags\": \"test\"}"
    "configurations": [
      {
        "type": "value",
        "name": "InternetGatewayDevice.ManagementServer.PeriodicInformEnable",
        "value": "true"
      },
      {
        "type": "value",
        "name": "InternetGatewayDevice.ManagementServer.PeriodicInformInterval",
        "value": "300"
      }
    ]
  }

.. code:: bash

  curl -i 'http://localhost:7557/presets/inform' \
  -X PUT \
  --data '{"weight": 0, "precondition": "{\"_tags\": \"test\"}", "configurations": [{"type": "value", "name": "InternetGatewayDevice.ManagementServer.PeriodicInformEnable", "value": "true"}, {"type": "value", "name": "InternetGatewayDevice.ManagementServer.PeriodicInformInterval", "value": "300"}]}'

DELETE /presets/\<preset_name\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: bash

	curl -i 'http://localhost:7557/presets/inform' -X DELETE

PUT /files/\<file_name\>
~~~~~~~~~~~~~~~~~~~~~~~~

Upload a new file or overwrite an existing one. Returns status code 200 if the
file has been added/updated successfully. The file content should be sent as
the request body.

*file_name*: The name of the uploaded file.

The following file metadata may be sent as request headers:

- ``fileType``: For firmware images it should be "1 Firmware Upgrade Image".
  Other common types are "2 Web Content" and "3 Vendor Configuration File".

- ``oui``: The OUI of the device model that this file belongs to.

- ``productClass``: The product class of the device.

- ``version``: In case of firmware images, this refer to the firmware version.

Example
^^^^^^^

Upload a firmware image file:

.. code:: bash

  curl -i 'http://localhost:7557/files/new_firmware_v1.0.bin' \
  -X PUT \
  --data-binary @"./new_firmware_v1.0.bin" \
  --header "fileType: 1 Firmware Upgrade Image" \
  --header "oui: 123456" \
  --header "productClass: ABC" \
  --header "version: 1.0"

DELETE /files/\<file_name\>
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Delete a previously uploaded file:

.. code:: bash

	curl -i 'http://localhost:7557/files/new_firmware_v1.0.bin' -X DELETE

GET /files/
~~~~~~~~~~~

Gets all previously uploaded files.

GET /files/?query={"filename":"\<filename\>"}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Find files using a query.

.. _tasks:

Tasks
-----

Find the different available tasks and their object structure.

``getParameterValues``
~~~~~~~~~~~~~~~~~~~~~~

.. code:: javascript

  query = {
    "name": "getParameterValues",
    "parameterNames": [
      "InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnectionNumberOfEntries",
      "InternetGatewayDevice.Time.NTPServer1", "InternetGatewayDevice.Time.Status"
    ]
  }

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-96318REF-SR360NA0A4%252D0003196/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "getParameterValues", "parameterNames": ["InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnectionNumberOfEntries", "InternetGatewayDevice.Time.NTPServer1", "InternetGatewayDevice.Time.Status"] }'

You may request a single or multiple parameters at once.

After the task has been executed successfully you can then fetch the CPE object
and read the parameters from the JSON object.

.. code:: javascript

  query = {"_id": "00236a-96318REF-SR360NA0A4%2D0003196"}

.. code:: bash

  curl -i 'http://localhost:7557/devices/?query=%7B%22_id%22%3A%2200236a-96318REF-SR360NA0A4%252D0003196%22%7D'

``refreshObject``
~~~~~~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "refreshObject", "objectName": "InternetGatewayDevice.WANDevice.1.WANConnectionDevice"}'

``setParameterValues``
~~~~~~~~~~~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "setParameterValues", "parameterValues": [["InternetGatewayDevice.ManagementServer.UpgradesManaged",false]]}'

Multiple values can be set at once by adding multiple arrays to the
parameterValues key. For example:

.. code:: javascript

  {
    name: "setParameterValues",
    parameterValues: [["InternetGatewayDevice.ManagementServer.UpgradesManaged", false], ["InternetGatewayDevice.Time.Enable", true], ["InternetGatewayDevice.Time.NTPServer1", "pool.ntp.org"]]
  }

``addObject``
~~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name":"addObject","objectName":"InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection"}'

``deleteObject``
~~~~~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name":"deleteObject","objectName":"InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1"}'

``reboot``
~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "reboot"}'

``factoryReset``
~~~~~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "factoryReset"}'

``download``
~~~~~~~~~~~~

.. code:: bash

  curl -i 'http://localhost:7557/devices/00236a-SR552n-SR552NA084%252D0003269/tasks?timeout=3000&connection_request' \
  -X POST \
  --data '{"name": "download", "file": "mipsbe-6-42-lite.xml"}'

.. _presets:

Presets
-------

Presets assign a set of configuration or a Provision script to devices based on
a precondition (search filter), schedule (cron expression), and events.

Precondition
~~~~~~~~~~~~

The ``precondition`` property is a JSON string representation of the search
filter to test if the preset applies to a given device. Examples preconditions
are:

- ``{"param": "value"}``
- ``{"param": value", "param2": {"$ne": "value2"}}``

Other operators that can be used are ``$gt``, ``$lt``, ``$gte`` and ``$lte``.

Configuration
~~~~~~~~~~~~~

The configuration property is an array containing the different configurations
to be applied to a device, as shown below:

.. code:: javascript

  [
    {
      "type": "value",
      "name": "InternetGatewayDevice.ManagementServer.PeriodicInformEnable",
      "value": "true"
    },
    {
      "type": "value",
      "name": "InternetGatewayDevice.ManagementServer.PeriodicInformInterval",
      "value": "300"
    },
    {
      "type": "delete_object",
      "name": "object_parent",
      "object": "object_name"
    },
    {
      "type": "add_object",
      "name": "object_parent",
      "object": "object_name"
    },
    {
      "type": "provision",
      "name": "YourProvisionName"
    },
  ] 

The configuration type ``provision`` triggers a Provision script. In the
example above, the provision named "YourProvisionName" will be executed.

Provisions
----------

Create a provision
~~~~~~~~~~~~~~~~~~

The Provision's JavaScript code is the body of the HTTP PUT request.

.. code:: bash

  curl -X PUT -i 'http://localhost:7557/provisions/mynewprovision' --data 'log("Provision started at " + now);'

Delete a provision
~~~~~~~~~~~~~~~~~~

.. code:: bash

  curl -X DELETE -i 'http://localhost:7557/provisions/mynewprovision'

Get provisions
~~~~~~~~~~~~~~

Get all provisions:

.. code:: bash

  curl -X GET -i 'http://localhost:7557/provisions/'


================================================
FILE: docs/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

import json

# -- Project information -----------------------------------------------------

project = 'GenieACS Documentation'
copyright = '2024, GenieACS Inc.'
author = 'GenieACS Inc.'

# The full version, including alpha/beta/rc tags
release = json.load(open("../package.json"))["version"]


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = 'sphinx_rtd_theme'
html_logo = "logo.svg"
html_theme_options = {
  "logo_only": True
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

master_doc = 'index'

highlight_language = 'javascript'

================================================
FILE: docs/cpe-authentication.rst
================================================
.. _cpe-authentication:

CPE Authentication
==================

CPE to ACS
----------

.. note::

  By default GenieACS will accept any incoming connection via HTTP/HTTPS and
  respond to it.

The following parameters are used to set and get (password is redacted but
can be set) the username/password used to authenticate against the ACS:

Username: ``Device.ManagementServer.Username`` or ``InternetGatewayDevice.ManagementServer.Username``

Password: ``Device.ManagementServer.Password`` or ``InternetGatewayDevice.ManagementServer.Password``

Enable CPE to ACS Authentication
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CPE to ACS authentication can be configured in the web interface by using the
`Config` option in the `Admin` tab.

Go to the `Admin` -> `Config` page and click on `New config` button at the
bottom of the page. This will open pop-up which requires you to fill in a key
and value. The key should be ``cwmp.auth``. The value accepts a boolean.
Setting the value to ``true`` makes it so that GenieACS accepts any incoming
connection, setting it to ``false`` makes GenieACS deny all incoming
connections. This can be further configured using the ``AUTH()`` and ``EXT()``
functions.

The ``AUTH()`` function
~~~~~~~~~~~~~~~~~~~~~~~

The ``AUTH()`` function accepts two parameters, username and password. It
checks the given username and password with the incoming request to determine
whether to return true or false.

Basic usage of the ``AUTH()`` function could be as follows:

.. code:: sql

   AUTH("fixed-username", "fixed-password")

This will only accept incoming request who authenticate with
"fixed-username" and "fixed-password".

The various device parameters can be referenced from within the ``cwmp.auth``
expression. For example:

.. code:: sql

   AUTH(Device.ManagementServer.Username, Device.ManagementServer.Password)

The ``EXT()`` function
~~~~~~~~~~~~~~~~~~~~~~

The ``EXT()`` function makes it possible to call an :ref:`extension
<extensions>` script from the auth expression. This can be used to fetch
the credentials from an external source:

.. code:: sql

   AUTH(DeviceID.SerialNumber, EXT("authenticate", "getPassword", DeviceID.SerialNumber))

ACS to CPE
----------

TODO


================================================
FILE: docs/environment-variables.rst
================================================
.. _environment-variables:

Environment Variables
=====================

Configuring GenieACS services can be done through the following environment
variables:

.. attention::

  All GenieACS environment variables must be prefixed with ``GENIEACS_``.

MONGODB_CONNECTION_URL
  MongoDB connection string.

  Default: ``mongodb://127.0.0.1/genieacs``

EXT_DIR
  The directory from which to look up extension scripts.

  Default: ``<installation dir>/config/ext``

EXT_TIMEOUT
  Timeout (in milliseconds) to allow for calls to extensions to return a
  response.

  Default: ``3000``

DEBUG_FILE
  File to dump CPE debug log.

  Default: unset

DEBUG_FORMAT
  Debug log format. Valid values are 'yaml' and 'json'.

  Default: ``yaml``

LOG_FORMAT
  The format used for the log entries in ``CWMP_LOG_FILE``, ``NBI_LOG_FILE``,
  ``FS_LOG_FILE``, and ``UI_LOG_FILE``. Possible values are ``simple`` and
  ``json``.

  Default: ``simple``

ACCESS_LOG_FORMAT
  The format used for the log entries in ``CWMP_ACCESS_LOG_FILE``,
  ``NBI_ACCESS_LOG_FILE``, ``FS_ACCESS_LOG_FILE``, and ``UI_ACCESS_LOG_FILE``.
  Possible values are ``simple`` and ``json``.

  Default: ``simple``

CWMP_WORKER_PROCESSES
  The number of worker processes to spawn for genieacs-cwmp. A value of 0 means
  as many as there are CPU cores available.

  Default: ``0``

CWMP_PORT
  The TCP port that genieacs-cwmp listens on.

  Default: ``7547``

CWMP_INTERFACE
  The network interface that genieacs-cwmp binds to.

  Default: ``::``

CWMP_SSL_CERT
  Path to certificate file. If omitted, non-secure HTTP will be used.

  Default: unset

CWMP_SSL_KEY
  Path to certificate key file. If omitted, non-secure HTTP will be used.

  Default: unset

CWMP_LOG_FILE
  File to log process related events for genieacs-cwmp. If omitted, logs will
  go to stderr.

  Default: unset

CWMP_ACCESS_LOG_FILE
  File to log incoming requests for genieacs-cwmp. If omitted, logs will go to
  stdout.

  Default: unset

NBI_WORKER_PROCESSES
  The number of worker processes to spawn for genieacs-nbi. A value of 0 means
  as many as there are CPU cores available.

  Default: ``0``

NBI_PORT
  The TCP port that genieacs-nbi listens on.

  Default: ``7557``

NBI_INTERFACE
  The network interface that genieacs-nbi binds to.

  Default: ``::``

NBI_SSL_CERT
  Path to certificate file. If omitted, non-secure HTTP will be used.

  Default: unset

NBI_SSL_KEY
  Path to certificate key file. If omitted, non-secure HTTP will be used.

  Default: unset

NBI_LOG_FILE
  File to log process related events for genieacs-nbi. If omitted, logs will go
  to stderr.

  Default: unset

NBI_ACCESS_LOG_FILE
  File to log incoming requests for genieacs-nbi. If omitted, logs will go to
  stdout.

  Default: unset

FS_WORKER_PROCESSES
  The number of worker processes to spawn for genieacs-fs. A value of 0 means
  as many as there are CPU cores available.

  Default: ``0``

FS_PORT
  The TCP port that genieacs-fs listens on.

  Default: ``7567``

FS_INTERFACE
  The network interface that genieacs-fs binds to.

  Default: ``::``

FS_SSL_CERT
  Path to certificate file. If omitted, non-secure HTTP will be used.

  Default: unset

FS_SSL_KEY
  Path to certificate key file. If omitted, non-secure HTTP will be used.

  Default: unset

FS_LOG_FILE
  File to log process related events for genieacs-fs. If omitted, logs will go
  to stderr.

  Default: unset

FS_ACCESS_LOG_FILE
  File to log incoming requests for genieacs-fs. If omitted, logs will go to
  stdout.

  Default: unset

FS_URL_PREFIX
  The URL prefix (e.g. 'https://example.com:7567/') to use when generating the
  file URL for TR-069 Download requests. Set this if genieacs-fs and
  genieacs-cwmp are behind a proxy or running on different servers.

  Default: auto generated based on the hostname from the ACS URL, FS_PORT
  config, and whether or not SSL is enabled for genieacs-fs.

UI_WORKER_PROCESSES
  The number of worker processes to spawn for genieacs-ui. A value of 0 means
  as many as there are CPU cores available.

  Default: ``0``

UI_PORT
  The TCP port that genieacs-ui listens on.

  Default: ``3000``

UI_INTERFACE
  The network interface that genieacs-ui binds to.

  Default: ``::``

UI_SSL_CERT
  Path to certificate file. If omitted, non-secure HTTP will be used.

  Default: unset

UI_SSL_KEY
  Path to certificate key file. If omitted, non-secure HTTP will be used.

  Default: unset

UI_LOG_FILE
  File to log process related events for genieacs-ui. If omitted, logs will go
  to stderr.

  Default: unset

UI_ACCESS_LOG_FILE
  File to log incoming requests for genieacs-ui. If omitted, logs will go to
  stdout.

  Default: unset

UI_JWT_SECRET
  The key used for signing JWT tokens that are stored in browser cookies. The
  string can be up to 64 characters in length.

  Default: unset


================================================
FILE: docs/ext-sample.js
================================================
// This is an example GenieACS extension to get the current latitude/longitude
// of the International Space Station. Why, you ask? Because why not.
// To install, copy this file to config/ext/iss.js.

"use strict";

const http = require("http");

let cache = null;
let cacheExpire = 0;

function latlong(args, callback) {
  if (Date.now() < cacheExpire) return callback(null, cache);

  http
    .get("http://api.open-notify.org/iss-now.json", (res) => {
      if (res.statusCode !== 200)
        return callback(
          new Error(`Request failed (status code: ${res.statusCode})`),
        );

      let rawData = "";
      res.on("data", (chunk) => (rawData += chunk));

      res.on("end", () => {
        let pos = JSON.parse(rawData)["iss_position"];
        cache = [+pos["latitude"], +pos["longitude"]];
        cacheExpire = Date.now() + 10000;
        callback(null, cache);
      });
    })
    .on("error", (err) => {
      callback(err);
    });
}

exports.latlong = latlong;


================================================
FILE: docs/extensions.rst
================================================
.. _extensions:

Extensions
==========

Given that :ref:`provisions` and :ref:`virtual-parameters` are executed in a
sandbox environment, it is not possible to interact with external sources or
execute any action that requires OS, file system, or network access. Extensions
exist to bridge that gap.

Extensions are fully-privileged Node.js modules and as such have access to
standard Node libraries and 3rd party packages. Functions exposed by the
extension can be called from Provision scripts using the ``ext()`` function. A
typical use case for extensions is fetching credentials from a database to have
that pushed to the device during provisioning.

By default, the extension JS code must be placed under ``config/ext``
directory. You may need to create that directory if it doesn't already exist.

The example extension below fetches data from an external REST API and returns
that to the caller:

.. literalinclude:: ext-sample.js
  :language: javascript

To call this extension from a Provision or a Virtual Parameter script:

.. code:: javascript

  // The arguments "arg1" and "arg2" are passed to the latlong. Though they are
  // unused in this particular example.
  const res = ext("ext-sample", "latlong", "arg1", "arg2");
  log(JSON.stringify(res));


================================================
FILE: docs/https.rst
================================================
.. _https:

HTTPS
=====

TODO


================================================
FILE: docs/index.rst
================================================
.. GenieACS documentation master file, created by
   sphinx-quickstart on Wed Jun  5 13:47:06 2019.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to GenieACS's documentation!
====================================

.. toctree::
  :caption: Table of Contents

.. raw:: latex

   \part{Installation}

.. toctree::
  :maxdepth: 1
  :caption: Installation

  installation-guide
  environment-variables

.. raw:: latex

   \part{Administration}

.. toctree::
  :maxdepth: 1
  :caption: Administration

  provisions
  virtual-parameters
  administration-faq

.. raw:: latex

   \part{Integration}

.. toctree::
  :maxdepth: 1
  :caption: Integration

  extensions
  api-reference

.. raw:: latex

   \part{Security}

.. toctree::
  :maxdepth: 1
  :caption: Security

  https
  cpe-authentication
  roles-and-permissions


================================================
FILE: docs/installation-guide.rst
================================================
Installation Guide
==================

This guide is for installing GenieACS on a single server on any Linux distro
that uses *systemd* as its init system.

The various GenieACS services are independent of each other and may be
installed on different servers. You may also run multiple instances of each in
a load-balancing/failover setup.

.. attention::

  For production deployments make sure to configure TLS and change
  ``UI_JWT_SECRET`` to a unique and secure string. Refer to :ref:`https`
  section for how to enable TLS to encrypt traffic.

Prerequisites
-------------

.. topic:: Node.js

  GenieACS requires Node.js 12.13 and up. Refer to https://nodejs.org/ for
  instructions.

.. topic:: MongoDB

  GenieACS requires MongoDB 3.6 and up. Refer to https://www.mongodb.com/ for
  instructions.

Install GenieACS
-------------------

.. topic:: Installing from NPM:

  .. parsed-literal::

    sudo npm install -g genieacs@\ |release|

.. topic:: Installing from source

  If you prefer installing from source, such as when running a GenieACS copy
  with custom patches, refer to README.md file in the source package. Adjust
  the next steps below accordingly.

Configure systemd
-----------------

.. topic:: Create a system user to run GenieACS daemons

  .. code:: bash

    sudo useradd --system --no-create-home --user-group genieacs

.. topic:: Create directory to save extensions and environment file

  We'll use :file:`/opt/genieacs/ext/` directory to store extension scripts (if any).

  .. code:: bash
    
    mkdir /opt/genieacs
    mkdir /opt/genieacs/ext
    chown genieacs:genieacs /opt/genieacs/ext

  Create the file :file:`/opt/genieacs/genieacs.env` to hold our configuration
  options which we pass to GenieACS as environment variables. See
  :ref:`environment-variables` section for a list of all available
  configuration options.

  .. code:: bash

    GENIEACS_CWMP_ACCESS_LOG_FILE=/var/log/genieacs/genieacs-cwmp-access.log
    GENIEACS_NBI_ACCESS_LOG_FILE=/var/log/genieacs/genieacs-nbi-access.log
    GENIEACS_FS_ACCESS_LOG_FILE=/var/log/genieacs/genieacs-fs-access.log
    GENIEACS_UI_ACCESS_LOG_FILE=/var/log/genieacs/genieacs-ui-access.log
    GENIEACS_DEBUG_FILE=/var/log/genieacs/genieacs-debug.yaml
    NODE_OPTIONS=--enable-source-maps
    GENIEACS_EXT_DIR=/opt/genieacs/ext

  Generate a secure JWT secret and append to :file:`/opt/genieacs/genieacs.env`:

  .. code:: bash

    node -e "console.log(\"GENIEACS_UI_JWT_SECRET=\" + require('crypto').randomBytes(128).toString('hex'))" >> /opt/genieacs/genieacs.env
  
  Set file ownership and permissions:

  .. code:: bash

    sudo chown genieacs:genieacs /opt/genieacs/genieacs.env
    sudo chmod 600 /opt/genieacs/genieacs.env

.. topic:: Create logs directory

  .. code:: bash
    
    mkdir /var/log/genieacs
    chown genieacs:genieacs /var/log/genieacs

.. topic:: Create systemd unit files

  Create a systemd unit file for each of the four GenieACS services. Note that
  we're using EnvironmentFile directive to read the environment variables from
  the file we created earlier.

  Each service has two streams of logs: access log and process log. Access logs
  are configured here to be dumped in a log file under
  :file:`/var/log/genieacs/` while process logs go to *journald*. Use
  ``journalctl`` command to view process logs.

  .. attention::

    If the command :command:`systemctl edit --force --full` fails, you can
    create the unit file manually.

  1. Run the following command to create ``genieacs-cwmp`` service:
  
    .. code:: bash

      sudo systemctl edit --force --full genieacs-cwmp
    
    Then paste the following in the editor and save:

    .. code:: cfg

      [Unit]
      Description=GenieACS CWMP
      After=network.target

      [Service]
      User=genieacs
      EnvironmentFile=/opt/genieacs/genieacs.env
      ExecStart=/usr/bin/genieacs-cwmp

      [Install]
      WantedBy=default.target

  2. Run the following command to create ``genieacs-nbi`` service:
  
    .. code:: bash

      sudo systemctl edit --force --full genieacs-nbi
    
    Then paste the following in the editor and save:

    .. code:: cfg

      [Unit]
      Description=GenieACS NBI
      After=network.target

      [Service]
      User=genieacs
      EnvironmentFile=/opt/genieacs/genieacs.env
      ExecStart=/usr/bin/genieacs-nbi

      [Install]
      WantedBy=default.target

  3. Run the following command to create ``genieacs-fs`` service:
  
    .. code:: bash

      sudo systemctl edit --force --full genieacs-fs
    
    Then paste the following in the editor and save:

    .. code:: cfg

      [Unit]
      Description=GenieACS FS
      After=network.target

      [Service]
      User=genieacs
      EnvironmentFile=/opt/genieacs/genieacs.env
      ExecStart=/usr/bin/genieacs-fs

      [Install]
      WantedBy=default.target

  4. Run the following command to create ``genieacs-ui`` service:
  
    .. code:: bash

      sudo systemctl edit --force --full genieacs-ui
    
    Then paste the following in the editor and save:

    .. code:: cfg

      [Unit]
      Description=GenieACS UI
      After=network.target

      [Service]
      User=genieacs
      EnvironmentFile=/opt/genieacs/genieacs.env
      ExecStart=/usr/bin/genieacs-ui

      [Install]
      WantedBy=default.target

.. topic:: Configure log file rotation using logrotate

  Save the following as :file:`/etc/logrotate.d/genieacs`

  .. code::
  
    /var/log/genieacs/*.log /var/log/genieacs/*.yaml {
        daily
        rotate 30
        compress
        delaycompress
        dateext
    }

.. topic:: Enable and start services

  .. code:: bash

    sudo systemctl enable genieacs-cwmp
    sudo systemctl start genieacs-cwmp
    sudo systemctl status genieacs-cwmp

    sudo systemctl enable genieacs-nbi
    sudo systemctl start genieacs-nbi
    sudo systemctl status genieacs-nbi

    sudo systemctl enable genieacs-fs
    sudo systemctl start genieacs-fs
    sudo systemctl status genieacs-fs

    sudo systemctl enable genieacs-ui
    sudo systemctl start genieacs-ui
    sudo systemctl status genieacs-ui

  Review the status message for each to verify that the services are running
  successfully.


================================================
FILE: docs/provisions.rst
================================================
.. _provisions:

Provisions
==========

A Provision is a piece of JavaScript code that is executed on the server on a
per-device basis. It enables implementing complex provisioning scenarios and
other operations such as automated firmware upgrade rollout. Apart from a few
special functions, the script is essentially a standard ES6 code executed in
strict mode.

Provisions are mapped to devices using presets. Note that the added performance
overhead when using Provisions as opposed to simple preset configuration
entries is relatively small. Anything that can be done via preset
configurations can be done using a Provision script. In fact, the now
deprecated configuration format is still supported primarily for backward
compatibility and it is recommended to use Provision scripts for all
configuration.

When assigning a Provision script to a preset, you may pass arguments to the
script. The arguments can be accessed from the script through the global
``args`` variable.

.. note::

  Provision scripts may get executed multiple times in a given session.
  Although all data model-mutating operations are idempotent, a script as a
  whole may not be. It is, therefore, necessary to repeatedly run the script
  until there are no more side effects and a stable state is reached.

Built-in functions
------------------

``declare(path, timestamps, values)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This function is for declaring parameter values to be set, as well as specify
constraints on how recent you'd like the parameter value (or other attributes)
to have been refreshed from the device. If the given timestamp is lower than
the timestamp of the last refresh from the device, then this function will
return the last known value. Otherwise, the value will be fetched from the
device before being returned to the caller.

The timestamp argument is an object where the key is the attribute name (e.g.
``value``, ``object``, ``writable``, ``path``) and the value is an integer
representing a Unix timestamp.

The values argument is an object similar to the timestamp argument but its
property values being the parameter values to be set.

The possible attributes in 'timestamps' and 'values' arguments are:

- ``value``: a [<value>, <type>] pair

This attribute is not available for objects or object instances. If the value
is not a [<value>, <type>] array then it'll assumed to be a value without a
type and therefore the type will be inferred from the parameter's type.

- ``writable``: boolean

The meaning of this attribute can vary depending on the type of the parameter.
In the case of regular parameters, it indicates if its value is writable. In
the case of objects, it's whether or not it's possible to add new object
instances. In the case of object instances, it indicates whether or not this
instance can be deleted.

- ``object``: boolean

True if this is an object or object instance, false otherwise.

- ``path``: string

This attribute is special in that it's not a parameter attribute per se, but it
refers to the presence of parameters matching the given path. For example,
given the following wildcard path:

``InternetGatewayDevice.LANDevice.1.Hosts.Host.*.MACAddress``

Using a recent timestamp for path in ``declare()`` will result in a sync with
the device to rediscover all Host instances (``Host.*``). The path attribute
can also be used to create or delete object instances as described in
:ref:`path-format` section.

The return value of ``declare()`` is an iterator to access parameters that
match the given path. Each item in the iterator has the attribute 'path' in
addition to any other attribute given in the ``declare()`` call. The iterator
object itself has convenience attribute accessors which come in handy when
you're expecting a single parameter (e.g. when path does not contain wildcards
or aliases).

.. code:: javascript

  // Example: Setting the SSID as the last 6 characters of the serial number
  let serial = declare("Device.DeviceInfo.SerialNumber", {value: 1});
  declare("Device.LANDevice.1.WLANConfiguration.1.SSID", null, {value: serial.value[0]});

``clear(path, timestamp)``
~~~~~~~~~~~~~~~~~~~~~~~~~~

This function invalidates the database copy of parameters (and their child
parameters) that match the given path and have a last refresh timestamp that is
less than the given timestamp. The most obvious use for this function is to
invalidate the database copy of the entire data model after the device has been
factory reset:

.. code:: javascript

  // Example: Clear cached device data model Note
  // Make sure to apply only on "0 BOOTSTRAP" event
  clear("Device", Date.now());
  clear("InternetGatewayDevice", Date.now());

``commit()``
~~~~~~~~~~~~

This function commits the pending declarations and performs any necessary sync
with the device. It's usually not required to call this function as it called
implicitly at the end of the script and when accessing any property of the
promise-like object returned by the ``declare()`` function. Calling this
explicitly is only necessary if you want to control the order in which
parameters are configured.

``ext(file, function, arg1, arg2, ...)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Execute an extension script and return the result. The first argument is the
script filename while second argument is the function name within that script.
Any remaining arguments will be passed to that function. See :ref:`extensions`
for more details.

``log(message)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Prints out a string in genieacs-cwmp's access log. It's meant to be used for
debugging. Note that you may see multiple log entries as the script can be
executed multiple times in a session. See :ref:`this FAQ
<administration-faq-duplicate-log-entries>`.

.. _path-format:

Path format
-----------

A parameter path may contain a wildcard (``*``) or an alias filter
(``[name:value]``). A wildcard segment in a parameter path will apply the
declared configuration to zero or more parameters that match the given path
where the wildcard segment can be anything.

An alias filter is like a wildcard, but additionally performs filtering on the
child parameters based on the key-value pairs provided. For example, the
following path:

``Device.WANDevice.1.WANConnectionDevice.1.WANIPConnection.[AddressingType:DHCP].ExternalIPAddress``

will return a list of ExternalIPAddress parameters (0 or more) where the
sibling parameter AddressingType is assigned the value "DHCP".

This can be useful when the exact instance numbers may be different from one
device to another. It is possible to use more than one key-value pair in the
alias filter. It's also possible to use multiple filters or use a combination
of filters and wildcards.

Creating/deleting object instances
----------------------------------

Given the declarative nature of provisions, we cannot explicitly tell the
device to create or delete an instance under a given object. Instead, we
specify the number of instances we want there to be, and based on that GenieACS
will determine whether or not it needs to create or delete instances. For
example, the following declaration will ensure we have one and only one
WANIPConnection object:

.. code:: javascript

  // Example: Ensure we have one and only one WANIPConnection object
  declare("InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANIPConnection.*", null, {path: 1});

Note the wildcard at the end of the parameter path.

It is also possible to use alias filters as the last path segment which will
ensure that the declared number of instances is satisfied given the alias
filter:

.. code:: javascript

  // Ensure that *all* other instances are deleted
  declare("InternetGatewayDevice.X_BROADCOM_COM_IPAddrAccCtrl.X_BROADCOM_COM_IPAddrAccCtrlListCfg.[]", null, {path: 0});

  // Add the two entries we care about
  declare("InternetGatewayDevice.X_BROADCOM_COM_IPAddrAccCtrl.X_BROADCOM_COM_IPAddrAccCtrlListCfg.[SourceIPAddress:192.168.1.0,SourceNetMask:255.255.255.0]",  {path: now}, {path: 1});
  declare("InternetGatewayDevice.X_BROADCOM_COM_IPAddrAccCtrl.X_BROADCOM_COM_IPAddrAccCtrlListCfg.[SourceIPAddress:172.16.12.0,SourceNetMask:255.255.0.0]", {path: now}, {path: 1});

Special GenieACS parameters
---------------------------

In addition to the parameters exposed in the device's data model through
TR-069, GenieACS has its own set of special parameters:

``DeviceID``
~~~~~~~~~~~~

This parameter sub-tree includes the following read-only parameters:

- ``DeviceID.ID``
- ``DeviceID.SerialNumber``
- ``DeviceID.ProductClass``
- ``DeviceID.OUI``
- ``DeviceID.Manufacturer``

``Tags``
~~~~~~~~

The ``Tags`` root parameter is used to expose device tags in the data model.
Tags appear as child parameters that are writable and have boolean value.
Setting a tag to ``false`` will delete that tag, and setting the value of a
non-existing tag parameter to ``true`` will create it.

.. code:: javascript

  // Example: Remove "tag1", add "tag2", and read "tag3"
  declare("Tags.tag1", null, {value: false});
  declare("Tags.tag2", null, {value: true});
  let tag3 = declare("Tags.tag3", {value: 1});

``Reboot``
~~~~~~~~~~

The ``Reboot`` root parameter hold the timestamp of the last reboot command.
The parameter value is writable and declaring a timestamp value that is larger
than the current value will trigger a reboot.

.. code:: javascript

  // Example: Reboot the device only if it hasn't been rebooted in the past 300 seconds
  declare("Reboot", null, {value: Date.now() - (300 * 1000)});

``FactoryReset``
~~~~~~~~~~~~~~~~

Works like ``Reboot`` parameter but for factory reset.

.. code:: javascript

  // Example: Default the device to factory settings
  declare("FactoryReset", null, {value: Date.now()});

``Downloads``
~~~~~~~~~~~~~

The ``Downloads`` sub-tree holds information about the last download
command(s). A download command is represented as an instance (e.g.
``Downloads.1``) containing parameters such as ``Download`` (timestamp),
``LastFileType``, ``LastFileName``. The parameters ``FileType``, ``FileName``,
``TargetFileName`` and ``Download`` are writable and can be used to trigger a
new download.

.. code:: javascript

  declare("Downloads.[FileType:1 Firmware Upgrade Image]", {path: 1}, {path: 1});
  declare("Downloads.[FileType:1 Firmware Upgrade Image].FileName", {value: 1}, {value: "firmware-2017.01.tar"});
  declare("Downloads.[FileType:1 Firmware Upgrade Image].Download", {value: 1}, {value: Date.now()});

Common file types are:

- ``1 Firmware Upgrade Image``
- ``2 Web Content``
- ``3 Vendor Configuration File``
- ``4 Tone File``
- ``5 Ringer File``

.. warning::

  Pushing a file to the device is often a service-interrupting operation. It's
  recommended to only trigger it on certain events such as ``1 BOOT`` or during
  a predetermined maintenance window).

After the CPE had finished downloading and applying the config file, it will
send a ``7 TRANSFER COMPLETE`` event. You may use that to trigger a reboot
after the firmware image or configuration file had been applied.


================================================
FILE: docs/requirements.txt
================================================
sphinx_rtd_theme==2.0.0


================================================
FILE: docs/roles-and-permissions.rst
================================================
.. _roles-and-permissions:

Roles and Permissions
=====================

TODO


================================================
FILE: docs/virtual-parameters.rst
================================================
.. _virtual-parameters:

Virtual Parameters
==================

Virtual parameters are user-defined parameters whose values are generated using
a custom Javascript code. Virtual parameters behave just like regular
parameters and appear in the data model under ``VirtualParameters.`` path.
Virtual parameter names cannot contain a period (``.``).

The execution environment for virtual parameters is almost identical to that of
provisions. See :ref:`provisions` for more details and examples. The only
differences between the scripts of provisions and virtual parameters are:

- You can't pass custom arguments to virtual parameter scripts. Instead, the
  variable ``args`` will hold the current vparam timestamps and values as well
  as the declared timestamps and values. Like this:

.. code:: javascript

  // [<declared attr timestamps, declared attr values>, <current attr timestamps>, <current attr values>]
  [{path: 1559849387191, value: 1559849387191}, {value: ["new val", "xsd:string"]}, {path: 1559840000000, value: 1559840000000}, {value: ["cur val", "xsd:string"]}]

- Virtual parameter scripts must return an object containing the attributes of
  this parameter.

.. note::

  Just like a regular parameter, creating a virtual parameter does not
  automatically add it to the parameter list for a device. It needs to fetched
  (manually or via a preset) before you can see it in the data model.

Examples
--------

Unified MAC parameter across different device models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: javascript

  // Example: Unified MAC parameter across different device models
  let m = "00:00:00:00:00:00";
  let d = declare("Device.WANDevice.*.WANConnectionDevice.*.WANIPConnection.*.MACAddress", {value: Date.now()});
  let igd = declare("InternetGatewayDevice.WANDevice.*.WANConnectionDevice.*.WANPPPConnection.*.MACAddress", {value: Date.now()});

  if (d.size) {
    for (let p of d) {
      if (p.value[0]) {
        m = p.value[0];
        break;
      }
    }  
  }
  else if (igd.size) {
    for (let p of igd) {
      if (p.value[0]) {
        m = p.value[0];
        break;
      }
    }  
  }

  return {writable: false, value: [m, "xsd:string"]};

Expose an external value as a virtual parameter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: javascript

  // Example: Expose an external value as a virtual parameter
  let serial = declare("DeviceID.SerialNumber", {value: 1});
  if (args[1].value) {
    ext("example-ext", "set", serial.value[0], args[1].value[0]);
    return {writable: true, value: [args[1].value[0], "xsd:string"]};
  }
  else {
    let v = ext("example-ext", "get", serial.value[0]);
    return {writable: true, value: [v, "xsd:string"]};
  }

Create an editable virtual parameter for WPA passphrase
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: javascript

  // Example: Create an editable virtual parameter for WPA passphrase
  let m = "";
  if (args[1].value) {
    m = args[1].value[0];
    declare("Device.WiFi.AccessPoint.1.Security.KeyPassphrase", null, {value: m});
    declare("InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.KeyPassphrase", null, {value: m});
  }
  else {
    let d = declare("Device.WiFi.AccessPoint.1.Security.KeyPassphrase", {value: Date.now()});
    let igd = declare("InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.KeyPassphrase", {value: Date.now()});

    if (d.size) {
      m = d.value[0];
    }
    else if (igd.size) {
      m = igd.value[0];  
    }
  }

  return {writable: true, value: [m, "xsd:string"]};


================================================
FILE: eslint.config.mjs
================================================
import { defineConfig } from "@eslint/config-helpers";
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import eslintConfigPrettier from "eslint-config-prettier";
import globals from "globals";

export default defineConfig(
  {
    ignores: ["dist/", "test/*.js"],
  },
  eslint.configs.recommended,
  ...tseslint.configs.recommended,
  eslintConfigPrettier,
  {
    languageOptions: {
      globals: {
        ...globals.es2022,
        ...globals.node,
      },
      parserOptions: {
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
      },
    },
    rules: {
      "@typescript-eslint/no-shadow": ["error", { allow: ["err"] }],
      "handle-callback-err": "error",
      "prefer-arrow-callback": "error",
      "no-buffer-constructor": "error",
      "prefer-const": ["error", { destructuring: "all" }],
      eqeqeq: ["error", "always", { null: "ignore" }],
      "@typescript-eslint/no-explicit-any": "off",
      "@typescript-eslint/no-use-before-define": [
        "error",
        { functions: false },
      ],
      "@typescript-eslint/explicit-function-return-type": [
        "error",
        { allowExpressions: true },
      ],
      "@typescript-eslint/no-floating-promises": "error",
      "@typescript-eslint/no-misused-promises": "error",
      "no-prototype-builtins": "off",
    },
  },
  {
    files: ["ui/**/*.ts", "ui/**/*.tsx"],
    languageOptions: {
      globals: {
        ...globals.browser,
      },
    },
  },
  {
    files: ["seed/*.js"],
    languageOptions: {
      parserOptions: {
        project: null,
      },
      globals: {
        declare: "readonly",
        clear: "readonly",
        commit: "readonly",
        ext: "readonly",
        log: "readonly",
        args: "readonly",
      },
    },
    rules: {
      "@typescript-eslint/explicit-function-return-type": "off",
      "@typescript-eslint/no-floating-promises": "off",
      "@typescript-eslint/no-misused-promises": "off",
      "@typescript-eslint/no-shadow": "off",
      "no-shadow": ["error", { allow: ["err", "total"] }],
    },
  },
  {
    files: ["seed/*.jsx"],
    languageOptions: {
      parserOptions: {
        project: null,
      },
      globals: {
        ...globals.browser,
        node: "readonly",
        Signal: "readonly",
      },
    },
    rules: {
      "@typescript-eslint/explicit-function-return-type": "off",
      "@typescript-eslint/no-floating-promises": "off",
      "@typescript-eslint/no-misused-promises": "off",
      "@typescript-eslint/no-shadow": "off",
      "no-shadow": ["error", { allow: ["err", "total"] }],
    },
  },
);


================================================
FILE: lib/api-functions.ts
================================================
import { ObjectId } from "mongodb";
import { collections } from "./db/db.ts";
import {
  deleteConfig,
  deleteFault as dbDeleteFault,
  deleteFile,
  deletePermission,
  deletePreset,
  deleteProvision,
  deleteTask,
  deleteUser,
  deleteVirtualParameter,
  putConfig,
  putPermission,
  putPreset,
  putProvision,
  putUser,
  putVirtualParameter,
  putView,
  deleteView,
} from "./ui/db.ts";
import * as common from "./util.ts";
import * as cache from "./cache.ts";
import { acquireLock, getToken, releaseLock } from "./lock.ts";
import {
  getRevision,
  getConfig,
  getConfigExpression,
  getUsers,
} from "./ui/local-cache.ts";
import {
  httpConnectionRequest,
  udpConnectionRequest,
  xmppConnectionRequest,
} from "./connection-request.ts";
import { Task } from "./types.ts";
import Expression, { Value } from "./common/expression.ts";
import { hashPassword } from "./auth.ts";
import { flattenDevice } from "./ui/db.ts";
import { ResourceLockedError } from "./common/errors.ts";
import * as config from "../lib/config.ts";

const XMPP_CONFIGURED = !!config.get("XMPP_JID");

export async function connectionRequest(
  deviceId: string,
  device?: Record<string, Value>,
): Promise<string> {
  if (!device) {
    const res = await collections.devices.findOne({ _id: deviceId });
    if (!res) throw new Error("No such device");
    device = flattenDevice(res);
  }

  let connectionRequestUrl,
    udpConnectionRequestAddress,
    stunEnable,
    connReqJabberId,
    username,
    password;

  if (device["InternetGatewayDevice.ManagementServer.ConnectionRequestURL"]) {
    connectionRequestUrl =
      device["InternetGatewayDevice.ManagementServer.ConnectionRequestURL"] ||
      "";
    udpConnectionRequestAddress =
      device[
        "InternetGatewayDevice.ManagementServer.UDPConnectionRequestAddress"
      ] || "";
    stunEnable =
      device["InternetGatewayDevice.ManagementServer.STUNEnable"] || "";
    connReqJabberId =
      device["InternetGatewayDevice.ManagementServer.ConnReqJabberID"] || "";
    username =
      device[
        "InternetGatewayDevice.ManagementServer.ConnectionRequestUsername"
      ] || "";
    password =
      device[
        "InternetGatewayDevice.ManagementServer.ConnectionRequestPassword"
      ] || "";
  } else {
    connectionRequestUrl =
      device["Device.ManagementServer.ConnectionRequestURL"] || "";
    udpConnectionRequestAddress =
      device["Device.ManagementServer.UDPConnectionRequestAddress"] || "";
    stunEnable = device["Device.ManagementServer.STUNEnable"] || "";
    connReqJabberId = device["Device.ManagementServer.ConnReqJabberID"] || "";
    username =
      device["Device.ManagementServer.ConnectionRequestUsername"] || "";
    password =
      device["Device.ManagementServer.ConnectionRequestPassword"] || "";
  }
  let remoteAddress;
  try {
    remoteAddress = new URL(connectionRequestUrl).hostname;
  } catch {
    return "Invalid connection request URL";
  }

  const snapshot = await getRevision();
  const now = Date.now();

  const evalCallback = (exp: Expression): Expression => {
    if (exp instanceof Expression.Parameter) {
      let name = exp.path.toString();
      if (name === "id") name = "DeviceID.ID";
      else if (name === "serialNumber") name = "DeviceID.SerialNumber";
      else if (name === "productClass") name = "DeviceID.ProductClass";
      else if (name === "oui") name = "DeviceID.OUI";
      else if (name === "remoteAddress")
        return new Expression.Literal(remoteAddress);
      else if (name === "username") return new Expression.Literal(username);
      else if (name === "password") return new Expression.Literal(password);
      return new Expression.Literal(device[name] ?? null);
    } else if (exp instanceof Expression.FunctionCall) {
      if (exp.name === "NOW") return new Expression.Literal(now);
      else if (exp.name === "REMOTE_ADDRESS")
        return new Expression.Literal(remoteAddress);
      else if (exp.name === "USERNAME") return new Expression.Literal(username);
      else if (exp.name === "PASSWORD") return new Expression.Literal(password);
    }
    return exp;
  };

  const configCallback = (exp: Expression): Expression.Literal => {
    const e = evalCallback(exp);
    if (e instanceof Expression.Literal) return e;
    return new Expression.Literal(null);
  };

  const UDP_CONNECTION_REQUEST_PORT = getConfig(
    snapshot,
    "cwmp.udpConnectionRequestPort",
    0,
    configCallback,
  );
  const CONNECTION_REQUEST_TIMEOUT = getConfig(
    snapshot,
    "cwmp.connectionRequestTimeout",
    2000,
    configCallback,
  );
  const CONNECTION_REQUEST_ALLOW_BASIC_AUTH = getConfig(
    snapshot,
    "cwmp.connectionRequestAllowBasicAuth",
    false,
    configCallback,
  );
  let authExp: Expression = getConfigExpression(
    snapshot,
    "cwmp.connectionRequestAuth",
  );

  if (!authExp) {
    authExp = new Expression.FunctionCall("AUTH", [
      new Expression.FunctionCall("USERNAME", []),
      new Expression.FunctionCall("PASSWORD", []),
    ]);
  }

  authExp = authExp.evaluate(evalCallback);

  const debug = getConfig(snapshot, "cwmp.debug", false, configCallback);

  let udpProm = Promise.resolve(false);
  if (udpConnectionRequestAddress && +stunEnable) {
    try {
      const u = new URL("udp://" + udpConnectionRequestAddress);
      udpProm = udpConnectionRequest(
        u.hostname,
        parseInt(u.port || "80"),
        authExp,
        UDP_CONNECTION_REQUEST_PORT,
        debug,
        deviceId,
      ).then(
        () => true,
        () => false,
      );
    } catch {
      // Ignore invalid address
    }
  }

  let status;

  if (connReqJabberId && XMPP_CONFIGURED) {
    status = await xmppConnectionRequest(
      connReqJabberId,
      authExp,
      CONNECTION_REQUEST_TIMEOUT,
      debug,
      deviceId,
    );
  } else {
    status = await httpConnectionRequest(
      connectionRequestUrl,
      authExp,
      CONNECTION_REQUEST_ALLOW_BASIC_AUTH,
      CONNECTION_REQUEST_TIMEOUT,
      debug,
      deviceId,
    );
  }

  if (await udpProm) return "";

  return status;
}

export async function awaitSessionStart(
  deviceId: string,
  lastInform: number,
  timeout: number,
): Promise<boolean> {
  const now = Date.now();
  const device = await collections.devices.findOne(
    { _id: deviceId },
    { projection: { _lastInform: 1 } },
  );
  const li = (device["_lastInform"] as Date).getTime();
  if (li > lastInform) return true;
  const token = await getToken(`cwmp_session_${deviceId}`);
  if (token?.startsWith("cwmp_session_")) return true;
  if (timeout < 500) return false;
  await new Promise((resolve) => setTimeout(resolve, 500));
  timeout -= Date.now() - now;
  return awaitSessionStart(deviceId, lastInform, timeout);
}

export async function awaitSessionEnd(
  deviceId: string,
  timeout: number,
): Promise<boolean> {
  const now = Date.now();
  const token = await getToken(`cwmp_session_${deviceId}`);
  if (!token?.startsWith("cwmp_session_")) return true;
  if (timeout < 500) return false;
  await new Promise((resolve) => setTimeout(resolve, 500));
  timeout -= Date.now() - now;
  return awaitSessionEnd(deviceId, timeout);
}

function sanitizeTask(task): void {
  task.timestamp = new Date(task.timestamp || Date.now());
  if (task.expiry) {
    if (task.expiry instanceof Date || isNaN(task.expiry))
      task.expiry = new Date(task.expiry);
    else task.expiry = new Date(task.timestamp.getTime() + +task.expiry * 1000);
  }

  const validParamValue = (p): boolean => {
    if (
      !Array.isArray(p) ||
      p.length < 2 ||
      typeof p[0] !== "string" ||
      !p[0].length ||
      !["string", "boolean", "number"].includes(typeof p[1]) ||
      (p[2] != null && typeof p[2] !== "string")
    )
      return false;
    return true;
  };

  switch (task.name) {
    case "getParameterValues":
      if (!Array.isArray(task.parameterNames) || !task.parameterNames.length)
        throw new Error("Missing 'parameterNames' property");
      for (const p of task.parameterNames) {
        if (typeof p !== "string" || !p.length)
          throw new Error(`Invalid parameter name '${p}'`);
      }
      break;

    case "setParameterValues":
      if (!Array.isArray(task.parameterValues) || !task.parameterValues.length)
        throw new Error("Missing 'parameterValues' property");
      for (const p of task.parameterValues) {
        if (!validParamValue(p))
          throw new Error(`Invalid parameter value '${p}'`);
      }
      break;

    case "refreshObject":
      if (typeof task.objectName !== "string")
        throw new Error("Missing 'objectName' property");
      break;

    case "deleteObject":
      if (typeof task.objectName !== "string" || !task.objectName.length)
        throw new Error("Missing 'objectName' property");
      break;

    case "addObject":
      if (task.parameterValues != null) {
        if (!Array.isArray(task.parameterValues))
          throw new Error("Invalid 'parameterValues' property");
        for (const p of task.parameterValues) {
          if (!validParamValue(p))
            throw new Error(`Invalid parameter value '${p}'`);
        }
      }
      break;

    case "download":
      // genieacs-gui sends file ID instead of fileName and fileType
      if (!task.file) {
        if (typeof task.fileType !== "string" || !task.fileType.length)
          throw new Error("Missing 'fileType' property");

        if (typeof task.fileName !== "string" || !task.fileName.length)
          throw new Error("Missing 'fileName' property");
      }

      if (
        task.targetFileName != null &&
        typeof task.targetFileName !== "string"
      )
        throw new Error("Invalid 'targetFileName' property");
      break;

    case "provisions":
      if (
        !Array.isArray(task.provisions) ||
        !task.provisions.every((arr) =>
          arr.every(
            (s) =>
              s == null || ["boolean", "number", "string"].includes(typeof s),
          ),
        )
      )
        throw new Error("Invalid 'provisions' property");
      break;

    case "reboot":
      break;

    case "factoryReset":
      break;

    default:
      throw new Error("Invalid task name");
  }

  return task;
}

export async function insertTasks(tasks: any[]): Promise<Task[]> {
  if (tasks && !Array.isArray(tasks)) tasks = [tasks];
  else if (!tasks?.length) return tasks || [];

  for (const task of tasks) {
    sanitizeTask(task);
    if (task.uniqueKey) {
      await collections.tasks.deleteOne({
        device: task.device,
        uniqueKey: task.uniqueKey,
      });
    }
  }
  await collections.tasks.insertMany(tasks);
  for (const task of tasks) task._id = task._id.toString();
  return tasks;
}

export async function deleteDevice(deviceId: string): Promise<void> {
  const token = await acquireLock(`cwmp_session_${deviceId}`, 5000);
  if (!token) throw new ResourceLockedError("Device is in session");
  try {
    await Promise.all([
      collections.tasks.deleteMany({ device: deviceId }),
      collections.devices.deleteOne({ _id: deviceId }),
      collections.faults.deleteMany({
        _id: {
          $regex: `^${common.escapeRegExp(deviceId)}\\:`,
        },
      }),
      collections.operations.deleteMany({
        _id: {
          $regex: `^${common.escapeRegExp(deviceId)}\\:`,
        },
      }),
    ]);
  } finally {
    await releaseLock(`cwmp_session_${deviceId}`, token);
  }
}

export async function deleteFault(id: string): Promise<void> {
  const deviceId = id.split(":", 1)[0];
  const channel = id.slice(deviceId.length + 1);
  const token = await acquireLock(`cwmp_session_${deviceId}`, 5000);
  if (!token) throw new ResourceLockedError("Device is in session");
  try {
    const proms = [dbDeleteFault(id)];
    if (channel.startsWith("task_"))
      proms.push(deleteTask(new ObjectId(channel.slice(5))));
    await Promise.all(proms);
  } finally {
    await releaseLock(`cwmp_session_${deviceId}`, token);
  }
}

export async function deleteResource(
  resource: string,
  id: string,
): Promise<void> {
  if (resource === "devices") {
    await deleteDevice(id);
  } else if (resource === "files") {
    await deleteFile(id);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "faults") {
    await deleteFault(id);
  } else if (resource === "provisions") {
    await deleteProvision(id);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "presets") {
    await deletePreset(id);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "virtualParameters") {
    await deleteVirtualParameter(id);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "config") {
    await deleteConfig(id);
    await Promise.all([
      cache.del("ui-local-cache-hash"),
      cache.del("cwmp-local-cache-hash"),
    ]);
  } else if (resource === "permissions") {
    await deletePermission(id);
    await cache.del("ui-local-cache-hash");
  } else if (resource === "users") {
    await deleteUser(id);
    await cache.del("ui-local-cache-hash");
  } else if (resource === "views") {
    await deleteView(id);
    await cache.del("ui-local-cache-hash");
  } else {
    throw new Error(`Unknown resource ${resource}`);
  }
}

// TODO Implement validation
export async function putResource(
  resource: string,
  id: string,
  data: any,
): Promise<void> {
  if (resource === "presets") {
    await putPreset(id, data);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "provisions") {
    await putProvision(id, data);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "virtualParameters") {
    await putVirtualParameter(id, data);
    await cache.del("cwmp-local-cache-hash");
  } else if (resource === "config") {
    await putConfig(id, data);
    await Promise.all([
      cache.del("ui-local-cache-hash"),
      cache.del("cwmp-local-cache-hash"),
    ]);
  } else if (resource === "permissions") {
    await putPermission(id, data);
    await cache.del("ui-local-cache-hash");
  } else if (resource === "users") {
    delete data["password"];
    delete data["salt"];
    await putUser(id, data);
    await cache.del("ui-local-cache-hash");
  } else if (resource === "views") {
    await putView(id, data);
    await cache.del("ui-local-cache-hash");
  } else {
    throw new Error(`Unknown resource ${resource}`);
  }
}

export function authLocal(
  snapshot: string,
  username: string,
  password: string,
): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const users = getUsers(snapshot);
    const user = users[username];
    if (!user?.password) return void resolve(null);
    hashPassword(password, user.salt)
      .then((hash) => {
        if (hash === user.password) resolve(true);
        else resolve(false);
      })
      .catch(reject);
  });
}


================================================
FILE: lib/auth.ts
================================================
import { createHash, randomBytes, pbkdf2 } from "node:crypto";

function parseHeaderFeilds(str: string): Record<string, string> {
  const res = {};
  const parts = str.split(",");

  let part: string;
  while ((part = parts.shift()) != null) {
    const name = part.split("=", 1)[0];
    if (name.length === part.length) {
      if (!part.trim()) continue;
      throw new Error("Unable to parse auth header");
    }

    let value = part.slice(name.length + 1);
    if (!/^\s*"/.test(value)) {
      value = value.trim();
    } else {
      while (!/[^\\]"\s*$/.test(value)) {
        const p = parts.shift();
        if (p == null) throw new Error("Unable to parse auth header");
        value += "," + p;
      }

      try {
        value = JSON.parse(value);
      } catch (error) {
        throw new Error("Unable to parse auth header", { cause: error });
      }
    }
    res[name.trim()] = value;
  }
  return res;
}

export function parseAuthorizationHeader(authHeader: string): {
  method: string;
} {
  authHeader = authHeader.trim();
  const method = authHeader.split(" ", 1)[0];
  const res = { method: method };

  if (method === "Basic") {
    // Inspired by https://github.com/jshttp/basic-auth
    const USER_PASS_REGEX = /^
Download .txt
gitextract_j_xjh90s/

├── .gitignore
├── .prettierignore
├── AGENTS.md
├── ARCHITECTURE.md
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── bin/
│   ├── genieacs-cwmp.ts
│   ├── genieacs-ext.ts
│   ├── genieacs-fs.ts
│   ├── genieacs-nbi.ts
│   └── genieacs-ui.ts
├── build/
│   ├── assets.ts
│   ├── build.ts
│   ├── generate-fonts.sh
│   ├── lint.ts
│   ├── spellcheck-dict.pws
│   ├── spellcheck.sh
│   └── test.ts
├── docs/
│   ├── .readthedocs.yaml
│   ├── administration-faq.rst
│   ├── api-reference.rst
│   ├── conf.py
│   ├── cpe-authentication.rst
│   ├── environment-variables.rst
│   ├── ext-sample.js
│   ├── extensions.rst
│   ├── https.rst
│   ├── index.rst
│   ├── installation-guide.rst
│   ├── provisions.rst
│   ├── requirements.txt
│   ├── roles-and-permissions.rst
│   └── virtual-parameters.rst
├── eslint.config.mjs
├── lib/
│   ├── api-functions.ts
│   ├── auth.ts
│   ├── bundle-views.ts
│   ├── cache.ts
│   ├── cluster.ts
│   ├── common/
│   │   ├── authorizer.ts
│   │   ├── debounce.ts
│   │   ├── errors.ts
│   │   ├── expression/
│   │   │   ├── evaluate.ts
│   │   │   ├── normalize.ts
│   │   │   ├── pagination.ts
│   │   │   ├── parser.ts
│   │   │   └── synth.ts
│   │   ├── expression.ts
│   │   ├── memoize.ts
│   │   ├── path-set.ts
│   │   ├── path.ts
│   │   └── yaml.ts
│   ├── config.ts
│   ├── connection-request.ts
│   ├── cwmp/
│   │   ├── db.ts
│   │   └── local-cache.ts
│   ├── cwmp.ts
│   ├── db/
│   │   ├── db.ts
│   │   ├── synth.ts
│   │   ├── types.ts
│   │   └── util.ts
│   ├── debug.ts
│   ├── default-provisions.ts
│   ├── device.ts
│   ├── extensions.ts
│   ├── forwarded.ts
│   ├── fs.ts
│   ├── gpn-heuristic.ts
│   ├── init.ts
│   ├── instance-set.ts
│   ├── local-cache.ts
│   ├── lock.ts
│   ├── logger.ts
│   ├── nbi.ts
│   ├── ping.ts
│   ├── query.ts
│   ├── sandbox.ts
│   ├── scheduling.ts
│   ├── server.ts
│   ├── session.ts
│   ├── soap.ts
│   ├── types.ts
│   ├── ui/
│   │   ├── api.ts
│   │   ├── db.ts
│   │   └── local-cache.ts
│   ├── ui.ts
│   ├── util.ts
│   ├── versioned-map.ts
│   ├── xml-parser.ts
│   └── xmpp-client.ts
├── npm-shrinkwrap.json
├── package.json
├── seed/
│   ├── bootstrap.js
│   ├── datamodel-explorer.jsx
│   ├── default.js
│   ├── device-page-tr098.jsx
│   ├── device-page-tr181.jsx
│   ├── device-page.jsx
│   ├── icon.jsx
│   ├── inform.js
│   ├── instance-table.jsx
│   ├── overview-page.jsx
│   ├── parameter.jsx
│   ├── pie-chart.jsx
│   ├── provisions.d.ts
│   ├── summon-button.jsx
│   ├── tags.jsx
│   ├── tsconfig.json
│   └── views.d.ts
├── test/
│   ├── auth.ts
│   ├── db.ts
│   ├── device.ts
│   ├── mocks/
│   │   └── store.ts
│   ├── pagination.ts
│   ├── path-set.ts
│   ├── path.ts
│   ├── ping.ts
│   ├── reactive-store.ts
│   ├── signals.ts
│   ├── synth.ts
│   ├── util.ts
│   ├── xml-parser.ts
│   ├── yaml-tests.json
│   └── yaml.ts
├── tsconfig.json
└── ui/
    ├── app.ts
    ├── autocomplete-compnent.ts
    ├── change-password-component.ts
    ├── code-editor-component.ts
    ├── codemirror-loader.ts
    ├── components/
    │   ├── all-parameters.ts
    │   ├── container.ts
    │   ├── device-actions.ts
    │   ├── device-faults.ts
    │   ├── device-link.ts
    │   ├── loading.ts
    │   ├── overview-dot.ts
    │   ├── parameter-list.ts
    │   ├── parameter-table.ts
    │   ├── parameter.ts
    │   ├── ping.ts
    │   ├── summon-button.ts
    │   └── tags.ts
    ├── components.ts
    ├── config-functions.ts
    ├── config-page.ts
    ├── config.ts
    ├── css/
    │   └── app.css
    ├── datalist.ts
    ├── device-page.ts
    ├── devices-page.ts
    ├── drawer-component.ts
    ├── dynamic-loader.ts
    ├── error-page.ts
    ├── faults-page.ts
    ├── files-page.ts
    ├── filter-component.ts
    ├── index-table-component.ts
    ├── layout.tsx
    ├── login-page.tsx
    ├── long-text-component.ts
    ├── notifications.ts
    ├── overlay.ts
    ├── overview-page.ts
    ├── permissions-page.ts
    ├── pie-chart-component.ts
    ├── presets-page.ts
    ├── provisions-page.ts
    ├── put-form-component.ts
    ├── reactive-store.ts
    ├── signals.ts
    ├── skewed-date.ts
    ├── smart-query.ts
    ├── store.ts
    ├── tailwind-utility-components.ts
    ├── task-queue.ts
    ├── timeago.ts
    ├── ui-config-component.ts
    ├── users-page.ts
    ├── views-bundle-placeholder.ts
    ├── views-page.ts
    ├── views.ts
    ├── virtual-parameters-page.ts
    ├── wizard-page.ts
    └── yaml-loader.ts
Download .txt
SYMBOL INDEX (1209 symbols across 127 files)

FILE: bin/genieacs-cwmp.ts
  constant SERVICE_ADDRESS (line 12) | const SERVICE_ADDRESS = config.get("CWMP_INTERFACE") as string;
  constant SERVICE_PORT (line 13) | const SERVICE_PORT = config.get("CWMP_PORT") as number;
  function exitWorkerGracefully (line 15) | function exitWorkerGracefully(): void {
  function exitWorkerUngracefully (line 26) | function exitWorkerUngracefully(): void {

FILE: bin/genieacs-ext.ts
  function errorToFault (line 7) | function errorToFault(err: Error): Fault {

FILE: bin/genieacs-fs.ts
  constant SERVICE_ADDRESS (line 11) | const SERVICE_ADDRESS = config.get("FS_INTERFACE") as string;
  constant SERVICE_PORT (line 12) | const SERVICE_PORT = config.get("FS_PORT") as number;
  function exitWorkerGracefully (line 14) | function exitWorkerGracefully(): void {
  function exitWorkerUngracefully (line 21) | function exitWorkerUngracefully(): void {

FILE: bin/genieacs-nbi.ts
  constant SERVICE_ADDRESS (line 12) | const SERVICE_ADDRESS = config.get("NBI_INTERFACE") as string;
  constant SERVICE_PORT (line 13) | const SERVICE_PORT = config.get("NBI_PORT") as number;
  function exitWorkerGracefully (line 15) | function exitWorkerGracefully(): void {
  function exitWorkerUngracefully (line 26) | function exitWorkerUngracefully(): void {

FILE: bin/genieacs-ui.ts
  constant SERVICE_ADDRESS (line 12) | const SERVICE_ADDRESS = config.get("UI_INTERFACE") as string;
  constant SERVICE_PORT (line 13) | const SERVICE_PORT = config.get("UI_PORT") as number;
  function exitWorkerGracefully (line 15) | function exitWorkerGracefully(): void {
  function exitWorkerUngracefully (line 26) | function exitWorkerUngracefully(): void {

FILE: build/assets.ts
  constant APP_JS (line 1) | const APP_JS = "app.js";
  constant APP_CSS (line 2) | const APP_CSS = "app.css";
  constant ICONS_SVG (line 3) | const ICONS_SVG = "icons.svg";
  constant LOGO_SVG (line 4) | const LOGO_SVG = "logo.svg";
  constant FAVICON_PNG (line 5) | const FAVICON_PNG = "favicon.png";

FILE: build/build.ts
  constant MODE (line 26) | const MODE = process.env["NODE_ENV"] || "production";
  constant INPUT_DIR (line 28) | const INPUT_DIR = process.cwd();
  constant OUTPUT_DIR (line 29) | const OUTPUT_DIR = path.join(INPUT_DIR, "dist");
  function rmDir (line 31) | async function rmDir(dirPath: string): Promise<void> {
  function stripDevDeps (line 44) | function stripDevDeps(deps): void {
  function stripDevDeps2 (line 54) | function stripDevDeps2(deps): void {
  function xmlTostring (line 62) | function xmlTostring(xml): string {
  function assetHash (line 71) | function assetHash(buffer: Buffer | string): string {
  constant ASSETS (line 75) | const ASSETS = {} as {
  method setup (line 85) | setup(build) {
  method setup (line 97) | setup(build) {
  method setup (line 110) | setup(build) {
  method setup (line 122) | setup(build) {
  function generateSymbol (line 147) | function generateSymbol(id: string, svgStr: string): string {
  function getBuildMetadata (line 164) | async function getBuildMetadata(): Promise<string> {
  function init (line 182) | async function init(): Promise<void> {
  function copyStatic (line 220) | async function copyStatic(): Promise<void> {
  function generateCss (line 251) | async function generateCss(): Promise<void> {
  function generateBackendJs (line 290) | async function generateBackendJs(): Promise<void> {
  function generateFrontendJs (line 326) | async function generateFrontendJs(): Promise<void> {
  function generateIconsSprite (line 358) | async function generateIconsSprite(): Promise<void> {

FILE: build/lint.ts
  function runEslint (line 6) | async function runEslint(): Promise<string> {
  function runTsc (line 23) | async function runTsc(): Promise<string> {
  function runPrettier (line 34) | async function runPrettier(): Promise<string> {
  function runAll (line 45) | async function runAll(): Promise<void> {

FILE: build/test.ts
  constant INPUT_DIR (line 6) | const INPUT_DIR = process.cwd();
  method setup (line 11) | setup(build) {
  method setup (line 28) | setup(build) {
  function buildTests (line 52) | async function buildTests(): Promise<void> {

FILE: docs/ext-sample.js
  function latlong (line 12) | function latlong(args, callback) {

FILE: lib/api-functions.ts
  constant XMPP_CONFIGURED (line 43) | const XMPP_CONFIGURED = !!config.get("XMPP_JID");
  function connectionRequest (line 45) | async function connectionRequest(
  function awaitSessionStart (line 212) | async function awaitSessionStart(
  function awaitSessionEnd (line 232) | async function awaitSessionEnd(
  function sanitizeTask (line 245) | function sanitizeTask(task): void {
  function insertTasks (line 349) | async function insertTasks(tasks: any[]): Promise<Task[]> {
  function deleteDevice (line 367) | async function deleteDevice(deviceId: string): Promise<void> {
  function deleteFault (line 390) | async function deleteFault(id: string): Promise<void> {
  function deleteResource (line 405) | async function deleteResource(
  function putResource (line 446) | async function putResource(
  function authLocal (line 482) | function authLocal(

FILE: lib/auth.ts
  function parseHeaderFeilds (line 3) | function parseHeaderFeilds(str: string): Record<string, string> {
  function parseAuthorizationHeader (line 36) | function parseAuthorizationHeader(authHeader: string): {
  function parseWwwAuthenticateHeader (line 60) | function parseWwwAuthenticateHeader(
  function basic (line 70) | function basic(username: string, password: string): string {
  function digest (line 74) | function digest(
  function solveDigest (line 119) | function solveDigest(
  function generateSalt (line 162) | function generateSalt(length: number): Promise<string> {
  function hashPassword (line 171) | function hashPassword(pass: string, salt: string): Promise<string> {

FILE: lib/bundle-views.ts
  function validateViewScript (line 6) | async function validateViewScript(
  function buildInput (line 26) | function buildInput(views: Views): string {
  function bundleViews (line 49) | async function bundleViews(views: Views): Promise<string> {
  function runBuild (line 53) | async function runBuild(input: string): Promise<string> {

FILE: lib/cache.ts
  constant CLOCK_SKEW_TOLERANCE (line 4) | const CLOCK_SKEW_TOLERANCE = 30000;
  constant MAX_CACHE_TTL (line 5) | const MAX_CACHE_TTL = +config.get("MAX_CACHE_TTL");
  function get (line 7) | async function get(key: string): Promise<string> {
  function del (line 12) | async function del(key: string): Promise<void> {
  function set (line 16) | async function set(
  function pop (line 32) | async function pop(key: string): Promise<string> {

FILE: lib/cluster.ts
  function fork (line 8) | function fork(): Worker {
  function restartWorker (line 20) | function restartWorker(worker, code, signal): void {
  function start (line 73) | function start(
  function stop (line 100) | function stop(): void {

FILE: lib/common/authorizer.ts
  class Authorizer (line 4) | class Authorizer {
    method constructor (line 13) | public constructor(permissionSets: PermissionSet[]) {
    method hasAccess (line 20) | public hasAccess(resourceType: string, access: number): boolean {
    method getFilter (line 41) | public getFilter(resourceType: string, access: number): Expression {
    method getValidator (line 60) | public getValidator(
    method getPermissionSets (line 126) | public getPermissionSets(): PermissionSet[] {

FILE: lib/common/debounce.ts
  function debounce (line 1) | function debounce<T>(

FILE: lib/common/errors.ts
  class ResourceLockedError (line 1) | class ResourceLockedError extends Error {
    method constructor (line 2) | constructor(message: string) {

FILE: lib/common/expression.ts
  type Value (line 9) | type Value = string | number | boolean | null;
  method toString (line 19) | toString(): string {
  method evaluate (line 24) | evaluate<T extends Expression>(fn: (e: Expression) => T = (e) => e as T)...
  method evaluateAsync (line 28) | async evaluateAsync<T extends Expression>(
  method parse (line 36) | static parse(input: string): Expression {
  method and (line 43) | static and(left: Expression, right: Expression): Expression {
  method or (line 81) | static or(left: Expression, right: Expression): Expression {
  class Literal (line 122) | class Literal extends Expression {
    method constructor (line 123) | constructor(public readonly value: Value) {
    method map (line 127) | map(): Literal {
    method mapAsync (line 131) | async mapAsync(): Promise<Literal> {
  class Parameter (line 136) | class Parameter extends Expression {
    method constructor (line 137) | constructor(public readonly path: Path) {
    method map (line 141) | map(): Parameter {
    method mapAsync (line 145) | async mapAsync(): Promise<Parameter> {
    method toString (line 149) | toString(): string {
  class Unary (line 154) | class Unary extends Expression {
    method constructor (line 155) | constructor(
    method map (line 162) | map(fn: (e: Expression, i: number) => Expression): Unary {
    method mapAsync (line 168) | async mapAsync(
  class Binary (line 177) | class Binary extends Expression {
    method constructor (line 178) | constructor(
    method map (line 186) | map(fn: (e: Expression, i: number) => Expression): Binary {
    method mapAsync (line 193) | async mapAsync(
  class FunctionCall (line 203) | class FunctionCall extends Expression {
    method constructor (line 204) | constructor(
    method map (line 211) | map(fn: (e: Expression, i: number) => Expression): FunctionCall {
    method mapAsync (line 217) | async mapAsync(
  class Conditional (line 226) | class Conditional extends Expression {
    method constructor (line 227) | constructor(
    method map (line 235) | map(fn: (e: Expression, i: number) => Expression): Conditional {
    method mapAsync (line 248) | async mapAsync(
  function extractPaths (line 265) | function extractPaths(exp: Expression): Path[] {
  function parseList (line 276) | function parseList(input: string): Expression[] {

FILE: lib/common/expression/evaluate.ts
  function compare (line 4) | function compare(
  function toNumber (line 14) | function toNumber(a: boolean | number | string): number {
  function toString (line 25) | function toString(a: boolean | number | string): string {
  function reduce (line 38) | function reduce(exp: Expression): Expression {

FILE: lib/common/expression/normalize.ts
  class Indeterminates (line 4) | class Indeterminates {
    method constructor (line 8) | public constructor(exp?: Expression) {
    method reciprocal (line 18) | public reciprocal(): Indeterminates {
    method multiply (line 26) | public static multiply(
    method compare (line 64) | public static compare(a: Indeterminates, b: Indeterminates): number {
  type Term (line 82) | interface Term {
  function findGcd (line 88) | function findGcd(a: bigint, b: bigint): bigint {
  class Polynomial (line 97) | class Polynomial extends Expression {
    method constructor (line 100) | public constructor(terms: Term[]) {
    method map (line 105) | map(): Polynomial {
    method mapAsync (line 109) | async mapAsync(): Promise<Polynomial> {
    method simplifyTerms (line 113) | public static simplifyTerms(terms: Term[]): Term[] {
    method fromIndeterminate (line 148) | public static fromIndeterminate(indeterminate: Expression): Polynomial {
    method fromConstant (line 160) | public static fromConstant(constant: number): Polynomial {
    method negation (line 181) | public negation(): Polynomial {
    method reciprocal (line 191) | public reciprocal(): Polynomial {
    method constant (line 200) | public constant(): Polynomial {
    method add (line 205) | public add(rhs: Polynomial): Polynomial {
    method subtract (line 211) | public subtract(rhs: Polynomial): Polynomial {
    method multiply (line 215) | public multiply(rhs: Polynomial): Polynomial {
    method divide (line 239) | public divide(rhs: Polynomial): Polynomial {
    method toExpression (line 243) | public toExpression(): Expression {
  constant SWAPPED_OPS (line 286) | const SWAPPED_OPS = {
  function cartesianProduct (line 295) | function cartesianProduct<T>(arrays: T[][]): T[][] {
  function toPolynomial (line 302) | function toPolynomial(e: Expression): Polynomial {
  function fromPolynomial (line 314) | function fromPolynomial(e: Expression): Expression {
  function normalizeCallback (line 320) | function normalizeCallback(exp: Expression): Expression {
  function normalize (line 488) | function normalize(exp: Expression): Expression {

FILE: lib/common/expression/pagination.ts
  type Bookmark (line 7) | type Bookmark = Record<string, null | boolean | number | string>;
  type Minterm (line 9) | type Minterm = number[];
  function toBookmark (line 11) | function toBookmark(
  function bookmarkToExpression (line 24) | function bookmarkToExpression(
  function getCover (line 61) | function getCover(
  function paginate (line 124) | function paginate(

FILE: lib/common/expression/parser.ts
  class Cursor (line 4) | class Cursor {
    method constructor (line 11) | constructor(input: string) {
    method fork (line 19) | fork(): Cursor {
    method sync (line 28) | sync(cursor: Cursor): void {
    method read (line 35) | read(cur: Cursor): string {
    method step (line 39) | step(): Cursor {
    method walk (line 47) | walk(callback: (charCode: number) => boolean): Cursor {
    method descend (line 52) | descend(chars: number[], override = true): void {
    method ascend (line 60) | ascend(): void {
    method skipwhitespace (line 66) | skipwhitespace(): Cursor {
  constant CHAR_SINGLE_QUOTE (line 71) | const CHAR_SINGLE_QUOTE = 39;
  constant CHAR_DOUBLE_QUOTE (line 72) | const CHAR_DOUBLE_QUOTE = 34;
  constant CHAR_OPEN_PAREN (line 73) | const CHAR_OPEN_PAREN = 40;
  constant CHAR_CLOSE_PAREN (line 74) | const CHAR_CLOSE_PAREN = 41;
  constant CHAR_COMMA (line 75) | const CHAR_COMMA = 44;
  constant CHAR_PERIOD (line 76) | const CHAR_PERIOD = 46;
  constant CHAR_COLON (line 77) | const CHAR_COLON = 58;
  constant CHAR_OPEN_BRACKET (line 78) | const CHAR_OPEN_BRACKET = 91;
  constant CHAR_BACKSLASH (line 79) | const CHAR_BACKSLASH = 92;
  constant CHAR_CLOSE_BRACKET (line 80) | const CHAR_CLOSE_BRACKET = 93;
  constant BINARY_OPERATORS (line 82) | const BINARY_OPERATORS = [
  constant PRECEDENCE (line 101) | const PRECEDENCE = {
  constant PATH_CHARS (line 127) | const PATH_CHARS = new Set<number>([
  function findOperator (line 138) | function findOperator(cursor: Cursor): string {
  function interpretEscapes (line 166) | function interpretEscapes(str): string {
  function parseExpression (line 185) | function parseExpression(cursor: Cursor, presedence = 0): Expression {
  function parseOldAliasValue (line 317) | function parseOldAliasValue(cursor: Cursor): string {
  function parseOldAlias (line 364) | function parseOldAlias(cursor: Cursor): Expression {
  function parsePath (line 402) | function parsePath(cur: Cursor): Path {
  function stringifyExpression (line 461) | function stringifyExpression(exp: Expression, level = 0): string {
  function parseLikePattern (line 511) | function parseLikePattern(pat: string, esc: string): string[] {
  function likePatternToRegExp (line 529) | function likePatternToRegExp(pat: string, esc = "", flags = ""): RegExp {

FILE: lib/common/expression/synth.ts
  type Minterm (line 6) | type Minterm = number[];
  method getVar (line 15) | public getVar(c: U): number {
  method getClause (line 26) | public getClause(v: number): U {
  method canRaise (line 33) | canRaise(idx: number, set: Set<number>): boolean {
  method canLower (line 38) | canLower(idx: number, set: Set<number>): boolean {
  method bias (line 42) | bias(a: number, b: number): number {
  method sanitizeMinterms (line 47) | sanitizeMinterms(minterms: Minterm[]): Minterm[] {
  method minimize (line 51) | minimize(minterms: Minterm[], dcSet: Minterm[] = []): Minterm[] {
  method expression (line 94) | expression(): Expression {
  method isBoolean (line 102) | isBoolean(): boolean {
  method isNullable (line 105) | isNullable(c: Clause.IsNull): boolean {
  method getNullables (line 113) | *getNullables(): IterableIterator<Clause.IsNull> {
  method toString (line 120) | toString(): string {
  class Not (line 127) | class Not extends Clause {
    method constructor (line 128) | constructor(public operand: Clause) {
    method getMinterms (line 131) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
  class And (line 139) | class And extends Clause {
    method constructor (line 140) | constructor(public operands: Clause[]) {
    method getMinterms (line 143) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
  class IsNull (line 167) | class IsNull extends Clause {
    method constructor (line 168) | constructor(public operand: Clause) {
    method getMinterms (line 171) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
    method isBoolean (line 181) | isBoolean(): boolean {
    method getNullables (line 184) | *getNullables(): IterableIterator<IsNull> {
    method expression (line 187) | expression(): Expression {
  class Exp (line 195) | class Exp extends Clause {
    method constructor (line 196) | constructor(public exp: Expression) {
    method getMinterms (line 199) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
    method expression (line 207) | expression(): Expression {
    method isBoolean (line 210) | isBoolean(): boolean {
  class Compare (line 222) | class Compare extends Clause {
    method constructor (line 223) | constructor(
    method getMinterms (line 230) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
    method getNullables (line 238) | *getNullables(): IterableIterator<IsNull> {
    method isBoolean (line 241) | isBoolean(): boolean {
    method expression (line 244) | expression(): Expression {
  class Like (line 253) | class Like extends Clause {
    method constructor (line 259) | constructor(
    method getMinterms (line 282) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
    method isBoolean (line 290) | isBoolean(): boolean {
    method isNullable (line 293) | isNullable(c: IsNull): boolean {
    method getNullables (line 296) | getNullables(): IterableIterator<IsNull> {
    method expression (line 299) | expression(): Expression {
  class Conditional (line 318) | class Conditional extends Clause {
    method constructor (line 319) | constructor(
    method getMinterms (line 326) | getMinterms(context: SynthContextBase<Clause>, res: number): Minterm[] {
    method expression (line 337) | expression(): Expression {
    method isBoolean (line 393) | isBoolean(): boolean {
  function fromExpression (line 398) | function fromExpression(exp: Expression): Clause {
  function groupBy (line 458) | function groupBy<T, K>(
  class SynthContext (line 473) | class SynthContext extends SynthContextBase<Clause, Clause> {
    method constructor (line 474) | constructor() {
    method getMinterms (line 478) | getMinterms(clause: Clause, res: number): number[][] {
    method getDcSet (line 498) | getDcSet(minterms: Minterm[]): number[][] {
    method canRaise (line 721) | canRaise(idx: number, set: Set<number>): boolean {
    method canLower (line 734) | canLower(idx: number, set: Set<number>): boolean {
    method bias (line 741) | bias(a: number, b: number): number {
    method sanitizeMinterms (line 746) | sanitizeMinterms(minterms: Minterm[]): Minterm[] {
    method toExpression (line 796) | toExpression(sop: number[][]): Expression {
  function createSynthContext (line 857) | function createSynthContext(): SynthContext {
  function likeMatches (line 861) | function likeMatches(
  function getLikePrefixUpperBound (line 903) | function getLikePrefixUpperBound(prefix: string): string | null {
  function getPureLikePrefix (line 916) | function getPureLikePrefix(pattern: string[]): string | null {
  function likeImplies (line 943) | function likeImplies(pat1: string[], pat2: string[]): boolean {
  function likeDisjoint (line 961) | function likeDisjoint(pat1: string[], pat2: string[]): boolean {
  function minimize (line 990) | function minimize(expr: Expression, boolean = false): Expression {
  function unionDiff (line 996) | function unionDiff(
  function covers (line 1029) | function covers(expr1: Expression, expr2: Expression): boolean {
  function areEquivalent (line 1049) | function areEquivalent(expr1: Expression, expr2: Expression): boolean {
  function subtract (line 1088) | function subtract(expr1: Expression, expr2: Expression): Expression {

FILE: lib/common/memoize.ts
  function getKey (line 5) | function getKey(obj): string {
  function memoize (line 23) | function memoize<T extends (...args: any[]) => any>(func: T): T {

FILE: lib/common/path-set.ts
  class PathSet (line 3) | class PathSet {
    method constructor (line 8) | public constructor() {}
    method add (line 10) | public add(pathStr: string): Path {
    method get (line 43) | public get(path: string): Path {
    method findCompat (line 47) | public findCompat(
    method find (line 64) | public find(path: Path, paramMask: number, attrMask: number): Path[] {

FILE: lib/common/path.ts
  type Segments (line 4) | type Segments = (string | Expression)[];
  class Path (line 9) | class Path {
    method constructor (line 17) | constructor(segments: Segments, colon: number) {
    method parse (line 49) | public static parse(input: string): Path {
    method length (line 64) | public get length(): number {
    method paramLength (line 68) | public get paramLength(): number {
    method attrLength (line 72) | public get attrLength(): number {
    method toString (line 76) | public toString(): string {
    method slice (line 80) | public slice(start = 0, end: number = this.segments.length): Path {
    method concat (line 112) | public concat(path2: Path): Path {
    method stripAlias (line 145) | public stripAlias(): Path {

FILE: lib/common/yaml.ts
  constant LINE_WIDTH (line 1) | const LINE_WIDTH = 80;
  constant INDENTATION (line 2) | const INDENTATION = "  ";
  constant STRING_RESERVED (line 4) | const STRING_RESERVED = new Set([
  function isPrintable (line 16) | function isPrintable(str: string): boolean {
  function stringifyKey (line 22) | function stringifyKey(str: string): string {
  function foldString (line 29) | function foldString(str: string): string[] {
  function stringifyString (line 66) | function stringifyString(str: string, res: string[], prefix1, prefix2): ...
  function stringifyAny (line 128) | function stringifyAny(
  function stringify (line 213) | function stringify(obj: unknown): string {

FILE: lib/config.ts
  constant ROOT_DIR (line 5) | let ROOT_DIR = resolve(__dirname, "..");
  function setConfig (line 92) | function setConfig(name, value, commandLineArgument = false): boolean {
  function get (line 240) | function get(
  function getDefault (line 271) | function getDefault(optionName: string): string | number | boolean {

FILE: lib/connection-request.ts
  function extractAuth (line 13) | async function extractAuth(
  function httpGet (line 50) | function httpGet(
  function httpConnectionRequest (line 78) | async function httpConnectionRequest(
  function udpConnectionRequest (line 175) | async function udpConnectionRequest(
  constant XMPP_JID (line 228) | const XMPP_JID = config.get("XMPP_JID") as string;
  constant XMPP_PASSWORD (line 229) | const XMPP_PASSWORD = config.get("XMPP_PASSWORD") as string;
  constant XMPP_RESOURCE (line 230) | const XMPP_RESOURCE = crypto.randomBytes(8).toString("hex");
  function xmppClientOnError (line 234) | function xmppClientOnError(err: Error): void {
  function xmppClientOnClose (line 243) | function xmppClientOnClose(): void {
  function xmppConnectionRequest (line 247) | async function xmppConnectionRequest(

FILE: lib/cwmp.ts
  constant REALM (line 52) | const REALM = "GenieACS";
  constant MAX_CYCLES (line 53) | const MAX_CYCLES = 4;
  constant MAX_CONCURRENT_REQUESTS (line 54) | const MAX_CONCURRENT_REQUESTS = +config.get("MAX_CONCURRENT_REQUESTS");
  constant MAX_SESSION_DURATION (line 56) | const MAX_SESSION_DURATION = 300000;
  constant LOCK_REFRESH_INTERVAL (line 57) | const LOCK_REFRESH_INTERVAL = 10000;
  constant REQUEST_TIMEOUT (line 58) | const REQUEST_TIMEOUT = 10000;
  function authenticate (line 70) | async function authenticate(
  function writeResponse (line 168) | async function writeResponse(
  function recordFault (line 237) | function recordFault(
  function inform (line 304) | async function inform(
  function transferComplete (line 336) | async function transferComplete(sessionContext, rpc): Promise<void> {
  function appendProvisions (line 370) | function appendProvisions(original, toAppend): boolean {
  function applyPresets (line 401) | async function applyPresets(sessionContext: SessionContext): Promise<voi...
  function nextRpc (line 615) | async function nextRpc(sessionContext: SessionContext): Promise<void> {
  function endSession (line 756) | async function endSession(sessionContext: SessionContext): Promise<void> {
  function sendAcsRequest (line 827) | async function sendAcsRequest(
  function onConnection (line 874) | async function onConnection(socket: Socket): Promise<void> {
  function onClientError (line 928) | async function onClientError(err: Error, socket: Socket): Promise<void> {
  function reportBadState (line 966) | async function reportBadState(sessionContext: SessionContext): Promise<v...
  function responseUnauthorized (line 981) | async function responseUnauthorized(
  function processRequest (line 1018) | async function processRequest(
  function listener (line 1258) | async function listener(
  function clientError (line 1273) | async function clientError(
  function decodeString (line 1318) | function decodeString(buffer: Buffer, charset: string): string {
  function listenerAsync (line 1327) | async function listenerAsync(

FILE: lib/cwmp/db.ts
  constant INVALID_PATH_SUFFIX (line 14) | const INVALID_PATH_SUFFIX = "__invalid";
  function compareAccessLists (line 16) | function compareAccessLists(list1: string[], list2: string[]): boolean {
  function fetchDevice (line 22) | async function fetchDevice(
  function saveDevice (line 237) | async function saveDevice(
  function getFaults (line 546) | async function getFaults(
  function saveFault (line 571) | async function saveFault(
  function deleteFault (line 592) | async function deleteFault(
  function getDueTasks (line 599) | async function getDueTasks(
  function clearTasks (line 663) | async function clearTasks(
  function getOperations (line 672) | async function getOperations(
  function saveOperation (line 702) | async function saveOperation(
  function deleteOperation (line 722) | async function deleteOperation(

FILE: lib/cwmp/local-cache.ts
  type Snapshot (line 17) | interface Snapshot {
  function flattenObject (line 25) | function flattenObject<T extends Record<keyof T, unknown>>(
  function fetchPresets (line 39) | async function fetchPresets(): Promise<[string, Preset[]]> {
  function fetchProvisions (line 216) | async function fetchProvisions(): Promise<[string, Provisions]> {
  function fetchVirtualParameters (line 237) | async function fetchVirtualParameters(): Promise<[string, VirtualParamet...
  function fetchFiles (line 258) | async function fetchFiles(): Promise<[string, Files]> {
  function fetchConfig (line 273) | async function fetchConfig(): Promise<[string, Config]> {
  function refresh (line 290) | async function refresh(): Promise<[string, Snapshot]> {
  function getRevision (line 313) | async function getRevision(): Promise<string> {
  function getPresets (line 317) | function getPresets(revision: string): Preset[] {
  function getProvisions (line 321) | function getProvisions(revision: string): Provisions {
  function getVirtualParameters (line 325) | function getVirtualParameters(revision: string): VirtualParameters {
  function getFiles (line 329) | function getFiles(revision: string): Files {
  function getConfig (line 351) | function getConfig(
  function getConfigExpression (line 367) | function getConfigExpression(

FILE: lib/db/db.ts
  function connect (line 27) | async function connect(): Promise<void> {
  function disconnect (line 57) | async function disconnect(): Promise<void> {

FILE: lib/db/synth.ts
  type Minterm (line 15) | type Minterm = number[];
  function getParam (line 17) | function getParam(exp: Expression, collection: string): string {
  function getTypes (line 37) | function getTypes(parameter: string, collection: string): string[] {
  function roundOid (line 112) | function roundOid(oid: string, roundUp: boolean): string {
  function groupBy (line 126) | function groupBy<T, K>(
  method toString (line 144) | toString(): string {
  class MongoClauseArray (line 149) | class MongoClauseArray extends MongoClause {
    method constructor (line 150) | constructor(
    method toQuery (line 157) | toQuery(truthy: boolean): Filter<unknown> {
  class MongoClauseCompare (line 163) | class MongoClauseCompare<T> extends MongoClause {
    method constructor (line 164) | constructor(
    method toQuery (line 173) | toQuery(truthy: boolean): Filter<unknown> {
  class MongoClauseType (line 185) | class MongoClauseType extends MongoClause {
    method constructor (line 186) | constructor(
    method toQuery (line 193) | toQuery(truthy: boolean): Filter<unknown> {
  class MongoClauseLike (line 199) | class MongoClauseLike extends MongoClause {
    method constructor (line 201) | constructor(
    method toQuery (line 211) | toQuery(truthy: boolean): Filter<unknown> {
  class MongoSynthContext (line 251) | class MongoSynthContext extends SynthContextBase<Clause, MongoClause> {
    method constructor (line 252) | constructor(private readonly collection: string) {
    method getMinterms (line 256) | getMinterms(clause: Clause, res: number): number[][] {
    method getDcSet (line 421) | getDcSet(minterms: Minterm[]): number[][] {
    method canRaise (line 569) | canRaise(i: number, s: Set<number>): boolean {
    method toQuery (line 584) | toQuery(minterms: Minterm[]): Filter<unknown> {
  function toMongoQuery (line 643) | function toMongoQuery(
  function validQuery (line 656) | function validQuery(exp: Expression, resource: string): void {

FILE: lib/db/types.ts
  type Fault (line 5) | interface Fault {
  type TaskBase (line 24) | interface TaskBase {
  type View (line 32) | interface View {
  type TaskGetParameterValues (line 37) | interface TaskGetParameterValues extends TaskBase {
  type TaskSetParameterValues (line 42) | interface TaskSetParameterValues extends TaskBase {
  type TaskRefreshObject (line 47) | interface TaskRefreshObject extends TaskBase {
  type TaskReboot (line 52) | interface TaskReboot extends TaskBase {
  type TaskFactoryReset (line 56) | interface TaskFactoryReset extends TaskBase {
  type TaskDownload (line 60) | interface TaskDownload extends TaskBase {
  type TaskAddObject (line 67) | interface TaskAddObject extends TaskBase {
  type TaskDeleteObject (line 73) | interface TaskDeleteObject extends TaskBase {
  type TaskProvisions (line 78) | interface TaskProvisions extends TaskBase {
  type Task (line 83) | type Task =
  type Operation (line 94) | interface Operation {
  type Config (line 104) | interface Config {
  type Cache (line 109) | interface Cache {
  type Device (line 116) | interface Device {
  type Configuration (line 124) | type Configuration =
  type Preset (line 133) | interface Preset {
  type Object (line 141) | interface Object {
  type Provision (line 145) | interface Provision {
  type VirtualParameter (line 150) | interface VirtualParameter {
  type File (line 155) | interface File {
  type Permission (line 168) | interface Permission {
  type User (line 177) | interface User {
  type Lock (line 184) | interface Lock {

FILE: lib/db/util.ts
  function optimizeProjection (line 7) | function optimizeProjection(obj: { [path: string]: 1 }): {
  function convertOldPrecondition (line 28) | function convertOldPrecondition(q: Record<string, unknown>): Expression {

FILE: lib/debug.ts
  constant DEBUG_FILE (line 8) | const DEBUG_FILE = "" + config.get("DEBUG_FILE");
  constant DEBUG_FORMAT (line 9) | const DEBUG_FORMAT = "" + config.get("DEBUG_FORMAT");
  function getConnectionTimestamp (line 13) | function getConnectionTimestamp(connection: Socket): Date {
  function incomingHttpRequest (line 22) | function incomingHttpRequest(
  function outgoingHttpResponse (line 51) | function outgoingHttpResponse(
  function outgoingHttpRequest (line 78) | function outgoingHttpRequest(
  function outgoingHttpRequestError (line 108) | function outgoingHttpRequestError(
  function incomingHttpResponse (line 137) | function incomingHttpResponse(
  function outgoingUdpMessage (line 163) | function outgoingUdpMessage(
  function clientError (line 187) | function clientError(remoteAddress: string, err: Error): void {
  function outgoingXmppStanza (line 204) | function outgoingXmppStanza(deviceId: string, body: string): void {
  function incomingXmppStanza (line 221) | function incomingXmppStanza(deviceId: string, body: string): void {

FILE: lib/default-provisions.ts
  constant MAX_DEPTH (line 7) | const MAX_DEPTH = +config.get("MAX_DEPTH");
  function refresh (line 9) | function refresh(
  function value (line 65) | function value(
  function tag (line 108) | function tag(
  function reboot (line 132) | function reboot(
  function reset (line 151) | function reset(
  function download (line 170) | function download(
  function instances (line 213) | function instances(

FILE: lib/device.ts
  constant CHANGE_FLAGS (line 11) | const CHANGE_FLAGS = {
  function parseBool (line 19) | function parseBool(v): boolean {
  function sanitizeParameterValue (line 27) | function sanitizeParameterValue(
  function getAliasDeclarations (line 69) | function getAliasDeclarations(
  function expressionToAlias (line 104) | function expressionToAlias(exp: Expression): [Path, Value][] {
  function unpack (line 120) | function unpack(
  function clear (line 192) | function clear(
  function compareEquality (line 257) | function compareEquality(a, b): boolean {
  function set (line 272) | function set(
  function track (line 386) | function track(
  function clearTrackers (line 407) | function clearTrackers(

FILE: lib/extensions.ts
  constant TIMEOUT (line 9) | const TIMEOUT = +config.get("EXT_TIMEOUT");
  function run (line 14) | function run(args: string[]): Promise<{ fault: Fault; value: any }> {
  function kill (line 83) | function kill(process: ChildProcess): Promise<void> {
  function killAll (line 102) | async function killAll(): Promise<void> {

FILE: lib/forwarded.ts
  type RequestOrigin (line 7) | interface RequestOrigin {
  constant FORWARDED_HEADER (line 16) | const FORWARDED_HEADER = "" + config.get("FORWARDED_HEADER");
  function parseForwardedHeader (line 34) | function parseForwardedHeader(str: string): { [name: string]: string } {
  function getRequestOrigin (line 79) | function getRequestOrigin(request: IncomingMessage): RequestOrigin {

FILE: lib/fs.ts
  function generateETag (line 57) | function generateETag(file: {
  function matchEtag (line 67) | function matchEtag(etag: string, header: string): boolean {
  function listener (line 82) | async function listener(

FILE: lib/gpn-heuristic.ts
  constant WILDCARD_MULTIPLIER (line 3) | const WILDCARD_MULTIPLIER = 2;
  constant UNDISCOVERED_DEPTH (line 4) | const UNDISCOVERED_DEPTH = 7;
  function estimateGpnCount (line 13) | function estimateGpnCount(

FILE: lib/init.ts
  type Status (line 28) | interface Status {
  function getStatus (line 37) | async function getStatus(): Promise<Status> {
  function seed (line 64) | async function seed(options: Record<string, boolean>): Promise<void> {

FILE: lib/instance-set.ts
  type Instance (line 1) | interface Instance {
  class InstanceSet (line 5) | class InstanceSet {
    method constructor (line 8) | public constructor() {
    method add (line 12) | public add(instance: Instance): void {
    method delete (line 16) | public delete(instance: Instance): void {
    method superset (line 20) | public superset(instance: Instance): Instance[] {
    method subset (line 56) | public subset(instance: Instance): Instance[] {
    method forEach (line 97) | public forEach(callback: (instance: Instance) => void): void {
    method values (line 101) | public values(): IterableIterator<Instance> {
    method clear (line 105) | public clear(): void {
    method size (line 109) | public get size(): number {
  method [Symbol.iterator] (line 93) | public [Symbol.iterator](): IterableIterator<Instance> {

FILE: lib/local-cache.ts
  constant REFRESH (line 5) | const REFRESH = 5000;
  constant EVICT_TIMEOUT (line 6) | const EVICT_TIMEOUT = 120000;
  class LocalCache (line 8) | class LocalCache<T> {
    method constructor (line 13) | constructor(
    method getRevision (line 18) | async getRevision(): Promise<string> {
    method hasRevision (line 23) | hasRevision(revision: string): boolean {
    method get (line 27) | get(revision: string): T {
    method refresh (line 33) | async refresh(): Promise<void> {

FILE: lib/lock.ts
  constant CLOCK_SKEW_TOLERANCE (line 3) | const CLOCK_SKEW_TOLERANCE = 30000;
  function acquireLock (line 5) | async function acquireLock(
  function releaseLock (line 36) | async function releaseLock(
  function getToken (line 47) | async function getToken(lockName: string): Promise<string> {

FILE: lib/logger.ts
  constant REOPEN_EVERY (line 14) | const REOPEN_EVERY = 60000;
  constant LOG_FORMAT (line 16) | const LOG_FORMAT = config.get("LOG_FORMAT");
  constant ACCESS_LOG_FORMAT (line 17) | const ACCESS_LOG_FORMAT = config.get("ACCESS_LOG_FORMAT") || LOG_FORMAT;
  constant LOG_SYSTEMD (line 21) | let LOG_SYSTEMD = false;
  constant ACCESS_LOG_SYSTEMD (line 22) | let ACCESS_LOG_SYSTEMD = false;
  constant LOG_FILE (line 24) | let LOG_FILE, ACCESS_LOG_FILE;
  constant ACCESS_LOG_FILE (line 24) | let LOG_FILE, ACCESS_LOG_FILE;
  type WritableStream (line 29) | interface WritableStream {
  type WriteStream (line 36) | interface WriteStream {
  function reopen (line 47) | function reopen(): void {
  function init (line 96) | function init(service: string, version: string): void {
  function close (line 133) | function close(): void {
  function flatten (line 138) | function flatten(
  function formatJson (line 216) | function formatJson(
  function formatSimple (line 232) | function formatSimple(
  function log (line 280) | function log(details: Record<string, unknown>): void {
  function info (line 290) | function info(details: Record<string, unknown>): void {
  function warn (line 295) | function warn(details: Record<string, unknown>): void {
  function error (line 300) | function error(details: Record<string, unknown>): void {
  function accessLog (line 305) | function accessLog(details: Record<string, unknown>): void {
  function accessInfo (line 315) | function accessInfo(details: Record<string, unknown>): void {
  function accessWarn (line 320) | function accessWarn(details: Record<string, unknown>): void {
  function accessError (line 325) | function accessError(details: Record<string, unknown>): void {

FILE: lib/nbi.ts
  constant DEVICE_TASKS_REGEX (line 19) | const DEVICE_TASKS_REGEX = /^\/devices\/([a-zA-Z0-9\-_%]+)\/tasks\/?$/;
  constant TASKS_REGEX (line 20) | const TASKS_REGEX = /^\/tasks\/([a-zA-Z0-9\-_%]+)(\/[a-zA-Z_]*)?$/;
  constant TAGS_REGEX (line 21) | const TAGS_REGEX =
  constant PRESETS_REGEX (line 23) | const PRESETS_REGEX = /^\/presets\/([a-zA-Z0-9\-_%]+)\/?$/;
  constant OBJECTS_REGEX (line 24) | const OBJECTS_REGEX = /^\/objects\/([a-zA-Z0-9\-_%]+)\/?$/;
  constant FILES_REGEX (line 25) | const FILES_REGEX = /^\/files\/([a-zA-Z0-9%!*'();:@&=+$,?#[\]\-_.~]+)\/?$/;
  constant PING_REGEX (line 26) | const PING_REGEX = /^\/ping\/([a-zA-Z0-9\-_.:]+)\/?$/;
  constant QUERY_REGEX (line 27) | const QUERY_REGEX = /^\/([a-zA-Z0-9_]+)\/?$/;
  constant DELETE_DEVICE_REGEX (line 28) | const DELETE_DEVICE_REGEX = /^\/devices\/([a-zA-Z0-9\-_%]+)\/?$/;
  constant PROVISIONS_REGEX (line 29) | const PROVISIONS_REGEX = /^\/provisions\/([a-zA-Z0-9\-_%]+)\/?$/;
  constant VIRTUAL_PARAMETERS_REGEX (line 30) | const VIRTUAL_PARAMETERS_REGEX =
  constant FAULTS_REGEX (line 32) | const FAULTS_REGEX = /^\/faults\/([a-zA-Z0-9\-_%:]+)\/?$/;
  function getBody (line 34) | async function getBody(request: IncomingMessage): Promise<Buffer> {
  function listener (line 48) | async function listener(
  function handler (line 73) | async function handler(

FILE: lib/ping.ts
  type PingResult (line 5) | interface PingResult {
  function isValidHost (line 15) | function isValidHost(host: string): boolean {
  function parsePing (line 24) | function parsePing(osPlatform: string, stdout: string): PingResult {
  function ping (line 70) | function ping(

FILE: lib/query.ts
  function isObject (line 1) | function isObject(obj: any): boolean {
  function stringToRegexp (line 5) | function stringToRegexp(input, flags?): RegExp | false {
  function normalize (line 19) | function normalize(input): any {
  constant EXPAND_OPS (line 38) | const EXPAND_OPS = new Set([
  function expandValue (line 49) | function expandValue(value: unknown): unknown[] {
  function permute (line 86) | function permute(param, val): any[] {
  function expand (line 101) | function expand(
  function sanitizeQueryTypes (line 129) | function sanitizeQueryTypes(

FILE: lib/sandbox.ts
  constant COMMIT (line 11) | const COMMIT = Symbol();
  constant EXT (line 14) | const EXT = Symbol();
  constant UNDEFINED (line 16) | const UNDEFINED = undefined;
  function runExtension (line 26) | function runExtension(sessionContext, key, extCall): Promise<Fault> {
  class SandboxDate (line 53) | class SandboxDate {
    method constructor (line 54) | public constructor(
    method now (line 70) | public static now(intervalOrCron, variance): number {
    method parse (line 94) | public static parse(dateString: string): number {
    method UTC (line 98) | public static UTC(
  function random (line 105) | function random(): number {
  class ParameterWrapper (line 115) | class ParameterWrapper {
    method constructor (line 116) | public constructor(path: Path, attributes, unpacked?, unpackedRevision...
  function declare (line 201) | function declare(
  function clear (line 254) | function clear(path: string, timestamp: number, attributes?): void {
  function commit (line 261) | function commit(): void {
  function ext (line 275) | function ext(...args: unknown[]): any {
  function log (line 287) | function log(msg: string, meta: Record<string, unknown>): void {
  function errorToFault (line 317) | function errorToFault(err: Error): Fault {
  function run (line 348) | async function run(

FILE: lib/scheduling.ts
  function md532 (line 4) | function md532(str): number {
  function variance (line 14) | function variance(deviceId: string, vrnc: number): number {
  function interval (line 18) | function interval(
  function parseCron (line 26) | function parseCron(cronExp: string): any {
  function cron (line 33) | function cron(

FILE: lib/server.ts
  function closeServer (line 12) | function closeServer(timeout, callback): void {
  type ServerOptions (line 37) | interface ServerOptions {
  type SocketEndpoint (line 48) | interface SocketEndpoint {
  type Promisify (line 59) | type Promisify<T extends (...args: any) => any> = (
  function getValidPrivKeys (line 63) | function getValidPrivKeys(value: string): Buffer[] {
  function getValidCerts (line 73) | function getValidCerts(value: string): Buffer[] {
  function start (line 83) | function start(
  function stop (line 147) | function stop(terminateConnections = true): Promise<void> {
  function getSocketEndpoints (line 157) | function getSocketEndpoints(socket: Socket): SocketEndpoint {

FILE: lib/session.ts
  constant VALID_PARAM_TYPES (line 46) | const VALID_PARAM_TYPES = new Set([
  function initDeviceData (line 56) | function initDeviceData(): DeviceData {
  function init (line 66) | function init(
  function generateRpcId (line 94) | function generateRpcId(sessionContext: SessionContext): string {
  function configContextCallback (line 102) | function configContextCallback(
  function inform (line 126) | async function inform(
  function transferComplete (line 255) | async function transferComplete(
  function revertDownloadParameters (line 360) | function revertDownloadParameters(
  function timeoutOperations (line 388) | async function timeoutOperations(
  function addProvisions (line 460) | function addProvisions(
  function clearProvisions (line 518) | function clearProvisions(sessionContext: SessionContext): void {
  function runProvisions (line 551) | async function runProvisions(
  function runVirtualParameters (line 630) | async function runVirtualParameters(
  function runDeclarations (line 747) | function runDeclarations(
  function rpcRequest (line 977) | async function rpcRequest(
  function generateGetRpcRequest (line 1493) | function generateGetRpcRequest(
  function compareAccessLists (line 1716) | function compareAccessLists(list1: string[], list2: string[]): boolean {
  function generateSetRpcRequest (line 1722) | function generateSetRpcRequest(
  function generateGetVirtualParameterProvisions (line 1922) | function generateGetVirtualParameterProvisions(
  function generateSetVirtualParameterProvisions (line 1968) | function generateSetVirtualParameterProvisions(
  function processDeclarations (line 2023) | function processDeclarations(
  function processInstances (line 2330) | function processInstances(
  function rpcResponse (line 2391) | async function rpcResponse(
  function rpcFault (line 2870) | async function rpcFault(
  function deserialize (line 2933) | async function deserialize(
  function serialize (line 2960) | async function serialize(

FILE: lib/soap.ts
  constant SERVER_NAME (line 35) | const SERVER_NAME = `GenieACS/${VERSION}`;
  constant NAMESPACES (line 37) | const NAMESPACES = {
  function parseBool (line 79) | function parseBool(v: string): boolean {
  function event (line 85) | function event(xml: Element): string[] {
  function parameterInfoList (line 91) | function parameterInfoList(xml: Element): [Path, boolean, boolean][] {
  function parameterValueList (line 141) | function parameterValueList(
  function parameterAttributeList (line 216) | function parameterAttributeList(xml: Element): [Path, number, string[]][] {
  function GetParameterNames (line 265) | function GetParameterNames(methodRequest): string {
  function GetParameterNamesResponse (line 271) | function GetParameterNamesResponse(xml): GetParameterNamesResponse {
  function GetParameterValues (line 280) | function GetParameterValues(methodRequest): string {
  function GetParameterValuesResponse (line 288) | function GetParameterValuesResponse(xml: Element): GetParameterValuesRes...
  function GetParameterAttributes (line 297) | function GetParameterAttributes(methodRequest): string {
  function GetParameterAttributesResponse (line 305) | function GetParameterAttributesResponse(
  function SetParameterValues (line 316) | function SetParameterValues(methodRequest): string {
  function SetParameterValuesResponse (line 338) | function SetParameterValuesResponse(xml: Element): SetParameterValuesRes...
  function SetParameterAttributes (line 363) | function SetParameterAttributes(methodRequest): string {
  function SetParameterAttributesResponse (line 387) | function SetParameterAttributesResponse(): SetParameterAttributesResponse {
  function AddObject (line 393) | function AddObject(methodRequest): string {
  function AddObjectResponse (line 401) | function AddObjectResponse(xml: Element): AddObjectResponse {
  function DeleteObject (line 432) | function DeleteObject(methodRequest): string {
  function DeleteObjectResponse (line 440) | function DeleteObjectResponse(xml: Element): DeleteObjectResponse {
  function Reboot (line 465) | function Reboot(methodRequest): string {
  function RebootResponse (line 471) | function RebootResponse(): RebootResponse {
  function FactoryReset (line 477) | function FactoryReset(): string {
  function FactoryResetResponse (line 481) | function FactoryResetResponse(): FactoryResetResponse {
  function Download (line 487) | function Download(methodRequest): string {
  function DownloadResponse (line 509) | function DownloadResponse(xml: Element): DownloadResponse {
  function Inform (line 557) | function Inform(xml: Element): InformRequest {
  function InformResponse (line 620) | function InformResponse(): string {
  function GetRPCMethods (line 624) | function GetRPCMethods(): GetRPCMethodsRequest {
  function GetRPCMethodsResponse (line 628) | function GetRPCMethodsResponse(methodResponse): string {
  function TransferComplete (line 636) | function TransferComplete(xml: Element): TransferCompleteRequest {
  function TransferCompleteResponse (line 699) | function TransferCompleteResponse(): string {
  function RequestDownload (line 703) | function RequestDownload(xml: Element): RequestDownloadRequest {
  function RequestDownloadResponse (line 710) | function RequestDownloadResponse(): string {
  function AcsFault (line 714) | function AcsFault(f: CpeFault): string {
  function faultStruct (line 726) | function faultStruct(xml: Element): FaultStruct {
  function fault (line 784) | function fault(xml: Element): CpeFault {
  function request (line 821) | function request(
  function response (line 981) | function response(rpc: {

FILE: lib/types.ts
  type Fault (line 9) | interface Fault {
  type SessionFault (line 22) | interface SessionFault extends Fault {
  type Attributes (line 31) | interface Attributes {
  type AttributeTimestamps (line 39) | interface AttributeTimestamps {
  type AttributeValues (line 47) | interface AttributeValues {
  type DeviceData (line 55) | interface DeviceData {
  type VirtualParameterDeclaration (line 63) | type VirtualParameterDeclaration = [
  type SyncState (line 83) | interface SyncState {
  type SessionContext (line 108) | interface SessionContext {
  type Task (line 152) | interface Task {
  type Operation (line 165) | interface Operation {
  type AcsRequest (line 179) | type AcsRequest =
  type GetParameterNames (line 191) | interface GetParameterNames {
  type GetParameterValues (line 197) | interface GetParameterValues {
  type GetParameterAttributes (line 202) | interface GetParameterAttributes {
  type SetParameterValues (line 207) | interface SetParameterValues {
  type SetParameterAttributes (line 215) | interface SetParameterAttributes {
  type AddObject (line 220) | interface AddObject {
  type DeleteObject (line 227) | interface DeleteObject {
  type FactoryReset (line 233) | interface FactoryReset {
  type Reboot (line 238) | interface Reboot {
  type Download (line 243) | interface Download {
  type SpvFault (line 259) | interface SpvFault {
  type FaultStruct (line 265) | interface FaultStruct {
  type CpeFault (line 271) | interface CpeFault {
  type CpeResponse (line 277) | type CpeResponse =
  type GetParameterNamesResponse (line 289) | interface GetParameterNamesResponse {
  type GetParameterValuesResponse (line 294) | interface GetParameterValuesResponse {
  type GetParameterAttributesResponse (line 299) | interface GetParameterAttributesResponse {
  type SetParameterValuesResponse (line 304) | interface SetParameterValuesResponse {
  type SetParameterAttributesResponse (line 309) | interface SetParameterAttributesResponse {
  type AddObjectResponse (line 313) | interface AddObjectResponse {
  type DeleteObjectResponse (line 319) | interface DeleteObjectResponse {
  type RebootResponse (line 324) | interface RebootResponse {
  type FactoryResetResponse (line 328) | interface FactoryResetResponse {
  type DownloadResponse (line 332) | interface DownloadResponse {
  type CpeRequest (line 339) | type CpeRequest =
  type InformRequest (line 345) | interface InformRequest {
  type TransferCompleteRequest (line 358) | interface TransferCompleteRequest {
  type GetRPCMethodsRequest (line 366) | interface GetRPCMethodsRequest {
  type RequestDownloadRequest (line 370) | interface RequestDownloadRequest {
  type AcsResponse (line 375) | type AcsResponse =
  type InformResponse (line 381) | interface InformResponse {
  type GetRPCMethodsResponse (line 385) | interface GetRPCMethodsResponse {
  type TransferCompleteResponse (line 390) | interface TransferCompleteResponse {
  type RequestDownloadResponse (line 394) | interface RequestDownloadResponse {
  type QueryOptions (line 398) | interface QueryOptions {
  type Declaration (line 407) | interface Declaration {
  type Clear (line 428) | type Clear = [
  type Preset (line 441) | interface Preset {
  type Provisions (line 450) | interface Provisions {
  type VirtualParameters (line 454) | interface VirtualParameters {
  type Views (line 458) | interface Views {
  type Files (line 462) | interface Files {
  type Users (line 466) | interface Users {
  type Permissions (line 470) | interface Permissions {
  type PermissionSet (line 482) | type PermissionSet = {
  type Config (line 490) | interface Config {
  type UiConfig (line 494) | type UiConfig = Record<string, string>;
  type SoapMessage (line 496) | interface SoapMessage {
  type ScriptResult (line 506) | interface ScriptResult {

FILE: lib/ui.ts
  constant JWT_SECRET (line 24) | const JWT_SECRET = "" + config.get("UI_JWT_SECRET");
  constant JWT_COOKIE (line 25) | const JWT_COOKIE = "genieacs-ui-jwt";
  function success (line 119) | function success(authMethod): void {
  function failure (line 133) | function failure(): void {

FILE: lib/ui/api.ts
  function logUnauthorizedWarning (line 24) | function logUnauthorizedWarning(log): void {
  constant RESOURCE_DELETE (line 29) | const RESOURCE_DELETE = 1 << 0;
  constant RESOURCE_PUT (line 30) | const RESOURCE_PUT = 1 << 1;
  constant RESOURCE_IDS (line 32) | const RESOURCE_IDS = {
  function singleParam (line 60) | function singleParam(p: string | string[]): string {
  function flushRow (line 104) | function flushRow(): void {

FILE: lib/ui/db.ts
  function processDeviceProjection (line 13) | function processDeviceProjection(
  function processDeviceSort (line 41) | function processDeviceSort(
  function parseDate (line 59) | function parseDate(d: Date): number | string {
  type FlatDevice (line 64) | interface FlatDevice {
  function flattenDevice (line 68) | function flattenDevice(device: Record<string, unknown>): FlatDevice {
  function flattenFault (line 162) | function flattenFault(fault: unknown): Fault {
  function flattenTask (line 169) | function flattenTask(task: unknown): Task {
  function flattenPreset (line 177) | function flattenPreset(
  function flattenFile (line 216) | function flattenFile(file: Record<string, unknown>): Record<string, unkn...
  function preProcessPreset (line 228) | function preProcessPreset(data: Record<string, unknown>): MongoTypes.Pre...
  type QueryOptions (line 268) | interface QueryOptions {
  function count (line 334) | function count(resource: string, filter: Expression): Promise<number> {
  function updateDeviceTags (line 348) | async function updateDeviceTags(
  function putPreset (line 368) | async function putPreset(
  function deletePreset (line 376) | async function deletePreset(id: string): Promise<void> {
  function putProvision (line 380) | async function putProvision(
  function deleteProvision (line 403) | async function deleteProvision(id: string): Promise<void> {
  function putVirtualParameter (line 407) | async function putVirtualParameter(
  function deleteVirtualParameter (line 430) | async function deleteVirtualParameter(id: string): Promise<void> {
  function putConfig (line 434) | async function putConfig(
  function deleteConfig (line 441) | async function deleteConfig(id: string): Promise<void> {
  function putPermission (line 445) | async function putPermission(
  function deletePermission (line 454) | async function deletePermission(id: string): Promise<void> {
  function putUser (line 458) | async function putUser(
  function deleteUser (line 470) | async function deleteUser(id: string): Promise<void> {
  function downloadFile (line 474) | function downloadFile(filename: string): Readable {
  function putFile (line 478) | function putFile(
  function deleteFile (line 514) | async function deleteFile(filename: string): Promise<void> {
  function deleteFault (line 518) | async function deleteFault(id: string): Promise<void> {
  function deleteTask (line 522) | async function deleteTask(id: ObjectId): Promise<void> {
  function putView (line 526) | async function putView(
  function deleteView (line 538) | async function deleteView(id: string): Promise<void> {

FILE: lib/ui/local-cache.ts
  type Snapshot (line 8) | interface Snapshot {
  function fetchPermissions (line 16) | async function fetchPermissions(): Promise<[string, Permissions]> {
  function fetchUsers (line 42) | async function fetchUsers(): Promise<[string, Users]> {
  function fetchConfig (line 62) | async function fetchConfig(): Promise<[string, Config, UiConfig]> {
  function fetchViews (line 84) | async function fetchViews(): Promise<[string, Views]> {
  function refresh (line 99) | async function refresh(): Promise<[string, Snapshot]> {
  function getRevision (line 121) | async function getRevision(): Promise<string> {
  function getConfig (line 143) | function getConfig(
  function getConfigExpression (line 159) | function getConfigExpression(revision: string, key: string): Expression {
  function getUsers (line 164) | function getUsers(revision: string): Users {
  function getPermissions (line 169) | function getPermissions(revision: string): Permissions {
  function getUiConfig (line 174) | function getUiConfig(revision: string): UiConfig {
  function getViewsBundle (line 179) | function getViewsBundle(revision: string): string {

FILE: lib/util.ts
  function generateDeviceId (line 3) | function generateDeviceId(
  function escapeRegExp (line 30) | function escapeRegExp(str: string): string {
  function encodeTag (line 34) | function encodeTag(tag: string): string {
  function decodeTag (line 44) | function decodeTag(tag: string): string {
  function once (line 48) | function once(
  function setTimeoutPromise (line 65) | function setTimeoutPromise(delay: number, ref = true): Promise<void> {

FILE: lib/versioned-map.ts
  constant NONEXISTENT (line 1) | const NONEXISTENT = Symbol();
  constant UNDEFINED (line 2) | const UNDEFINED = undefined;
  type Revisions (line 4) | interface Revisions<V> {
  class VersionedMap (line 9) | class VersionedMap<K, V> {
    method constructor (line 15) | public constructor() {
    method size (line 22) | public get size(): number {
    method revision (line 26) | public get revision(): number {
    method revision (line 30) | public set revision(rev: number) {
    method get (line 37) | public get(key: K, rev = this._revision): V {
    method has (line 46) | public has(key: K, rev = this._revision): boolean {
    method set (line 55) | public set(key: K, value: V, rev = this._revision): this {
    method delete (line 82) | public delete(key: K, rev = this._revision): boolean {
    method getRevisions (line 101) | public getRevisions(key: K): Revisions<V> {
    method setRevisions (line 120) | public setRevisions(key: K, revisionsObj: Revisions<V>): void {
    method getDiff (line 144) | public getDiff(key: K): [V, V] {
    method diff (line 154) | public *diff(): IterableIterator<[K, V, V]> {
    method collapse (line 166) | public collapse(revision: number): void {
  method [Symbol.iterator] (line 187) | public *[Symbol.iterator](): IterableIterator<[K, V]> {

FILE: lib/xml-parser.ts
  constant CHAR_SINGLE_QUOTE (line 1) | const CHAR_SINGLE_QUOTE = 39;
  constant CHAR_DOUBLE_QUOTE (line 2) | const CHAR_DOUBLE_QUOTE = 34;
  constant CHAR_LESS_THAN (line 3) | const CHAR_LESS_THAN = 60;
  constant CHAR_GREATER_THAN (line 4) | const CHAR_GREATER_THAN = 62;
  constant CHAR_COLON (line 5) | const CHAR_COLON = 58;
  constant CHAR_SPACE (line 6) | const CHAR_SPACE = 32;
  constant CHAR_TAB (line 7) | const CHAR_TAB = 9;
  constant CHAR_CR (line 8) | const CHAR_CR = 13;
  constant CHAR_LF (line 9) | const CHAR_LF = 10;
  constant CHAR_SLASH (line 10) | const CHAR_SLASH = 47;
  constant CHAR_EXMARK (line 11) | const CHAR_EXMARK = 33;
  constant CHAR_QMARK (line 12) | const CHAR_QMARK = 63;
  constant CHAR_EQUAL (line 13) | const CHAR_EQUAL = 61;
  constant STATE_LESS_THAN (line 15) | const STATE_LESS_THAN = 1;
  constant STATE_SINGLE_QUOTE (line 16) | const STATE_SINGLE_QUOTE = 2;
  constant STATE_DOUBLE_QUOTE (line 17) | const STATE_DOUBLE_QUOTE = 3;
  type Attribute (line 19) | interface Attribute {
  type Element (line 26) | interface Element {
  function parseXmlDeclaration (line 36) | function parseXmlDeclaration(buffer: Buffer): Attribute[] {
  function parseAttrs (line 52) | function parseAttrs(string: string): Attribute[] {
  function decodeEntities (line 115) | function decodeEntities(string: string): string {
  function encodeEntities (line 148) | function encodeEntities(string: string): string {
  function parseXml (line 159) | function parseXml(string: string): Element {

FILE: lib/xmpp-client.ts
  function encodeBase64 (line 7) | function encodeBase64(str: string): string {
  function decodeBase64 (line 11) | function decodeBase64(str: string): string {
  function detectStreamTag (line 15) | function detectStreamTag(data: string): number {
  function xmppStream (line 23) | function xmppStream<T>(
  constant INT_1 (line 78) | const INT_1 = Buffer.from([0, 0, 0, 1]);
  function saltPassword (line 86) | function saltPassword(
  constant STATUS_RESTART_STREAM (line 240) | const STATUS_RESTART_STREAM = 1;
  constant STATUS_STARTTLS (line 241) | const STATUS_STARTTLS = 2;
  function upgradeTls (line 286) | function upgradeTls(socket: net.Socket, host: string): Promise<tls.TLSSo...
  type XmppClientOptions (line 296) | interface XmppClientOptions {
  class XmppClient (line 305) | class XmppClient extends EventEmitter {
    method constructor (line 315) | private constructor() {
    method connect (line 324) | static async connect(opts: XmppClientOptions): Promise<XmppClient> {
    method close (line 364) | close(): void {
    method ref (line 371) | ref(): void {
    method unref (line 375) | unref(): void {
    method host (line 379) | get host(): string {
    method username (line 383) | get username(): string {
    method resource (line 387) | get resource(): string {
    method _onData (line 391) | private _onData(chunk: Buffer): void {
    method _onError (line 425) | private _onError(err: Error): void {
    method send (line 431) | send(msg: string): void {
    method sendIqStanza (line 435) | sendIqStanza(

FILE: seed/device-page-tr098.jsx
  constant FIVE_MINUTES (line 97) | const FIVE_MINUTES = 5 * 60 * 1000;
  constant ONE_DAY (line 98) | const ONE_DAY = 24 * 60 * 60 * 1000;

FILE: seed/device-page-tr181.jsx
  constant FIVE_MINUTES (line 93) | const FIVE_MINUTES = 5 * 60 * 1000;
  constant ONE_DAY (line 94) | const ONE_DAY = 24 * 60 * 60 * 1000;

FILE: seed/overview-page.jsx
  constant FIVE_MINUTES (line 6) | const FIVE_MINUTES = 5 * 60 * 1000;
  constant ONE_DAY (line 7) | const ONE_DAY = 24 * 60 * 60 * 1000;

FILE: seed/provisions.d.ts
  type Timestamps (line 1) | interface Timestamps {
  type Values (line 10) | interface Values {
  type ParameterWrapper (line 19) | interface ParameterWrapper extends Iterable<ParameterWrapper> {
  type DateConstructor (line 49) | interface DateConstructor {

FILE: seed/views.d.ts
  type Signal (line 1) | interface Signal<T = any> {
  type StateSignal (line 5) | interface StateSignal<T = any> extends Signal<T> {
  type ComputedSignal (line 10) | interface ComputedSignal<T = any> extends Signal<T> {}
  type ConstSignal (line 13) | interface ConstSignal<T = any> extends Signal<T> {}
  type SignalConstructors (line 15) | interface SignalConstructors {
  type ViewElement (line 23) | type ViewElement = ViewNode | string | number | Signal | ViewElement[];
  class ViewNode (line 25) | class ViewNode {
  type SignalizedViewNode (line 31) | interface SignalizedViewNode {

FILE: test/mocks/store.ts
  function getClockSkew (line 13) | function getClockSkew(): number {
  type MockHandler (line 18) | type MockHandler = (options: XhrRequestOptions) => unknown | Promise<unk...
  type RequestRecord (line 24) | interface RequestRecord {
  type XhrRequestOptions (line 32) | interface XhrRequestOptions {
  type MockXhr (line 42) | interface MockXhr {
  function parseQueryParams (line 48) | function parseQueryParams(url: string): Record<string, string> {
  function evaluate (line 63) | function evaluate(
  function filterData (line 83) | function filterData(data: unknown[], filterStr: string | undefined): unk...
  function xhrRequest (line 96) | async function xhrRequest(options: XhrRequestOptions): Promise<unknown> {
  function mockRegisterHandler (line 131) | function mockRegisterHandler(handler: MockHandler): void {
  function mockClearHandlers (line 135) | function mockClearHandlers(): void {
  function mockGetRequestLog (line 140) | function mockGetRequestLog(): RequestRecord[] {
  function mockClearRequestLog (line 144) | function mockClearRequestLog(): void {
  function mockUrlHandler (line 148) | function mockUrlHandler(
  function mockCountHandler (line 165) | function mockCountHandler(
  function mockFetchHandler (line 203) | function mockFetchHandler(

FILE: test/pagination.ts
  constant VALUES (line 12) | const VALUES = [null, -1, false, "a"];
  constant PARAMS (line 13) | const PARAMS = ["param1", "param2"];
  function query (line 17) | async function query(filter: string): Promise<{ id: string }[]> {
  function getAllSortOrders (line 46) | function getAllSortOrders(columns: string[]): Array<Record<string, numbe...
  function testPaginate (line 72) | async function testPaginate(

FILE: test/reactive-store.ts
  type FetchedRegion (line 44) | interface FetchedRegion {
  type ResourceCache (line 49) | interface ResourceCache {
  function getCacheState (line 56) | function getCacheState(resource: string): {
  function clearStores (line 89) | function clearStores(): void {
  function forcePruneCache (line 93) | function forcePruneCache(resource: string): void {

FILE: test/signals.ts
  class Counter (line 84) | class Counter extends StateSignal<number> {
    method increment (line 85) | increment(): void {

FILE: test/synth.ts
  function isFalse (line 13) | function isFalse(expr: Expression): boolean {
  constant STRING_VALUES (line 17) | const STRING_VALUES = [null, "", "a", "ab", "ab10", "ab-10"];
  constant DECIMAL_VALUES (line 18) | const DECIMAL_VALUES = [null, 0, -10, 10];
  function query (line 22) | async function query(filter: string): Promise<Set<number>> {
  function setsEqual (line 46) | function setsEqual(set1: Set<number>, set2: Set<number>): boolean {
  function getPermutations (line 52) | function getPermutations(...arrs: any[][]): any[][] {

FILE: ui/app.ts
  type Window (line 31) | interface Window {
  function pagify (line 63) | function pagify(pageName, page): RouteResolver {

FILE: ui/autocomplete-compnent.ts
  type AutocompleteCallback (line 1) | type AutocompleteCallback = (
  class Autocomplete (line 6) | class Autocomplete {
    method constructor (line 15) | public constructor(callback: AutocompleteCallback) {
    method attach (line 31) | public attach(el: HTMLInputElement): void {
    method reposition (line 76) | public reposition(): void {
    method hide (line 89) | private hide(): void {
    method update (line 103) | private update(): void {

FILE: ui/change-password-component.ts
  type Attrs (line 6) | interface Attrs {

FILE: ui/code-editor-component.ts
  type Attrs (line 5) | interface Attrs {

FILE: ui/components.ts
  type MC (line 45) | interface MC extends Static {
  function contextFn (line 86) | function contextFn(context, ...argumentsList): Vnode {
  function applyContext (line 92) | function applyContext(vnode, parentContext): void {
  function contextifyComponent (line 106) | function contextifyComponent(component: ComponentTypes): ComponentTypes {

FILE: ui/components/all-parameters.ts
  function escapeRegExp (line 12) | function escapeRegExp(str): string {
  type Parameter (line 16) | interface Parameter {
  type Attrs (line 52) | interface Attrs {

FILE: ui/components/container.ts
  type Attrs (line 35) | interface Attrs {

FILE: ui/components/loading.ts
  function apply (line 8) | function apply(vnode: VnodeDOM): void {

FILE: ui/components/overview-dot.ts
  constant CHARTS (line 6) | const CHARTS = overview.charts;

FILE: ui/components/parameter-list.ts
  type Attrs (line 7) | interface Attrs {

FILE: ui/components/parameter-table.ts
  type Attrs (line 10) | interface Attrs {

FILE: ui/components/ping.ts
  constant REFRESH_INTERVAL (line 5) | const REFRESH_INTERVAL = 3000;

FILE: ui/components/summon-button.ts
  type Attrs (line 10) | interface Attrs {

FILE: ui/components/tags.ts
  type Attrs (line 11) | interface Attrs {

FILE: ui/config-functions.ts
  type Config (line 1) | interface Config {
  type Diff (line 6) | interface Diff {
  function flattenConfig (line 11) | function flattenConfig(config: Record<string, unknown>): any {
  function orderKeys (line 27) | function orderKeys(config: any): number {
  function structureConfig (line 55) | function structureConfig(config: Config[]): any {
  function diffConfig (line 111) | function diffConfig(

FILE: ui/config-page.ts
  type ValidationErrors (line 17) | interface ValidationErrors {
  function putActionHandler (line 21) | function putActionHandler(action, _object, isNew?): Promise<ValidationEr...
  function escapeRegExp (line 90) | function escapeRegExp(str): string {
  function init (line 94) | function init(): Promise<Record<string, unknown>> {
  function renderTable (line 109) | function renderTable(confsResponse, searchString): Children {

FILE: ui/config.ts
  type Filters (line 5) | type Filters = { label: string; parameter: Expression; type: string }[];
  type pageSize (line 6) | type pageSize = number;
  type overview (line 7) | type overview = {
  type Index (line 24) | type Index = {
  type NestedRecord (line 32) | type NestedRecord = { [k: string]: Expression | NestedRecord };

FILE: ui/datalist.ts
  function hash (line 6) | function hash(str: string): number {
  function getDatalistId (line 16) | function getDatalistId(options: string[]): string {

FILE: ui/device-page.ts
  function init (line 9) | function init(
  type Attrs (line 28) | interface Attrs {

FILE: ui/devices-page.ts
  function init (line 55) | function init(args: Record<string, unknown>): Promise<Attrs> {
  function renderActions (line 78) | function renderActions(selected: Set<string>): Children {
  type Attrs (line 261) | interface Attrs {
  function showMore (line 273) | function showMore(): void {
  function onFilterChanged (line 279) | function onFilterChanged(filter: Expression): void {
  function onSortChange (line 297) | function onSortChange(sortedAttrs): void {

FILE: ui/drawer-component.ts
  function renderStagingSpv (line 26) | function renderStagingSpv(task: StageTask, queueFunc, cancelFunc): Child...
  function renderStagingDownload (line 97) | function renderStagingDownload(task: StageTask): Children {
  function renderStaging (line 186) | function renderStaging(staging: Set<StageTask>): Child[] {
  function renderQueue (line 240) | function renderQueue(queue: Set<QueueTask>): Child[] {
  function renderNotifications (line 397) | function renderNotifications(notifs): Child[] {
  function repositionNotifications (line 475) | function repositionNotifications(): void {
  function resizeDrawer (line 483) | function resizeDrawer(): void {

FILE: ui/dynamic-loader.ts
  function onError (line 8) | function onError(): void {
  function loadCodeMirror (line 22) | function loadCodeMirror(): Promise<void> {
  function loadYaml (line 38) | function loadYaml(): Promise<void> {

FILE: ui/faults-page.ts
  function deleteFaults (line 58) | async function deleteFaults(faults: Iterable<string>): Promise<void> {
  function init (line 70) | function init(
  function showMore (line 91) | function showMore(): void {
  function onFilterChanged (line 97) | function onFilterChanged(filter): void {
  function onSortChange (line 115) | function onSortChange(sortAttrs): void {

FILE: ui/files-page.ts
  function upload (line 66) | function upload(
  function init (line 104) | function init(
  function showMore (line 126) | function showMore(): void {
  function onFilterChanged (line 132) | function onFilterChanged(filter): void {
  function onSortChange (line 148) | function onSortChange(sortAttrs): void {

FILE: ui/filter-component.ts
  function parseFilter (line 24) | function parseFilter(resource: string, f: string): Expression {
  function splitFilter (line 63) | function splitFilter(filter: Expression): string[] {
  type Attrs (line 86) | interface Attrs {
  function onChange (line 98) | function onChange(): void {

FILE: ui/index-table-component.ts
  type Attribute (line 6) | interface Attribute {
  constant MAX_PAGE_SIZE (line 12) | const MAX_PAGE_SIZE = 200;
  function getExcerpt (line 14) | function getExcerpt(text: string, maxLength = 80, maxLines = 10): string...
  function renderTable (line 30) | function renderTable(

FILE: ui/layout.tsx
  function tsxComponent (line 17) | function tsxComponent<T>(
  function classNames (line 29) | function classNames(...classes: string[]): string {
  type Attrs (line 33) | interface Attrs {
  function setSidebarOpen (line 40) | function setSidebarOpen(open: boolean): void {

FILE: ui/login-page.tsx
  function init (line 8) | function init(
  function logIn (line 19) | function logIn(e: MouseEvent): boolean {
  function changePassword (line 33) | function changePassword(): void {

FILE: ui/long-text-component.ts
  function overflowed (line 11) | function overflowed(_vnode): void {

FILE: ui/notifications.ts
  type Notification (line 3) | interface Notification {
  function push (line 12) | function push(
  function dismiss (line 34) | function dismiss(n: Notification): void {
  function getNotifications (line 39) | function getNotifications(): Set<Notification> {

FILE: ui/overlay.ts
  type OverlayCallback (line 4) | type OverlayCallback = () => Children;
  type CloseCallback (line 5) | type CloseCallback = () => boolean;
  function open (line 10) | function open(
  function close (line 18) | function close(callback: OverlayCallback, force = true): boolean {
  function render (line 29) | function render(): Children {

FILE: ui/overview-page.ts
  constant GROUPS (line 9) | const GROUPS = overview.groups;
  constant CHARTS (line 10) | const CHARTS: typeof overview.charts = {};
  function queryCharts (line 16) | function queryCharts(charts: typeof overview.charts): typeof charts {
  function init (line 28) | function init(): Promise<{ charts: typeof overview.charts }> {
  type Attrs (line 38) | interface Attrs {

FILE: ui/permissions-page.ts
  function getExcerpt (line 46) | function getExcerpt(text: string, maxLength = 80, maxLines = 10): string...
  type ValidationErrors (line 82) | interface ValidationErrors {
  function putActionHandler (line 86) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 182) | function init(
  function showMore (line 203) | function showMore(): void {
  function onFilterChanged (line 209) | function onFilterChanged(filter): void {
  function onSortChange (line 228) | function onSortChange(sortAttrs): void {

FILE: ui/pie-chart-component.ts
  function drawChart (line 5) | function drawChart(chartData: Attrs["chart"]): Children {
  type Attrs (line 136) | interface Attrs {

FILE: ui/presets-page.ts
  type ValidationErrors (line 48) | interface ValidationErrors {
  function getExcerpt (line 52) | function getExcerpt(text: string, maxLength = 80, maxLines = 10): string...
  function putActionHandler (line 68) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 152) | function init(
  function showMore (line 174) | function showMore(): void {
  function onFilterChanged (line 180) | function onFilterChanged(filter): void {
  function onSortChange (line 206) | function onSortChange(sortAttrs): void {

FILE: ui/provisions-page.ts
  type ValidationErrors (line 42) | interface ValidationErrors {
  function putActionHandler (line 46) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 121) | function init(
  function showMore (line 150) | function showMore(): void {
  function onFilterChanged (line 156) | function onFilterChanged(filter): void {
  function onSortChange (line 172) | function onSortChange(sortAttrs): void {

FILE: ui/put-form-component.ts
  function createField (line 16) | function createField(current, attr, focus): Children {
  type Attrs (line 175) | interface Attrs {

FILE: ui/reactive-store.ts
  function evaluate (line 21) | function evaluate(
  type BookmarkData (line 41) | type BookmarkData = Record<string, null | boolean | number | string>;
  type QueryState (line 43) | interface QueryState<T> {
  type FetchedRegion (line 49) | interface FetchedRegion {
  type CachedCount (line 55) | interface CachedCount {
  type CachedBookmark (line 60) | interface CachedBookmark {
  type ResourceCache (line 65) | interface ResourceCache {
  class Bookmark (line 72) | class Bookmark {
    method constructor (line 73) | constructor(
    method applySkip (line 79) | applySkip(filter: Expression): Expression {
    method applyLimit (line 85) | applyLimit(filter: Expression): Expression {
  class QuerySignal (line 91) | class QuerySignal<T> extends SignalBase<QueryState<T>> {
    method constructor (line 95) | constructor(initialValue: T) {
    method get (line 105) | get(): QueryState<T> {
    method _peek (line 112) | _peek(): QueryState<T> {
    method _update (line 117) | _update(value: T, timestamp: number, loading: boolean): void {
    method _markSinksDirty (line 129) | private _markSinksDirty(): void {
    method _markSinksChecking (line 145) | private _markSinksChecking(
  method [Symbol.dispose] (line 165) | [Symbol.dispose](): void {
  function compareFunction (line 172) | function compareFunction(
  function getObjectId (line 208) | function getObjectId(resourceType: string, obj: unknown): string {
  type FetchQueryEntry (line 215) | interface FetchQueryEntry {
  type CountQueryEntry (line 221) | interface CountQueryEntry {
  type BookmarkQueryEntry (line 226) | interface BookmarkQueryEntry {
  class ResourceStore (line 233) | class ResourceStore {
    method constructor (line 243) | constructor(private resourceType: string) {
    method fetch (line 259) | fetch(
    method count (line 302) | count(filter: Expression, freshness: number): QuerySignal<number> {
    method createBookmark (line 337) | createBookmark(
    method getCombinedFilter (line 386) | private getCombinedFilter(minTimestamp: number): Expression {
    method checkCoverage (line 395) | private checkCoverage(
    method findMatchingObjects (line 421) | private findMatchingObjects(
    method addFetchedRegion (line 439) | private addFetchedRegion(filter: Expression, timestamp: number): void {
    method triggerFetchRefresh (line 469) | private triggerFetchRefresh(
    method triggerCountRefresh (line 531) | private triggerCountRefresh(
    method triggerBookmarkRefresh (line 576) | private triggerBookmarkRefresh(
    method invalidate (line 629) | invalidate(timestamp: number): void {
    method onQueryDisposed (line 671) | private onQueryDisposed(type: string, key: string): void {
    method pruneCache (line 684) | private pruneCache(): void {
  function getStore (line 743) | function getStore(resource: string): ResourceStore {
  function applyDefaultSort (line 752) | function applyDefaultSort(
  function fetch (line 765) | function fetch(
  function count (line 778) | function count(
  function createBookmark (line 787) | function createBookmark(
  function invalidate (line 808) | function invalidate(timestamp: number): void {

FILE: ui/signals.ts
  type ComputedState (line 4) | const enum ComputedState {
  function createSafeProxy (line 12) | function createSafeProxy<T extends object>(target: T): T {
  function registerDependency (line 47) | function registerDependency(source: SignalBase<unknown>): void {
  function registerCleanup (line 54) | function registerCleanup(cleanup: () => void): void {
  function runCleanups (line 60) | function runCleanups(signal: ComputedSignal<unknown>): void {
  type Sink (line 68) | type Sink = ComputedSignal<unknown> | Watcher;
  function markSinksChecking (line 70) | function markSinksChecking(sinks: Set<WeakRef<Sink>>): void {
  function markSinksDirty (line 92) | function markSinksDirty(sinks: Set<WeakRef<Sink>>): void {
  class ConstSignal (line 126) | class ConstSignal<T> extends SignalBase<T> {
    method constructor (line 129) | constructor(value: T) {
    method get (line 139) | get(): T {
  method [Symbol.dispose] (line 144) | [Symbol.dispose](): void {
  class StateSignal (line 151) | class StateSignal<T> extends SignalBase<T> {
    method constructor (line 154) | constructor(initialValue: T) {
    method get (line 165) | get(): T {
    method set (line 171) | set(newValue: T): void {
  method [Symbol.dispose] (line 178) | [Symbol.dispose](): void {
  class ComputedSignal (line 186) | class ComputedSignal<T> extends SignalBase<T> {
    method constructor (line 199) | constructor(callback: () => T) {
    method get (line 211) | get(): T {
    method _isValid (line 225) | _isValid(): boolean {
    method _recompute (line 242) | private _recompute(): T {
  method [Symbol.dispose] (line 280) | [Symbol.dispose](): void {
  class Watcher (line 307) | class Watcher implements Disposable {
    method constructor (line 314) | constructor(notify: () => void) {
    method watch (line 320) | watch(...signals: SignalBase<unknown>[]): void {
    method unwatch (line 329) | unwatch(...signals: SignalBase<unknown>[]): void {
    method getPending (line 338) | getPending(): SignalBase<unknown>[] {
    method _notify (line 350) | _notify(): void {
  method [Symbol.dispose] (line 356) | [Symbol.dispose](): void {
  class SafeConstSignal (line 368) | class SafeConstSignal<T> extends ConstSignal<T> {
    method constructor (line 373) | constructor(value: T) {
  method [Symbol.hasInstance] (line 369) | static [Symbol.hasInstance](instance: unknown): boolean {
  class SafeStateSignal (line 379) | class SafeStateSignal<T> extends StateSignal<T> {
    method constructor (line 384) | constructor(initialValue: T) {
  method [Symbol.hasInstance] (line 380) | static [Symbol.hasInstance](instance: unknown): boolean {
  class SafeComputedSignal (line 390) | class SafeComputedSignal<T> extends ComputedSignal<T> {
    method constructor (line 395) | constructor(callback: () => T) {
  method [Symbol.hasInstance] (line 391) | static [Symbol.hasInstance](instance: unknown): boolean {
  method [Symbol.hasInstance] (line 405) | [Symbol.hasInstance](instance: unknown): boolean {
  function setTimeout (line 413) | function setTimeout<TArgs extends unknown[]>(
  function setInterval (line 440) | function setInterval<TArgs extends unknown[]>(

FILE: ui/skewed-date.ts
  function getClockSkew (line 1) | function getClockSkew(): number {
  class SkewedDate (line 5) | class SkewedDate extends Date {
    method constructor (line 6) | constructor(...args: unknown[]) {
    method now (line 14) | static override now(): number {

FILE: ui/smart-query.ts
  function getLabels (line 113) | function getLabels(resource: string): string[] {
  function queryNumber (line 118) | function queryNumber(param: Expression, value: string): Expression {
  function queryTimestamp (line 134) | function queryTimestamp(param: Expression, value: string): Expression {
  function queryString (line 150) | function queryString(param: Expression, value: string): Expression {
  function queryStringCaseSensitive (line 158) | function queryStringCaseSensitive(
  function queryStringMonoCase (line 165) | function queryStringMonoCase(param: Expression, value: string): Expressi...
  function queryMac (line 180) | function queryMac(param: Expression, value: string): Expression {
  function queryMacWildcard (line 214) | function queryMacWildcard(param: Expression, value: string): Expression {
  function queryTag (line 243) | function queryTag(tag: string): Expression {
  function getTip (line 251) | function getTip(resource: string, label: string): string {
  function unpack (line 295) | function unpack(

FILE: ui/store.ts
  function evaluate (line 24) | function evaluate(
  type Resources (line 62) | interface Resources {
  class QueryResponse (line 92) | class QueryResponse {
    method fulfilled (line 93) | public get fulfilled(): number {
    method fulfilling (line 98) | public get fulfilling(): boolean {
    method value (line 103) | public get value(): any {
  function checkConnection (line 109) | function checkConnection(): void {
  function xhrRequest (line 196) | async function xhrRequest(
  function unpackExpression (line 246) | function unpackExpression(exp: Expression): Expression {
  function count (line 250) | function count(resourceType: string, filter: Expression): QueryResponse {
  function compareFunction (line 262) | function compareFunction(sort: {
  function findMatches (line 298) | function findMatches(resourceType, filter, sort, limit): any[] {
  function fetch (line 310) | function fetch(
  function fulfill (line 347) | function fulfill(accessTimestamp: number): void {
  function getTimestamp (line 565) | function getTimestamp(): number {
  function setTimestamp (line 569) | function setTimestamp(t: number): void {
  function postTasks (line 577) | function postTasks(
  function updateTags (line 610) | function updateTags(
  function deleteResource (line 621) | function deleteResource(
  function putResource (line 631) | function putResource(
  function queryConfig (line 645) | function queryConfig(pattern = "%"): Promise<any[]> {
  function resourceExists (line 658) | function resourceExists(resource: string, id: string): Promise<number> {
  function evaluateExpression (line 689) | function evaluateExpression(
  function changePassword (line 696) | function changePassword(
  function logIn (line 711) | function logIn(
  function logOut (line 724) | function logOut(): Promise<void> {
  function ping (line 731) | function ping(host: string): Promise<PingResult> {

FILE: ui/tailwind-utility-components.ts
  type DialogAttrs (line 39) | interface DialogAttrs {
  method view (line 47) | view(vnode) {
  type DialogOverlayAttrs (line 60) | interface DialogOverlayAttrs {
  method view (line 66) | view(vnode) {
  type TransitionRootAttrs (line 79) | interface TransitionRootAttrs {
  method view (line 92) | view(vnode: Vnode<TransitionRootAttrs>) {
  type TransitionChildAttrs (line 114) | interface TransitionChildAttrs {
  function updateCssClasses (line 128) | function updateCssClasses(vnode: VnodeDOM<TransitionChildAttrs>): void {
  method view (line 161) | view(vnode: Vnode<TransitionChildAttrs>) {
  method oncreate (line 168) | oncreate(vnode: VnodeDOM<TransitionChildAttrs>) {
  method onupdate (line 172) | onupdate(vnode: VnodeDOM<TransitionChildAttrs>) {
  type IconAttrs (line 178) | interface IconAttrs {
  method view (line 185) | view(vnode) {

FILE: ui/task-queue.ts
  type QueueTask (line 6) | interface QueueTask extends Task {
  type StageTask (line 11) | interface StageTask extends Task {
  constant MAX_QUEUE (line 15) | const MAX_QUEUE = 100;
  function canQueue (line 20) | function canQueue(tasks: QueueTask[]): boolean {
  function queueTask (line 26) | function queueTask(...tasks: QueueTask[]): void {
  function deleteTask (line 39) | function deleteTask(task: QueueTask): void {
  function getQueue (line 43) | function getQueue(): Set<QueueTask> {
  function clear (line 47) | function clear(): void {
  function getStaging (line 51) | function getStaging(): Set<StageTask> {
  function clearStaging (line 55) | function clearStaging(): void {
  function stageSpv (line 59) | function stageSpv(task: StageTask): void {
  function stageDownload (line 68) | function stageDownload(task: StageTask): void {
  function commit (line 77) | function commit(

FILE: ui/timeago.ts
  constant UNITS (line 1) | const UNITS = {
  function timeAgo (line 10) | function timeAgo(dtime: number): string {

FILE: ui/ui-config-component.ts
  function putActionHandler (line 9) | function putActionHandler(prefix: string[], dataYaml: string): Promise<a...
  type Attrs (line 70) | interface Attrs {

FILE: ui/users-page.ts
  type ValidationErrors (line 42) | interface ValidationErrors {
  function putActionHandler (line 46) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 137) | function init(
  function showMore (line 159) | function showMore(): void {
  function onFilterChanged (line 165) | function onFilterChanged(filter): void {
  function onSortChange (line 184) | function onSortChange(sortAttrs): void {

FILE: ui/views-page.ts
  constant PAGE_SIZE (line 15) | const PAGE_SIZE = config.pageSize || 10;
  type ValidationErrors (line 42) | interface ValidationErrors {
  function putActionHandler (line 46) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 120) | function init(
  function showMore (line 146) | function showMore(): void {
  function onFilterChanged (line 152) | function onFilterChanged(filter): void {
  function onSortChange (line 166) | function onSortChange(sortAttrs): void {

FILE: ui/views.ts
  type ViewElement (line 20) | type ViewElement =
  class ViewNode (line 27) | class ViewNode {
    method constructor (line 31) | constructor(
  type SignalizedViewNode (line 45) | interface SignalizedViewNode {
  function toSignal (line 52) | function toSignal<T>(value: T | SignalBase<T>): SignalBase<T> {
  function signalizeNode (line 58) | function signalizeNode(node: ViewNode): SignalizedViewNode {
  function doCount (line 71) | function doCount(node: SignalizedViewNode): ViewElement {
  function doFetch (line 96) | function doFetch(node: SignalizedViewNode): ViewElement {
  function doTask (line 119) | function doTask(node: SignalizedViewNode): ViewElement {
  function doNotify (line 166) | function doNotify(node: SignalizedViewNode): ViewElement {
  function doDelete (line 180) | function doDelete(node: SignalizedViewNode): ViewElement {
  function doYamlStringify (line 202) | function doYamlStringify(node: SignalizedViewNode): ViewElement {
  function doUpdateTags (line 212) | function doUpdateTags(node: SignalizedViewNode): ViewElement {
  function doPing (line 234) | function doPing(node: SignalizedViewNode): ViewElement {
  function initView (line 256) | function initView(context: RenderContext, node: ViewElement): ViewElement {
  type SetTimeout (line 300) | type SetTimeout = typeof setTimeout;
  type DateConstructorLike (line 302) | type DateConstructorLike = typeof globalThis.Date;
  type ViewFunc (line 304) | type ViewFunc = (
  class RenderContext (line 311) | class RenderContext {
    method constructor (line 315) | constructor(clone?: RenderContext) {
    method getView (line 325) | getView(name: string): ViewFunc {
    method pushViews (line 331) | pushViews(_views: Record<string, ViewFunc>): RenderContext {
    method popView (line 339) | popView(name: string): RenderContext {
    method getDeferred (line 347) | getDeferred(): (ViewNode | SignalBase | any)[] {
    method popDeferred (line 352) | popDeferred(): RenderContext {
    method pushDeferred (line 358) | pushDeferred(deferred: (ViewNode | SignalBase | any)[]): RenderContext {
  function renderNode (line 365) | function renderNode(node: ViewElement): ReturnType<typeof m> {

FILE: ui/virtual-parameters-page.ts
  type ValidationErrors (line 42) | interface ValidationErrors {
  function putActionHandler (line 46) | function putActionHandler(action, _object, isNew): Promise<ValidationErr...
  function init (line 121) | function init(
  function showMore (line 150) | function showMore(): void {
  function onFilterChanged (line 156) | function onFilterChanged(filter): void {
  function onSortChange (line 172) | function onSortChange(sortAttrs): void {

FILE: ui/wizard-page.ts
  function init (line 5) | async function init(): Promise<Record<string, unknown>> {
Condensed preview — 187 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,832K chars).
[
  {
    "path": ".gitignore",
    "chars": 33,
    "preview": "*~\nnode_modules\ndist\ndocs/_build\n"
  },
  {
    "path": ".prettierignore",
    "chars": 25,
    "preview": "dist\nnpm-shrinkwrap.json\n"
  },
  {
    "path": "AGENTS.md",
    "chars": 2907,
    "preview": "# AGENTS.md — GenieACS\n\nGenieACS is a TR-069 Auto Configuration Server for remote management of CPE\ndevices (routers, mo"
  },
  {
    "path": "ARCHITECTURE.md",
    "chars": 23077,
    "preview": "# Architecture\n\nThis document describes the high-level architecture of GenieACS. If you want to\nfamiliarize yourself wit"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 18889,
    "preview": "# Change Log\n\n## 1.2.14 (2026-03-12)\n\n- Prevent UI crash when a malformed URL is sent to the server.\n\n- Fix potential ed"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 13257,
    "preview": "# Contributing to GenieACS\n\n## Questions and Support\n\nPlease use the [forum](https://forum.genieacs.com) for questions, "
  },
  {
    "path": "LICENSE",
    "chars": 34520,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 2726,
    "preview": "# GenieACS\n\n**This is the development branch for GenieACS v1.3. It is unstable and not ready\nfor production use. For the"
  },
  {
    "path": "bin/genieacs-cwmp.ts",
    "chars": 2873,
    "preview": "import * as config from \"../lib/config.ts\";\nimport * as logger from \"../lib/logger.ts\";\nimport * as cluster from \"../lib"
  },
  {
    "path": "bin/genieacs-ext.ts",
    "chars": 1791,
    "preview": "import { Fault } from \"../lib/types.ts\";\n\nconst jobs = new Set();\nconst fileName = process.argv[2];\nlet script;\n\nfunctio"
  },
  {
    "path": "bin/genieacs-fs.ts",
    "chars": 2499,
    "preview": "import * as config from \"../lib/config.ts\";\nimport * as logger from \"../lib/logger.ts\";\nimport * as cluster from \"../lib"
  },
  {
    "path": "bin/genieacs-nbi.ts",
    "chars": 2651,
    "preview": "import * as config from \"../lib/config.ts\";\nimport * as logger from \"../lib/logger.ts\";\nimport * as cluster from \"../lib"
  },
  {
    "path": "bin/genieacs-ui.ts",
    "chars": 2673,
    "preview": "import * as config from \"../lib/config.ts\";\nimport * as logger from \"../lib/logger.ts\";\nimport * as cluster from \"../lib"
  },
  {
    "path": "build/assets.ts",
    "chars": 182,
    "preview": "export const APP_JS = \"app.js\";\nexport const APP_CSS = \"app.css\";\nexport const ICONS_SVG = \"icons.svg\";\nexport const LOG"
  },
  {
    "path": "build/build.ts",
    "chars": 11594,
    "preview": "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { promisify } f"
  },
  {
    "path": "build/generate-fonts.sh",
    "chars": 715,
    "preview": "#!/bin/bash\n\ncd \"$(dirname \"$0\")\"\n\ndeclare -A FONTS=(\n  [InterVariable]=https://rsms.me/inter/font-files/InterVariable.w"
  },
  {
    "path": "build/lint.ts",
    "chars": 1512,
    "preview": "import { exec } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst execPromise = promisify(exec);\n"
  },
  {
    "path": "build/spellcheck-dict.pws",
    "chars": 1563,
    "preview": "personal_ws-1.1 en 0\ngenieacs\nGenieACS\njavascript\nsudo\nconfig\ncwmp\nCPE\nsystemctl\nnbi\nCWMP\nNBI\nACS\nSSL\nxsd\nargs\nDeviceID\n"
  },
  {
    "path": "build/spellcheck.sh",
    "chars": 221,
    "preview": "#! /bin/sh\n\ncd \"$(dirname \"$0\")\"\n\nFILES=`ls ../docs/*.rst ../docs/*.js ../*.md`\n\nfor FILE in $FILES\ndo\n    echo $FILE\n  "
  },
  {
    "path": "build/test.ts",
    "chars": 2128,
    "preview": "import path from \"node:path\";\nimport { readdir, readFile } from \"node:fs/promises\";\n\nimport * as esbuild from \"esbuild\";"
  },
  {
    "path": "docs/.readthedocs.yaml",
    "chars": 313,
    "preview": "# Read the Docs configuration file for Sphinx projects\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html f"
  },
  {
    "path": "docs/administration-faq.rst",
    "chars": 2565,
    "preview": ".. _administration-faq:\n\nAdministration FAQ\n==================\n\n.. _administration-faq-duplicate-log-entries:\n\nDuplicate"
  },
  {
    "path": "docs/api-reference.rst",
    "chars": 14461,
    "preview": "API Reference\n=============\n\nGenieACS exposes a rich RESTful API through its NBI component. This document\nserves as a re"
  },
  {
    "path": "docs/conf.py",
    "chars": 2133,
    "preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
  },
  {
    "path": "docs/cpe-authentication.rst",
    "chars": 2209,
    "preview": ".. _cpe-authentication:\n\nCPE Authentication\n==================\n\nCPE to ACS\n----------\n\n.. note::\n\n  By default GenieACS "
  },
  {
    "path": "docs/environment-variables.rst",
    "chars": 4815,
    "preview": ".. _environment-variables:\n\nEnvironment Variables\n=====================\n\nConfiguring GenieACS services can be done throu"
  },
  {
    "path": "docs/ext-sample.js",
    "chars": 992,
    "preview": "// This is an example GenieACS extension to get the current latitude/longitude\n// of the International Space Station. Wh"
  },
  {
    "path": "docs/extensions.rst",
    "chars": 1266,
    "preview": ".. _extensions:\n\nExtensions\n==========\n\nGiven that :ref:`provisions` and :ref:`virtual-parameters` are executed in a\nsan"
  },
  {
    "path": "docs/https.rst",
    "chars": 30,
    "preview": ".. _https:\n\nHTTPS\n=====\n\nTODO\n"
  },
  {
    "path": "docs/index.rst",
    "chars": 893,
    "preview": ".. GenieACS documentation master file, created by\n   sphinx-quickstart on Wed Jun  5 13:47:06 2019.\n   You can adapt thi"
  },
  {
    "path": "docs/installation-guide.rst",
    "chars": 6216,
    "preview": "Installation Guide\n==================\n\nThis guide is for installing GenieACS on a single server on any Linux distro\nthat"
  },
  {
    "path": "docs/provisions.rst",
    "chars": 11086,
    "preview": ".. _provisions:\n\nProvisions\n==========\n\nA Provision is a piece of JavaScript code that is executed on the server on a\npe"
  },
  {
    "path": "docs/requirements.txt",
    "chars": 24,
    "preview": "sphinx_rtd_theme==2.0.0\n"
  },
  {
    "path": "docs/roles-and-permissions.rst",
    "chars": 78,
    "preview": ".. _roles-and-permissions:\n\nRoles and Permissions\n=====================\n\nTODO\n"
  },
  {
    "path": "docs/virtual-parameters.rst",
    "chars": 3576,
    "preview": ".. _virtual-parameters:\n\nVirtual Parameters\n==================\n\nVirtual parameters are user-defined parameters whose val"
  },
  {
    "path": "eslint.config.mjs",
    "chars": 2637,
    "preview": "import { defineConfig } from \"@eslint/config-helpers\";\nimport eslint from \"@eslint/js\";\nimport tseslint from \"typescript"
  },
  {
    "path": "lib/api-functions.ts",
    "chars": 14879,
    "preview": "import { ObjectId } from \"mongodb\";\nimport { collections } from \"./db/db.ts\";\nimport {\n  deleteConfig,\n  deleteFault as "
  },
  {
    "path": "lib/auth.ts",
    "chars": 4783,
    "preview": "import { createHash, randomBytes, pbkdf2 } from \"node:crypto\";\n\nfunction parseHeaderFeilds(str: string): Record<string, "
  },
  {
    "path": "lib/bundle-views.ts",
    "chars": 2227,
    "preview": "import esbuild from \"esbuild\";\n\nimport { APP_JS } from \"../build/assets.ts\";\nimport { Views } from \"./types.ts\";\n\nexport"
  },
  {
    "path": "lib/cache.ts",
    "chars": 935,
    "preview": "import { collections } from \"./db/db.ts\";\nimport * as config from \"./config.ts\";\n\nconst CLOCK_SKEW_TOLERANCE = 30000;\nco"
  },
  {
    "path": "lib/cluster.ts",
    "chars": 2409,
    "preview": "import cluster, { Worker } from \"node:cluster\";\nimport { cpus } from \"node:os\";\nimport * as logger from \"./logger.ts\";\n\n"
  },
  {
    "path": "lib/common/authorizer.ts",
    "chars": 3973,
    "preview": "import { PermissionSet } from \"../types.ts\";\nimport Expression from \"./expression.ts\";\n\nexport default class Authorizer "
  },
  {
    "path": "lib/common/debounce.ts",
    "chars": 364,
    "preview": "export default function debounce<T>(\n  func: (args: T[]) => void,\n  timeout: number,\n): (arg: T) => void {\n  let timer: "
  },
  {
    "path": "lib/common/errors.ts",
    "chars": 147,
    "preview": "export class ResourceLockedError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"R"
  },
  {
    "path": "lib/common/expression/evaluate.ts",
    "chars": 7889,
    "preview": "import Expression from \"../expression.ts\";\nimport { likePatternToRegExp } from \"./parser.ts\";\n\nfunction compare(\n  a: bo"
  },
  {
    "path": "lib/common/expression/normalize.ts",
    "chars": 14400,
    "preview": "import Expression from \"../expression.ts\";\nimport { reduce } from \"./evaluate.ts\";\n\nclass Indeterminates {\n  declare pub"
  },
  {
    "path": "lib/common/expression/pagination.ts",
    "chars": 5015,
    "preview": "import { complement } from \"espresso-iisojs\";\nimport Expression from \"../expression.ts\";\nimport normalize from \"./normal"
  },
  {
    "path": "lib/common/expression/parser.ts",
    "chars": 16261,
    "preview": "import Path from \"../path.ts\";\nimport Expression from \"../expression.ts\";\n\nexport class Cursor {\n  input: string;\n  pos:"
  },
  {
    "path": "lib/common/expression/synth.ts",
    "chars": 35263,
    "preview": "import { espresso, complement, tautology } from \"espresso-iisojs\";\nimport Expression from \"../expression.ts\";\nimport { p"
  },
  {
    "path": "lib/common/expression.ts",
    "chars": 8387,
    "preview": "import {\n  Cursor,\n  parseExpression,\n  stringifyExpression,\n} from \"./expression/parser.ts\";\nimport Path from \"./path.t"
  },
  {
    "path": "lib/common/memoize.ts",
    "chars": 1335,
    "preview": "let cache1 = new Map();\nlet cache2 = new Map();\nconst keys = new WeakMap();\n\nfunction getKey(obj): string {\n  if (obj =="
  },
  {
    "path": "lib/common/path-set.ts",
    "chars": 3494,
    "preview": "import Path from \"./path.ts\";\n\nexport default class PathSet {\n  private paramSegmentIndex: Map<string, Set<Path>>[] = []"
  },
  {
    "path": "lib/common/path.ts",
    "chars": 4921,
    "preview": "import Expression from \"./expression.ts\";\nimport { Cursor, parsePath } from \"./expression/parser.ts\";\n\ntype Segments = ("
  },
  {
    "path": "lib/common/yaml.ts",
    "chars": 4962,
    "preview": "const LINE_WIDTH = 80;\nconst INDENTATION = \"  \";\n\nconst STRING_RESERVED = new Set([\n  \"true\",\n  \"True\",\n  \"TRUE\",\n  \"fal"
  },
  {
    "path": "lib/config.ts",
    "chars": 8731,
    "preview": "import { resolve } from \"node:path\";\nimport { readFileSync, existsSync } from \"node:fs\";\n\n// Find project root directory"
  },
  {
    "path": "lib/connection-request.ts",
    "chars": 9864,
    "preview": "import * as crypto from \"node:crypto\";\nimport * as dgram from \"node:dgram\";\nimport * as http from \"node:http\";\nimport Ex"
  },
  {
    "path": "lib/cwmp/db.ts",
    "chars": 22221,
    "preview": "import { ObjectId } from \"mongodb\";\nimport { decodeTag, encodeTag, escapeRegExp } from \"../util.ts\";\nimport {\n  DeviceDa"
  },
  {
    "path": "lib/cwmp/local-cache.ts",
    "chars": 10160,
    "preview": "import * as vm from \"node:vm\";\nimport * as crypto from \"node:crypto\";\nimport { collections } from \"../db/db.ts\";\nimport "
  },
  {
    "path": "lib/cwmp.ts",
    "chars": 46430,
    "preview": "import * as zlib from \"node:zlib\";\nimport * as crypto from \"node:crypto\";\nimport { Socket } from \"node:net\";\nimport { In"
  },
  {
    "path": "lib/db/db.ts",
    "chars": 2385,
    "preview": "import { MongoClient, Collection, GridFSBucket } from \"mongodb\";\nimport { get } from \"../config.ts\";\nimport * as MongoTy"
  },
  {
    "path": "lib/db/synth.ts",
    "chars": 23173,
    "preview": "import { Filter } from \"mongodb\";\nimport { EJSON } from \"bson\";\nimport { complement } from \"espresso-iisojs\";\nimport { p"
  },
  {
    "path": "lib/db/types.ts",
    "chars": 3513,
    "preview": "import { ObjectId } from \"mongodb\";\nimport { FaultStruct } from \"../types.ts\";\nimport { Value } from \"../common/expressi"
  },
  {
    "path": "lib/db/util.ts",
    "chars": 5957,
    "preview": "import Expression, { Value } from \"../common/expression.ts\";\nimport Path from \"../common/path.ts\";\nimport { encodeTag } "
  },
  {
    "path": "lib/debug.ts",
    "chars": 6746,
    "preview": "import { IncomingMessage, ServerResponse, ClientRequest } from \"node:http\";\nimport { Socket } from \"node:net\";\nimport { "
  },
  {
    "path": "lib/default-provisions.ts",
    "chars": 6122,
    "preview": "import Path from \"./common/path.ts\";\nimport * as config from \"./config.ts\";\nimport * as device from \"./device.ts\";\nimpor"
  },
  {
    "path": "lib/device.ts",
    "chars": 11494,
    "preview": "import Expression, { Value } from \"./common/expression.ts\";\nimport Path from \"./common/path.ts\";\nimport {\n  DeviceData,\n"
  },
  {
    "path": "lib/extensions.ts",
    "chars": 2990,
    "preview": "import { spawn, ChildProcess } from \"node:child_process\";\nimport * as crypto from \"node:crypto\";\nimport readline from \"n"
  },
  {
    "path": "lib/forwarded.ts",
    "chars": 4926,
    "preview": "import { IncomingMessage } from \"node:http\";\nimport { TLSSocket } from \"node:tls\";\nimport { parseCIDR, parse, IPv6, IPv4"
  },
  {
    "path": "lib/fs.ts",
    "chars": 5550,
    "preview": "import * as url from \"node:url\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { PassThrough, pipe"
  },
  {
    "path": "lib/gpn-heuristic.ts",
    "chars": 1707,
    "preview": "import Path from \"./common/path.ts\";\n\nconst WILDCARD_MULTIPLIER = 2;\nconst UNDISCOVERED_DEPTH = 7;\n\n// Simple heuristic "
  },
  {
    "path": "lib/init.ts",
    "chars": 8449,
    "preview": "import { getRevision, getUiConfig, getUsers } from \"./ui/local-cache.ts\";\nimport { generateSalt, hashPassword } from \"./"
  },
  {
    "path": "lib/instance-set.ts",
    "chars": 2372,
    "preview": "interface Instance {\n  [name: string]: string;\n}\n\nexport default class InstanceSet {\n  declare private set: Set<Instance"
  },
  {
    "path": "lib/local-cache.ts",
    "chars": 1924,
    "preview": "import { setTimeoutPromise } from \"./util.ts\";\nimport { get, set } from \"./cache.ts\";\nimport { acquireLock, releaseLock "
  },
  {
    "path": "lib/lock.ts",
    "chars": 1384,
    "preview": "import { collections } from \"./db/db.ts\";\n\nconst CLOCK_SKEW_TOLERANCE = 30000;\n\nexport async function acquireLock(\n  loc"
  },
  {
    "path": "lib/logger.ts",
    "chars": 9086,
    "preview": "import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as config from \"./config.ts\";\nimport { getRequest"
  },
  {
    "path": "lib/nbi.ts",
    "chars": 21971,
    "preview": "import * as vm from \"node:vm\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Collection, ObjectI"
  },
  {
    "path": "lib/ping.ts",
    "chars": 2860,
    "preview": "import { platform } from \"node:os\";\nimport { exec } from \"node:child_process\";\nimport { domainToASCII } from \"node:url\";"
  },
  {
    "path": "lib/query.ts",
    "chars": 4231,
    "preview": "function isObject(obj: any): boolean {\n  return Object.prototype.toString.call(obj) === \"[object Object]\";\n}\n\nfunction s"
  },
  {
    "path": "lib/sandbox.ts",
    "chars": 10645,
    "preview": "import * as vm from \"node:vm\";\nimport seedrandom from \"seedrandom\";\nimport * as device from \"./device.ts\";\nimport * as e"
  },
  {
    "path": "lib/scheduling.ts",
    "chars": 1253,
    "preview": "import * as crypto from \"node:crypto\";\nimport * as later from \"@breejs/later\";\n\nfunction md532(str): number {\n  const di"
  },
  {
    "path": "lib/server.ts",
    "chars": 4504,
    "preview": "import { readFileSync } from \"node:fs\";\nimport * as http from \"node:http\";\nimport * as https from \"node:https\";\nimport {"
  },
  {
    "path": "lib/session.ts",
    "chars": 87462,
    "preview": "import * as device from \"./device.ts\";\nimport * as sandbox from \"./sandbox.ts\";\nimport * as localCache from \"./cwmp/loca"
  },
  {
    "path": "lib/soap.ts",
    "chars": 28883,
    "preview": "import {\n  parseXml,\n  Element,\n  parseAttrs,\n  encodeEntities,\n  decodeEntities,\n} from \"./xml-parser.ts\";\nimport memoi"
  },
  {
    "path": "lib/types.ts",
    "chars": 11037,
    "preview": "import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Script } from \"node:vm\";\nimport Path from \"./commo"
  },
  {
    "path": "lib/ui/api.ts",
    "chars": 24445,
    "preview": "import { Readable } from \"node:stream\";\nimport Router from \"@koa/router\";\nimport { ObjectId } from \"mongodb\";\nimport * a"
  },
  {
    "path": "lib/ui/db.ts",
    "chars": 15989,
    "preview": "import { Script } from \"node:vm\";\nimport { Readable } from \"node:stream\";\nimport { Collection, ObjectId, WithoutId } fro"
  },
  {
    "path": "lib/ui/local-cache.ts",
    "chars": 4858,
    "preview": "import * as crypto from \"node:crypto\";\nimport { collections } from \"../db/db.ts\";\nimport Expression, { Value } from \"../"
  },
  {
    "path": "lib/ui.ts",
    "chars": 9031,
    "preview": "import { constants } from \"node:zlib\";\nimport Koa from \"koa\";\nimport Router from \"@koa/router\";\nimport * as jwt from \"js"
  },
  {
    "path": "lib/util.ts",
    "chars": 1920,
    "preview": "import { EventEmitter } from \"node:events\";\n\nexport function generateDeviceId(\n  deviceIdStruct: Record<string, string>,"
  },
  {
    "path": "lib/versioned-map.ts",
    "chars": 5271,
    "preview": "const NONEXISTENT = Symbol();\nconst UNDEFINED = undefined;\n\ninterface Revisions<V> {\n  [rev: number]: V;\n  delete?: numb"
  },
  {
    "path": "lib/xml-parser.ts",
    "chars": 9156,
    "preview": "const CHAR_SINGLE_QUOTE = 39;\nconst CHAR_DOUBLE_QUOTE = 34;\nconst CHAR_LESS_THAN = 60;\nconst CHAR_GREATER_THAN = 62;\ncon"
  },
  {
    "path": "lib/xmpp-client.ts",
    "chars": 13694,
    "preview": "import * as net from \"node:net\";\nimport * as tls from \"node:tls\";\nimport { EventEmitter } from \"node:events\";\nimport { c"
  },
  {
    "path": "npm-shrinkwrap.json",
    "chars": 408058,
    "preview": "{\n  \"name\": \"genieacs\",\n  \"version\": \"1.3.0-dev\",\n  \"lockfileVersion\": 2,\n  \"requires\": true,\n  \"packages\": {\n    \"\": {\n"
  },
  {
    "path": "package.json",
    "chars": 2352,
    "preview": "{\n  \"name\": \"genieacs\",\n  \"version\": \"1.3.0-dev\",\n  \"description\": \"A TR-069 Auto Configuration Server (ACS)\",\n  \"reposi"
  },
  {
    "path": "seed/bootstrap.js",
    "chars": 130,
    "preview": "const now = Date.now();\n\n// Clear cached data model to force a refresh\nclear(\"Device\", now);\nclear(\"InternetGatewayDevic"
  },
  {
    "path": "seed/datamodel-explorer.jsx",
    "chars": 4461,
    "preview": "// Interactive explorer for browsing and searching device data model parameters.\n//\n// Attributes:\n//   device - Device "
  },
  {
    "path": "seed/default.js",
    "chars": 1201,
    "preview": "const hourly = Date.now(3600000);\n\n// Refresh basic parameters hourly\ndeclare(\"InternetGatewayDevice.DeviceInfo.Hardware"
  },
  {
    "path": "seed/device-page-tr098.jsx",
    "chars": 9943,
    "preview": "// Device page for TR-098 (InternetGatewayDevice) data model.\n//\n// Displays device information, parameters, LAN hosts, "
  },
  {
    "path": "seed/device-page-tr181.jsx",
    "chars": 9678,
    "preview": "// Device page for TR-181 (Device:2) data model.\n//\n// Displays device information, parameters, LAN hosts, faults, and d"
  },
  {
    "path": "seed/device-page.jsx",
    "chars": 842,
    "preview": "// Router that delegates to the appropriate data model-specific device page.\n//\n// Automatically detects device data mod"
  },
  {
    "path": "seed/icon.jsx",
    "chars": 1823,
    "preview": "// SVG icon library component.\n//\n// Attributes:\n//   name  - Icon name (see available icons below)\n//   class - CSS cla"
  },
  {
    "path": "seed/inform.js",
    "chars": 1628,
    "preview": "// Device ID as user name\nconst username = declare(\"DeviceID.ID\", { value: 1 }).value[0];\n\n// Password will be fixed for"
  },
  {
    "path": "seed/instance-table.jsx",
    "chars": 4010,
    "preview": "// Table component for displaying object instances with configurable columns.\n//\n// Attributes:\n//   device - Device obj"
  },
  {
    "path": "seed/overview-page.jsx",
    "chars": 962,
    "preview": "// Dashboard page displaying device online status statistics.\n//\n// This is the default overview page shown on the main "
  },
  {
    "path": "seed/parameter.jsx",
    "chars": 2016,
    "preview": "// Displays a device parameter value with optional inline editing.\n//\n// Attributes:\n//   device - Device object contain"
  },
  {
    "path": "seed/pie-chart.jsx",
    "chars": 4032,
    "preview": "// Pie chart component that displays device counts by filter criteria.\n//\n// Attributes:\n//   label - Chart title displa"
  },
  {
    "path": "seed/provisions.d.ts",
    "chars": 1659,
    "preview": "interface Timestamps {\n  path?: number;\n  object?: number;\n  writable?: number;\n  value?: number;\n  notification?: numbe"
  },
  {
    "path": "seed/summon-button.jsx",
    "chars": 1565,
    "preview": "// Button that initiates a device session and refreshes parameters.\n//\n// Attributes:\n//   deviceId - Device identifier "
  },
  {
    "path": "seed/tags.jsx",
    "chars": 2384,
    "preview": "// Displays and manages device tags with add/remove functionality.\n//\n// Attributes:\n//   device   - Device object conta"
  },
  {
    "path": "seed/tsconfig.json",
    "chars": 294,
    "preview": "{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"noEmit\": true,\n    \"target\": \"ES2022\",\n    \"jsx\""
  },
  {
    "path": "seed/views.d.ts",
    "chars": 1119,
    "preview": "interface Signal<T = any> {\n  get(): T;\n}\n\ninterface StateSignal<T = any> extends Signal<T> {\n  set(value: T): void;\n}\n\n"
  },
  {
    "path": "test/auth.ts",
    "chars": 1195,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { randomBytes } from \"node:crypto\";\nimport * as a"
  },
  {
    "path": "test/db.ts",
    "chars": 5229,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { EJSON } from \"bson\";\nimport { Filter } from \"mo"
  },
  {
    "path": "test/device.ts",
    "chars": 3100,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport Path from \"../lib/common/path.ts\";\nimport * as de"
  },
  {
    "path": "test/mocks/store.ts",
    "chars": 6157,
    "preview": "// Mock implementation of ui/store.ts for testing (substituted via esbuild alias)\n\nimport Expression from \"../../lib/com"
  },
  {
    "path": "test/pagination.ts",
    "chars": 3651,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport initSqlJs from \"sql.js/dist/sql-asm.js\";\nimport {"
  },
  {
    "path": "test/path-set.ts",
    "chars": 1579,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport Path from \"../lib/common/path.ts\";\nimport PathSet"
  },
  {
    "path": "test/path.ts",
    "chars": 6201,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport Path from \"../lib/common/path.ts\";\n\nvoid test(\"pa"
  },
  {
    "path": "test/ping.ts",
    "chars": 1566,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { parsePing } from \"../lib/ping.ts\";\n\nvoid test(\""
  },
  {
    "path": "test/reactive-store.ts",
    "chars": 44398,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport { ComputedSignal } from \"../ui/signals.ts\";\nimpor"
  },
  {
    "path": "test/signals.ts",
    "chars": 21645,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport {\n  ConstSignal,\n  SignalBase,\n  StateSignal,\n  C"
  },
  {
    "path": "test/synth.ts",
    "chars": 9680,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport initSqlJs from \"sql.js/dist/sql-asm.js\";\nimport {"
  },
  {
    "path": "test/util.ts",
    "chars": 1134,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport * as common from \"../lib/util.ts\";\n\nvoid test(\"ge"
  },
  {
    "path": "test/xml-parser.ts",
    "chars": 1689,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport {\n  parseXmlDeclaration,\n  decodeEntities,\n  pars"
  },
  {
    "path": "test/yaml-tests.json",
    "chars": 14043,
    "preview": "[\n  [\n    {\n      \"name\": \"Mark McGwire\",\n      \"hr\": 65,\n      \"avg\": 0.278\n    },\n    {\n      \"name\": \"Sammy Sosa\",\n  "
  },
  {
    "path": "test/yaml.ts",
    "chars": 518,
    "preview": "import test from \"node:test\";\nimport assert from \"node:assert\";\nimport * as yaml from \"yaml\";\nimport { stringify } from "
  },
  {
    "path": "tsconfig.json",
    "chars": 577,
    "preview": "{\n  \"compilerOptions\": {\n    \"lib\": [\"ES2022\", \"dom\"],\n    \"module\": \"Preserve\",\n    \"moduleResolution\": \"bundler\",\n    "
  },
  {
    "path": "ui/app.ts",
    "chars": 4084,
    "preview": "import m, { RouteResolver } from \"mithril\";\nimport layout from \"./layout.tsx\";\nimport * as store from \"./store.ts\";\nimpo"
  },
  {
    "path": "ui/autocomplete-compnent.ts",
    "chars": 5440,
    "preview": "type AutocompleteCallback = (\n  value: string,\n  callback: (suggestions: { value: string; tip?: string }[]) => void,\n) ="
  },
  {
    "path": "ui/change-password-component.ts",
    "chars": 4380,
    "preview": "import { VnodeDOM, ClosureComponent } from \"mithril\";\nimport * as notifications from \"./notifications.ts\";\nimport { chan"
  },
  {
    "path": "ui/code-editor-component.ts",
    "chars": 2656,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { codeMirror } from \"./dynamic-l"
  },
  {
    "path": "ui/codemirror-loader.ts",
    "chars": 386,
    "preview": "export { EditorView, keymap, lineNumbers } from \"@codemirror/view\";\nexport { EditorState } from \"@codemirror/state\";\nexp"
  },
  {
    "path": "ui/components/all-parameters.ts",
    "chars": 7017,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as taskQueue from \"../task-qu"
  },
  {
    "path": "ui/components/container.ts",
    "chars": 2509,
    "preview": "import { Attributes, ClosureComponent } from \"mithril\";\nimport memoize from \"../../lib/common/memoize.ts\";\nimport Expres"
  },
  {
    "path": "ui/components/device-actions.ts",
    "chars": 3159,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as taskQueue from "
  },
  {
    "path": "ui/components/device-faults.ts",
    "chars": 4322,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as store from \"../"
  },
  {
    "path": "ui/components/device-link.ts",
    "chars": 1128,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport { evaluateExpression"
  },
  {
    "path": "ui/components/loading.ts",
    "chars": 1772,
    "preview": "import { VnodeDOM, ClosureComponent, Component } from \"mithril\";\n\nconst component: ClosureComponent = (): Component => {"
  },
  {
    "path": "ui/components/overview-dot.ts",
    "chars": 1297,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport { overview } from \"."
  },
  {
    "path": "ui/components/parameter-list.ts",
    "chars": 2009,
    "preview": "import { ClosureComponent, VnodeDOM } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport { QueryResponse, eval"
  },
  {
    "path": "ui/components/parameter-table.ts",
    "chars": 6033,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as taskQueue from \"../task-qu"
  },
  {
    "path": "ui/components/parameter.ts",
    "chars": 3497,
    "preview": "import { ClosureComponent, Component, VnodeDOM } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as taskQ"
  },
  {
    "path": "ui/components/ping.ts",
    "chars": 1641,
    "preview": "import { ClosureComponent, Component, VnodeDOM } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as store"
  },
  {
    "path": "ui/components/summon-button.ts",
    "chars": 3024,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as taskQueue from \"../task-qu"
  },
  {
    "path": "ui/components/tags.ts",
    "chars": 4772,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"../components.ts\";\nimport * as notifications from \"../not"
  },
  {
    "path": "ui/components.ts",
    "chars": 4619,
    "preview": "import m, {\n  Static,\n  Attributes,\n  Children,\n  ComponentTypes,\n  CommonAttributes,\n  ClosureComponent,\n  Vnode,\n} fro"
  },
  {
    "path": "ui/config-functions.ts",
    "chars": 3180,
    "preview": "interface Config {\n  _id: string;\n  value: string;\n}\n\ninterface Diff {\n  add: Config[];\n  remove: string[];\n}\n\nexport fu"
  },
  {
    "path": "ui/config-page.ts",
    "chars": 12297,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport * as store "
  },
  {
    "path": "ui/config.ts",
    "chars": 3805,
    "preview": "import Expression from \"../lib/common/expression.ts\";\nexport const configSnapshot = window.configSnapshot;\nexport const "
  },
  {
    "path": "ui/css/app.css",
    "chars": 4259,
    "preview": "@import \"tailwindcss\";\n@plugin \"@tailwindcss/forms\";\n\n@source inline(\"h-full bg-stone-100\");\n@source \"../../ui/**/*.{ts,"
  },
  {
    "path": "ui/datalist.ts",
    "chars": 1073,
    "preview": "import m, { ClosureComponent, Component, Vnode } from \"mithril\";\n\nconst elements: Map<string, Vnode> = new Map();\n\n// So"
  },
  {
    "path": "ui/device-page.ts",
    "chars": 2090,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { device as deviceConfig } from "
  },
  {
    "path": "ui/devices-page.ts",
    "chars": 12256,
    "preview": "import { ClosureComponent, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize as PAGE_SIZ"
  },
  {
    "path": "ui/drawer-component.ts",
    "chars": 20686,
    "preview": "import m, {\n  Children,\n  Child,\n  ClosureComponent,\n  Component,\n  VnodeDOM,\n} from \"mithril\";\nimport * as store from \""
  },
  {
    "path": "ui/dynamic-loader.ts",
    "chars": 1078,
    "preview": "import * as notifications from \"./notifications.ts\";\n\nexport let codeMirror: typeof import(\"./codemirror-loader\");\nexpor"
  },
  {
    "path": "ui/error-page.ts",
    "chars": 328,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"./components.ts\";\n\nexport const component: Clo"
  },
  {
    "path": "ui/faults-page.ts",
    "chars": 7146,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/files-page.ts",
    "chars": 11194,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/filter-component.ts",
    "chars": 5060,
    "preview": "import m, { ClosureComponent } from \"mithril\";\nimport memoize from \"../lib/common/memoize.ts\";\nimport Autocomplete from "
  },
  {
    "path": "ui/index-table-component.ts",
    "chars": 10131,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { icon } fr"
  },
  {
    "path": "ui/layout.tsx",
    "chars": 11814,
    "preview": "import m, { ClosureComponent } from \"mithril\";\nimport drawerComponent from \"./drawer-component.ts\";\nimport * as overlay "
  },
  {
    "path": "ui/login-page.tsx",
    "chars": 7986,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport * as store "
  },
  {
    "path": "ui/long-text-component.ts",
    "chars": 2018,
    "preview": "import m, { ClosureComponent, Component } from \"mithril\";\nimport * as overlay from \"./overlay.ts\";\n\nconst component: Clo"
  },
  {
    "path": "ui/notifications.ts",
    "chars": 749,
    "preview": "import m from \"mithril\";\n\ninterface Notification {\n  type: string;\n  message: string;\n  timestamp: number;\n  actions?: {"
  },
  {
    "path": "ui/overlay.ts",
    "chars": 2061,
    "preview": "import m, { Children } from \"mithril\";\nimport { dialog, dialogOverlay, icon } from \"./tailwind-utility-components.ts\";\n\n"
  },
  {
    "path": "ui/overview-page.ts",
    "chars": 2684,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { overview, rawConf } from \"./co"
  },
  {
    "path": "ui/permissions-page.ts",
    "chars": 15151,
    "preview": "import { Children, ClosureComponent, Component } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/pie-chart-component.ts",
    "chars": 4196,
    "preview": "import { ClosureComponent, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport Expression from \"../li"
  },
  {
    "path": "ui/presets-page.ts",
    "chars": 15363,
    "preview": "import { ClosureComponent, Component, Children, Vnode } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pa"
  },
  {
    "path": "ui/provisions-page.ts",
    "chars": 12066,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/put-form-component.ts",
    "chars": 8645,
    "preview": "import { VnodeDOM, ClosureComponent, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport codeEditorCo"
  },
  {
    "path": "ui/reactive-store.ts",
    "chars": 24446,
    "preview": "import m from \"mithril\";\nimport {\n  SignalBase,\n  ComputedSignal,\n  ComputedState,\n  Watcher,\n  registerDependency,\n} fr"
  },
  {
    "path": "ui/signals.ts",
    "chars": 12671,
    "preview": "// Reactive signals system based on the TC39 Signals proposal.\n// https://github.com/tc39/proposal-signals\n\nexport const"
  },
  {
    "path": "ui/skewed-date.ts",
    "chars": 354,
    "preview": "export function getClockSkew(): number {\n  return window.clockSkew;\n}\n\nexport class SkewedDate extends Date {\n  construc"
  },
  {
    "path": "ui/smart-query.ts",
    "chars": 9118,
    "preview": "import { filters } from \"./config.ts\";\nimport Expression from \"../lib/common/expression.ts\";\nimport { encodeTag } from \""
  },
  {
    "path": "ui/store.ts",
    "chars": 21578,
    "preview": "import m from \"mithril\";\nimport Expression from \"../lib/common/expression.ts\";\nimport Path from \"../lib/common/path.ts\";"
  },
  {
    "path": "ui/tailwind-utility-components.ts",
    "chars": 4747,
    "preview": "import m, {\n  ChildArrayOrPrimitive,\n  ClosureComponent,\n  mount,\n  Vnode,\n  VnodeDOM,\n} from \"mithril\";\nimport { ICONS_"
  },
  {
    "path": "ui/task-queue.ts",
    "chars": 2843,
    "preview": "import m from \"mithril\";\nimport * as store from \"./store.ts\";\nimport { Task } from \"../lib/types.ts\";\nimport * as notifi"
  },
  {
    "path": "ui/timeago.ts",
    "chars": 630,
    "preview": "const UNITS = {\n  year: 12 * 30 * 24 * 60 * 60 * 1000,\n  month: 30 * 24 * 60 * 60 * 1000,\n  day: 24 * 60 * 60 * 1000,\n  "
  },
  {
    "path": "ui/ui-config-component.ts",
    "chars": 4221,
    "preview": "import { ClosureComponent } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport * as store from \"./store.ts\";\nim"
  },
  {
    "path": "ui/users-page.ts",
    "chars": 13965,
    "preview": "import { Children, ClosureComponent, Component } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/views-bundle-placeholder.ts",
    "chars": 122,
    "preview": "declare module \"views-bundle\" {\n  const views: Record<string, (...args: unknown[]) => unknown>;\n  export default views;\n"
  },
  {
    "path": "ui/views-page.ts",
    "chars": 11795,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport * as config"
  },
  {
    "path": "ui/views.ts",
    "chars": 12403,
    "preview": "import m, { ClosureComponent, ChildArray } from \"mithril\";\nimport {\n  ComputedSignal,\n  ConstSignal,\n  SignalBase,\n  Sta"
  },
  {
    "path": "ui/virtual-parameters-page.ts",
    "chars": 12318,
    "preview": "import { ClosureComponent, Component, Children } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport { pageSize "
  },
  {
    "path": "ui/wizard-page.ts",
    "chars": 4348,
    "preview": "import { ClosureComponent, Component } from \"mithril\";\nimport { m } from \"./components.ts\";\nimport * as notifications fr"
  },
  {
    "path": "ui/yaml-loader.ts",
    "chars": 41,
    "preview": "export { parse, stringify } from \"yaml\";\n"
  }
]

About this extraction

This page contains the full source code of the zaidka/genieacs GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 187 files (1.6 MB), approximately 486.3k tokens, and a symbol index with 1209 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!