@nexgen-os/core 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +2 -2
  2. package/dist/address.d.ts +3 -62
  3. package/dist/connectors/activations.d.ts +63 -0
  4. package/dist/connectors/activations.js +73 -0
  5. package/dist/connectors/devices.d.ts +132 -0
  6. package/dist/connectors/devices.js +125 -0
  7. package/dist/connectors/interfaces.d.ts +2 -104
  8. package/dist/connectors/interfaces.js +4 -11
  9. package/dist/connectors/measured.d.ts +12 -0
  10. package/dist/connectors/measured.js +44 -0
  11. package/dist/connectors/meter-data.d.ts +2 -39
  12. package/dist/connectors/meter-data.js +3 -13
  13. package/dist/connectors/settlement.js +2 -2
  14. package/dist/db.d.ts +8 -0
  15. package/dist/db.js +32 -1
  16. package/dist/files/dsmr.d.ts +1 -0
  17. package/dist/files/dsmr.js +5 -0
  18. package/dist/files/enedis-r6x.d.ts +1 -32
  19. package/dist/files/enedis-r6x.js +5 -86
  20. package/dist/files/energy-bill.d.ts +4 -3
  21. package/dist/files/energy-bill.js +11 -6
  22. package/dist/files/evcc.d.ts +102 -0
  23. package/dist/files/evcc.js +76 -0
  24. package/dist/files/geojson.d.ts +41 -2
  25. package/dist/files/geojson.js +61 -1
  26. package/dist/files/index.d.ts +6 -0
  27. package/dist/files/index.js +6 -0
  28. package/dist/files/project-sheet.d.ts +44 -0
  29. package/dist/files/project-sheet.js +102 -0
  30. package/dist/files/project.d.ts +108 -0
  31. package/dist/files/project.js +104 -0
  32. package/dist/files/pvsol.d.ts +64 -0
  33. package/dist/files/pvsol.js +99 -0
  34. package/dist/files/weather-files.d.ts +3 -2
  35. package/dist/files/weather-files.js +11 -7
  36. package/dist/files/wesmart-db.d.ts +229 -0
  37. package/dist/files/wesmart-db.js +412 -0
  38. package/dist/gestures.d.ts +135 -0
  39. package/dist/gestures.js +99 -1
  40. package/dist/index.d.ts +4 -1
  41. package/dist/index.js +12 -0
  42. package/dist/refusal.d.ts +2 -11
  43. package/dist/refusal.js +5 -29
  44. package/dist/series.d.ts +11 -6
  45. package/dist/series.js +6 -1
  46. package/dist/time.d.ts +1 -6
  47. package/dist/time.js +4 -25
  48. package/package.json +13 -6
  49. package/schema/geojson-export.1.json +605 -0
@@ -50,6 +50,8 @@ export declare function getObject(db: Db, kind: string, id: string): Promise<Rec
50
50
  export declare function readSeries(db: Db, seriesId: string, from: string, to: string, step: string): Promise<import("./series.js").Bucket[]>;
51
51
  /** The value of a parameter for an object, through the cascade of defaults (`parameter_of()`). */
52
52
  export declare function parameterOf(db: Db, kind: string, id: string, attributeType: string, at?: string): Promise<unknown>;
53
+ /** Refuses `module_not_installed` when the module of that code is not installed. */
54
+ export declare function requireModule(db: Db, code: string): Promise<void>;
53
55
  /** The indicators of an object over a period (`kpis.of()`). */
54
56
  export declare function kpisOf(db: Db, kind: string, id: string, from: string, to: string): Promise<unknown[]>;
55
57
  /** The estimates of a module (`solar.estimates`, `battery.estimates`) about a participant or a device. */
@@ -125,6 +127,54 @@ export interface DeviceInput {
125
127
  export declare function installDevice(db: Db, d: DeviceInput): Promise<{
126
128
  id: string;
127
129
  }>;
130
+ /** The statuses a device moves to through the works and its life; `removed` is `retire_device()`'s. */
131
+ export type DeviceStatus = 'installed' | 'in_service' | 'out_of_service';
132
+ /**
133
+ * Moves a device on a day by a named transition (`set_device_status()`):
134
+ * planned to installed or in service, the day becoming its installation
135
+ * date; installed to in service, or out of service when it failed its
136
+ * commissioning; in service to out of service and back. Refuses
137
+ * `device_status_invalid`, `device_day_invalid`, `device_retired`,
138
+ * `device_not_found`, `not_allowed`. Returns where the device stands.
139
+ */
140
+ export declare function setDeviceStatus(db: Db, d: {
141
+ device_id: string;
142
+ status: DeviceStatus;
143
+ on?: string;
144
+ }): Promise<{
145
+ id: string;
146
+ status: string;
147
+ installation_date: string | null;
148
+ }>;
149
+ export interface PvArrayInput {
150
+ name: string;
151
+ /** Degrees clockwise from true north: 180 faces south. */
152
+ azimuth_deg: number;
153
+ /** Degrees from horizontal. */
154
+ tilt_deg: number;
155
+ /** The array's DC power; the system's when it has one array. */
156
+ kwp?: number;
157
+ mounting?: string;
158
+ }
159
+ export interface PvSystemInput {
160
+ participant_id: string;
161
+ name: string;
162
+ /** The DC power of the system, kWp. */
163
+ kwp: number;
164
+ arrays: PvArrayInput[];
165
+ installed_on?: string;
166
+ }
167
+ /**
168
+ * A PV system of a participant, described as the `solar` module reads it: a
169
+ * device of the core (`install_device()`, type `solar`), its row of
170
+ * `solar.devices` with its DC power, and one row of `solar.pv_arrays` per
171
+ * array with its own orientation. Its yield is then a computation of the
172
+ * module (`solar.yield`).
173
+ */
174
+ export declare function describePvSystem(db: Db, p: PvSystemInput): Promise<{
175
+ device_id: string;
176
+ arrays: string[];
177
+ }>;
128
178
  /**
129
179
  * The readings of one entity of a Home Assistant export, read by its format
130
180
  * library (`@nexgen-os/homeassistant`) and written through `store()` as a
@@ -162,6 +212,42 @@ export declare function moveAction(db: Db, actionId: string, toStatus: string, o
162
212
  id: string;
163
213
  status: string;
164
214
  }>;
215
+ /** An organisation; the person this acts as becomes its owner (`create_organisation()`). */
216
+ export declare function createOrganisation(db: Db, name: string): Promise<{
217
+ id: string;
218
+ }>;
219
+ /** Who is a member of an organisation, with their role: a person's id, never more of their account. */
220
+ export declare function listMembers(db: Db, organisationId: string): Promise<{
221
+ user_id: string;
222
+ role: string;
223
+ created_at: string;
224
+ }[]>;
225
+ /** Gives a person a role in an organisation (`add_member()`); viewer when no role is given. */
226
+ export declare function addMember(db: Db, m: {
227
+ organisation_id: string;
228
+ user_id: string;
229
+ role?: string;
230
+ }): Promise<{
231
+ organisation_id: string;
232
+ user_id: string;
233
+ role: string;
234
+ }>;
235
+ /** Changes a member's role (`set_member_role()`); an organisation keeps an owner. */
236
+ export declare function setMemberRole(db: Db, m: {
237
+ organisation_id: string;
238
+ user_id: string;
239
+ role: string;
240
+ }): Promise<{
241
+ organisation_id: string;
242
+ user_id: string;
243
+ role: string;
244
+ }>;
245
+ /** Removes a member (`remove_member()`); an organisation keeps an owner. */
246
+ export declare function removeMember(db: Db, organisationId: string, userId: string): Promise<{
247
+ organisation_id: string;
248
+ user_id: string;
249
+ removed: true;
250
+ }>;
165
251
  /** Issues a key on an organisation; the secret is in the answer once, and nowhere else. */
166
252
  export declare function createApiKey(db: Db, k: {
167
253
  organisation_id: string;
@@ -199,3 +285,52 @@ export type ComputationName = keyof Computations;
199
285
  export declare const COMPUTATIONS: ComputationName[];
200
286
  /** Runs a module's computation with the request it takes, after checking the module is installed. */
201
287
  export declare function compute(db: Db, computations: Computations, name: ComputationName, request: Record<string, unknown>): Promise<unknown>;
288
+ export interface PvYieldAtInput {
289
+ project_id: string;
290
+ /** The participant's name: the place, the roof, the client. */
291
+ name: string;
292
+ /** ISO 3166-1 alpha-2: the country is data of the place, never assumed. */
293
+ country: string;
294
+ lon: number;
295
+ lat: number;
296
+ time_zone?: string;
297
+ kwp: number;
298
+ /** Degrees clockwise from true north: 180 faces south. */
299
+ azimuth_deg: number;
300
+ tilt_deg: number;
301
+ /** A whole calendar year PVGIS covers; without it, the mean of every year it covers. */
302
+ year?: number;
303
+ /**
304
+ * The system loss the person says for this place, a fraction (0.025 for
305
+ * 2.5 %): set on the participant as `system_loss`, where any other
306
+ * surface reads it too; without it, the cascade answers (decision 0055).
307
+ */
308
+ system_loss?: number;
309
+ profileCode?: string;
310
+ }
311
+ /**
312
+ * The yield of a PV system at a point, in one gesture: the participant
313
+ * joins the project at that point, its PV system is described with one
314
+ * array (`describePvSystem()`), the `solar` module estimates its yield for
315
+ * the year asked, or as the mean of every year PVGIS covers (`solar.yield`),
316
+ * and it is read back by calendar month through `resample()`, in UTC, the
317
+ * mean of the years. The system loss is the place's: the one given is set
318
+ * on the participant, and the estimate says the level it was read at.
319
+ */
320
+ export declare function estimatePvYieldAt(db: Db, computations: Computations, p: PvYieldAtInput): Promise<{
321
+ participant_id: string;
322
+ device_id: string;
323
+ estimate_id: string;
324
+ annual_kwh: number;
325
+ kwh_per_kwp: number;
326
+ years: {
327
+ from: number;
328
+ to: number;
329
+ };
330
+ system_loss: Record<string, unknown> | null;
331
+ provenance: string;
332
+ months: {
333
+ month: number;
334
+ kwh: number;
335
+ }[];
336
+ }>;
package/dist/gestures.js CHANGED
@@ -93,7 +93,8 @@ export async function parameterOf(db, kind, id, attributeType, at) {
93
93
  const { value } = await first(db, 'select parameter_of($1, $2, $3, coalesce($4::timestamptz, now())) as value', [kindOf(kind), id, attributeType, at ?? null]);
94
94
  return value;
95
95
  }
96
- async function requireModule(db, code) {
96
+ /** Refuses `module_not_installed` when the module of that code is not installed. */
97
+ export async function requireModule(db, code) {
97
98
  const [found] = await rows(db, 'select 1 from modules where code = $1', [code]);
98
99
  if (found === undefined)
99
100
  throw new GestureError(`module_not_installed: the ${code} module is not installed on this database`);
@@ -166,6 +167,39 @@ export async function installDevice(db, d) {
166
167
  return first(db, `select install_device($1, $2, $3, $4, $5, $6, $7, coalesce($8, 1)) id`, [d.participant_id, d.device_type, d.name, d.product_id ?? null, d.rated_power_kw ?? null, d.installed_on ?? null,
167
168
  d.source_code ?? null, d.unit_count ?? null]);
168
169
  }
170
+ /**
171
+ * Moves a device on a day by a named transition (`set_device_status()`):
172
+ * planned to installed or in service, the day becoming its installation
173
+ * date; installed to in service, or out of service when it failed its
174
+ * commissioning; in service to out of service and back. Refuses
175
+ * `device_status_invalid`, `device_day_invalid`, `device_retired`,
176
+ * `device_not_found`, `not_allowed`. Returns where the device stands.
177
+ */
178
+ export async function setDeviceStatus(db, d) {
179
+ await db.query('select set_device_status($1, $2, coalesce($3::date, current_date))', [d.device_id, d.status, d.on ?? null]);
180
+ return first(db, 'select id::text, status, installation_date::text from devices where id = $1', [d.device_id]);
181
+ }
182
+ /**
183
+ * A PV system of a participant, described as the `solar` module reads it: a
184
+ * device of the core (`install_device()`, type `solar`), its row of
185
+ * `solar.devices` with its DC power, and one row of `solar.pv_arrays` per
186
+ * array with its own orientation. Its yield is then a computation of the
187
+ * module (`solar.yield`).
188
+ */
189
+ export async function describePvSystem(db, p) {
190
+ await requireModule(db, 'solar');
191
+ if (p.arrays.length === 0)
192
+ throw new GestureError('pv_array_required: a PV system has at least one array, with its azimuth and tilt');
193
+ const { id } = await installDevice(db, { participant_id: p.participant_id, device_type: 'solar', name: p.name, rated_power_kw: p.kwp, ...(p.installed_on ? { installed_on: p.installed_on } : {}) });
194
+ await db.query('insert into solar.devices (id, kwp_dc) values ($1, $2)', [id, p.kwp]);
195
+ const arrays = [];
196
+ for (const a of p.arrays) {
197
+ const row = await first(db, `insert into solar.pv_arrays (organisation_id, device_id, name, azimuth_deg, tilt_deg, mounting, kwp_dc)
198
+ select d.organisation_id, d.id, $2, $3, $4, $5, $6 from devices d where d.id = $1 returning id`, [id, a.name, a.azimuth_deg, a.tilt_deg, a.mounting ?? null, a.kwp ?? (p.arrays.length === 1 ? p.kwp : null)]);
199
+ arrays.push(row.id);
200
+ }
201
+ return { device_id: id, arrays };
202
+ }
169
203
  /**
170
204
  * The readings of one entity of a Home Assistant export, read by its format
171
205
  * library (`@nexgen-os/homeassistant`) and written through `store()` as a
@@ -206,6 +240,33 @@ export async function moveAction(db, actionId, toStatus, on) {
206
240
  return { id: actionId, status: toStatus };
207
241
  }
208
242
  // ---------------------------------------------------------------------------
243
+ // Organisations and their members — what follows an installation
244
+ // ---------------------------------------------------------------------------
245
+ /** An organisation; the person this acts as becomes its owner (`create_organisation()`). */
246
+ export async function createOrganisation(db, name) {
247
+ return first(db, 'select create_organisation($1) id', [name]);
248
+ }
249
+ /** Who is a member of an organisation, with their role: a person's id, never more of their account. */
250
+ export async function listMembers(db, organisationId) {
251
+ return rows(db, 'select user_id, role::text as role, created_at from organisation_members where organisation_id = $1 order by created_at, user_id', [organisationId]);
252
+ }
253
+ /** Gives a person a role in an organisation (`add_member()`); viewer when no role is given. */
254
+ export async function addMember(db, m) {
255
+ const role = m.role ?? 'viewer';
256
+ await db.query('select add_member($1, $2, $3::member_role)', [m.organisation_id, m.user_id, role]);
257
+ return { organisation_id: m.organisation_id, user_id: m.user_id, role };
258
+ }
259
+ /** Changes a member's role (`set_member_role()`); an organisation keeps an owner. */
260
+ export async function setMemberRole(db, m) {
261
+ await db.query('select set_member_role($1, $2, $3::member_role)', [m.organisation_id, m.user_id, m.role]);
262
+ return { organisation_id: m.organisation_id, user_id: m.user_id, role: m.role };
263
+ }
264
+ /** Removes a member (`remove_member()`); an organisation keeps an owner. */
265
+ export async function removeMember(db, organisationId, userId) {
266
+ await db.query('select remove_member($1, $2)', [organisationId, userId]);
267
+ return { organisation_id: organisationId, user_id: userId, removed: true };
268
+ }
269
+ // ---------------------------------------------------------------------------
209
270
  // Keys — an owner's gestures (decision 0046)
210
271
  // ---------------------------------------------------------------------------
211
272
  /** Issues a key on an organisation; the secret is in the answer once, and nowhere else. */
@@ -230,3 +291,40 @@ export async function compute(db, computations, name, request) {
230
291
  throw new GestureError(`computation_not_loaded: ${name} is the code of its module, and this surface was started without it`);
231
292
  return fn(db, request);
232
293
  }
294
+ /**
295
+ * The yield of a PV system at a point, in one gesture: the participant
296
+ * joins the project at that point, its PV system is described with one
297
+ * array (`describePvSystem()`), the `solar` module estimates its yield for
298
+ * the year asked, or as the mean of every year PVGIS covers (`solar.yield`),
299
+ * and it is read back by calendar month through `resample()`, in UTC, the
300
+ * mean of the years. The system loss is the place's: the one given is set
301
+ * on the participant, and the estimate says the level it was read at.
302
+ */
303
+ export async function estimatePvYieldAt(db, computations, p) {
304
+ const place = { country: p.country, geometry: { type: 'Point', coordinates: [p.lon, p.lat, 0] }, location_precision: 'rooftop' };
305
+ const participant = await addParticipant(db, { project_id: p.project_id, name: p.name, place, category: 'prosumer', ...(p.time_zone ? { time_zone: p.time_zone } : {}) });
306
+ if (p.system_loss !== undefined) {
307
+ await db.query(`select set_attribute('participant', $1, 'system_loss', $2::jsonb, null, null, 'said by the person', 'estimated')`, [participant.id, JSON.stringify(p.system_loss)]);
308
+ }
309
+ const system = await describePvSystem(db, {
310
+ participant_id: participant.id, name: 'PV system', kwp: p.kwp,
311
+ arrays: [{ name: 'Array 1', azimuth_deg: p.azimuth_deg, tilt_deg: p.tilt_deg }],
312
+ });
313
+ const estimate = await compute(db, computations, 'solar.yield', {
314
+ deviceId: system.device_id, ...(p.year !== undefined ? { years: { from: p.year, to: p.year } } : {}), ...(p.profileCode ? { profileCode: p.profileCode } : {}),
315
+ });
316
+ const { provenance, years, system_loss } = await first(db, `select provenance, inputs -> 'weather' -> 'years' years, inputs -> 'system_loss' system_loss from solar.estimates where id = $1`, [estimate.estimateId]);
317
+ const n = years.to - years.from + 1;
318
+ const byMonth = new Map();
319
+ for (const b of await resample(db, estimate.seriesId, `${years.from}-01-01T00:00:00Z`, `${years.to + 1}-01-01T00:00:00Z`, '1 month', { timeZone: 'UTC' })) {
320
+ if (b.value === null)
321
+ continue;
322
+ const month = Number(b.bucket.slice(5, 7));
323
+ byMonth.set(month, (byMonth.get(month) ?? 0) + Number(b.value));
324
+ }
325
+ const months = [...byMonth.entries()].sort(([a], [b]) => a - b).map(([month, kwh]) => ({ month, kwh: Math.round((kwh / n) * 10) / 10 }));
326
+ return {
327
+ participant_id: participant.id, device_id: system.device_id, estimate_id: estimate.estimateId,
328
+ annual_kwh: estimate.annualKwh, kwh_per_kwp: estimate.kwhPerKwp, years, system_loss, provenance, months,
329
+ };
330
+ }
package/dist/index.d.ts CHANGED
@@ -6,13 +6,16 @@
6
6
  * that write what a format library reads into the model, and the gestures the
7
7
  * command line and the MCP server share, each acting as a person (`session.ts`).
8
8
  */
9
- export type { Db } from './db.js';
9
+ export { atomically, type Db } from './db.js';
10
10
  export { orientation, polygonWkt, closed, type Point as Vertex } from './geometry.js';
11
11
  export * from './address.js';
12
12
  export * from './series.js';
13
13
  export * from './time.js';
14
14
  export * from './connectors/interfaces.js';
15
+ export * from './connectors/measured.js';
15
16
  export * from './connectors/meter-data.js';
17
+ export * from './connectors/devices.js';
18
+ export * from './connectors/activations.js';
16
19
  export * from './connectors/runner.js';
17
20
  export * from './connectors/pvlib.js';
18
21
  export * from './connectors/settlement.js';
package/dist/index.js CHANGED
@@ -1,9 +1,21 @@
1
+ /**
2
+ * `@nexgen-os/core` — what the code of Nexgen OS shares: the database seam,
3
+ * the standard shape of a place and the geocoder chain, the interfaces of
4
+ * the connectors, the series API (`store()` and the reads), the shared
5
+ * geometry, the runner of the program connectors in other languages, the importers
6
+ * that write what a format library reads into the model, and the gestures the
7
+ * command line and the MCP server share, each acting as a person (`session.ts`).
8
+ */
9
+ export { atomically } from './db.js';
1
10
  export { orientation, polygonWkt, closed } from './geometry.js';
2
11
  export * from './address.js';
3
12
  export * from './series.js';
4
13
  export * from './time.js';
5
14
  export * from './connectors/interfaces.js';
15
+ export * from './connectors/measured.js';
6
16
  export * from './connectors/meter-data.js';
17
+ export * from './connectors/devices.js';
18
+ export * from './connectors/activations.js';
7
19
  export * from './connectors/runner.js';
8
20
  export * from './connectors/pvlib.js';
9
21
  export * from './connectors/settlement.js';
package/dist/refusal.d.ts CHANGED
@@ -7,8 +7,8 @@
7
7
  * a name is and on what counts as the database saying no. The shape is Ekwo
8
8
  * OS's (`refusal.ts`), so an agent reads both projects the same way.
9
9
  */
10
- /** The name of a raise like `time_zone_required: the participant …`, or undefined. */
11
- export declare function refusalCode(message: string): string | undefined;
10
+ import { GestureError } from '@nexgen-os/connector';
11
+ export { GestureError, refusalCode } from '@nexgen-os/connector';
12
12
  /**
13
13
  * Whether an SQLSTATE is the database declining, as opposed to failing: a
14
14
  * raise of its own (`P0001`, `P0002`), a right the caller does not hold or a
@@ -16,14 +16,5 @@ export declare function refusalCode(message: string): string | undefined;
16
16
  * (`25006`), a constraint (class `23`).
17
17
  */
18
18
  export declare function isRefusalState(sqlstate: string | undefined): boolean;
19
- /** An error of a gesture: its name, its message, and the sentence that explains it when there is one. */
20
- export declare class GestureError extends Error {
21
- readonly code: string | undefined;
22
- readonly hint: string | undefined;
23
- constructor(message: string, options?: {
24
- code?: string;
25
- hint?: string;
26
- });
27
- }
28
19
  /** The error a surface reports for whatever the database or a gesture threw. */
29
20
  export declare function explain(error: unknown): GestureError;
package/dist/refusal.js CHANGED
@@ -7,11 +7,11 @@
7
7
  * a name is and on what counts as the database saying no. The shape is Ekwo
8
8
  * OS's (`refusal.ts`), so an agent reads both projects the same way.
9
9
  */
10
- /** The name of a raise like `time_zone_required: the participant …`, or undefined. */
11
- export function refusalCode(message) {
12
- const match = /^([a-z][a-z0-9_]{3,}):/.exec(message.trim());
13
- return match?.[1];
14
- }
10
+ import { GestureError, refusalCode } from '@nexgen-os/connector';
11
+ // The name of a refusal and the error that carries it live in
12
+ // `@nexgen-os/connector`, MIT, so that a connector refuses by name without
13
+ // the core (decision 0064); the core re-exports them.
14
+ export { GestureError, refusalCode } from '@nexgen-os/connector';
15
15
  /**
16
16
  * Whether an SQLSTATE is the database declining, as opposed to failing: a
17
17
  * raise of its own (`P0001`, `P0002`), a right the caller does not hold or a
@@ -25,30 +25,6 @@ export function isRefusalState(sqlstate) {
25
25
  return true;
26
26
  return sqlstate.startsWith('23');
27
27
  }
28
- /** What a few refusals mean, for whoever reads them next. An unknown name keeps its message. */
29
- const HINTS = {
30
- read_only: 'This connection reads. Writing is allowed by the person: NEXGEN_WRITE=1 in the environment they wrote, a key with write, or the scope energy.write on the connection they approved.',
31
- not_allowed: 'The person this acts as does not hold that right. Ask them, or an owner of the organisation.',
32
- api_key_revoked: 'The key was withdrawn. Its owner issues another one.',
33
- api_key_expired: 'The key expired. Its owner issues another one.',
34
- api_key_unknown: 'The key was not issued by this installation. Check the variable it was put in.',
35
- api_key_issuer_left: 'The person who issued the key left the organisation. An owner issues another one.',
36
- time_zone_required: 'The participant has no time zone: give it one before reading or storing daily values.',
37
- geocoder_not_configured: 'No geocoder was configured by the person. Give the place as a point, or ask them to configure one.',
38
- module_not_installed: 'The module is not installed on this database: nexgen-os init --modules adds it.',
39
- computation_not_loaded: 'This server was started without the code of the module that computes this. Start it from a checkout of the repository, where the modules are.',
40
- };
41
- /** An error of a gesture: its name, its message, and the sentence that explains it when there is one. */
42
- export class GestureError extends Error {
43
- code;
44
- hint;
45
- constructor(message, options = {}) {
46
- super(message);
47
- this.name = 'GestureError';
48
- this.code = options.code ?? refusalCode(message);
49
- this.hint = options.hint ?? (this.code === undefined ? undefined : HINTS[this.code]);
50
- }
51
- }
52
28
  /** The error a surface reports for whatever the database or a gesture threw. */
53
29
  export function explain(error) {
54
30
  if (error instanceof GestureError)
package/dist/series.d.ts CHANGED
@@ -1,10 +1,7 @@
1
+ import type { SeriesPoint } from '@nexgen-os/solar';
1
2
  import type { Db } from './db.js';
2
- /** One value at one instant, ISO 8601 with its offset, with its quality code (0 measured when absent; 3 missing). */
3
- export interface SeriesPoint {
4
- at: string;
5
- value: number;
6
- quality?: number;
7
- }
3
+ /** One value at one instant: the type the computations of `@nexgen-os/solar` read, one definition for both. */
4
+ export type { SeriesPoint };
8
5
  /** What names a series when it may not exist yet: the keys of `series_ensure()`. */
9
6
  export interface SeriesIdentity {
10
7
  /** The kind of the object observed: `organisation`, `project`, `participant`, `meter`, `device` or `series`. */
@@ -31,6 +28,10 @@ export interface Bucket {
31
28
  expected: number | null;
32
29
  quality: number | null;
33
30
  }
31
+ /** One bucket of several series added up (`aggregate()`): `series` is how many of them held a value in it. */
32
+ export interface AggregateBucket extends Bucket {
33
+ series: number;
34
+ }
34
35
  export interface Reading {
35
36
  at: string;
36
37
  value: number;
@@ -68,6 +69,10 @@ export declare function resample(db: Db, seriesId: string, from: string, to: str
68
69
  timeZone?: string | null;
69
70
  issuedBefore?: string | null;
70
71
  }): Promise<Bucket[]>;
72
+ /** Several series of one summable quantity added up on a regular step (`aggregate()`), each read as `resample()` reads it. */
73
+ export declare function aggregate(db: Db, seriesIds: string[], from: string, to: string, step: string, options?: {
74
+ timeZone?: string | null;
75
+ }): Promise<AggregateBucket[]>;
71
76
  /** The stored values themselves, in time order (`window()`): how a register's index is read. */
72
77
  export declare function window(db: Db, seriesId: string, from: string, to: string, limit?: number): Promise<Reading[]>;
73
78
  /** The latest value that is not missing of each series (`latest()`). */
package/dist/series.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Series: the SQL functions of the core, typed for TypeScript.
2
2
  //
3
3
  // One way to write (`store()`), one family of reads (`resample()`,
4
- // `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`,
4
+ // `aggregate()`, `window()`, `latest()`, `fill()`, `coverage()`, `forecastAt()`,
5
5
  // `exportRows()`), each a thin call of the function of the same name in
6
6
  // schema `nexgen` (decision 0031). Nothing here computes a bucket, converts
7
7
  // a unit or fills a gap: the database does, so that a page, a module, the
@@ -33,6 +33,11 @@ export async function resample(db, seriesId, from, to, step, options = {}) {
33
33
  const r = await db.query(`select bucket, value, samples, expected, quality from resample($1, $2::timestamptz, $3::timestamptz, $4::interval, $5, $6::timestamptz)`, [seriesId, from, to, step, options.timeZone ?? null, options.issuedBefore ?? null]);
34
34
  return r.rows.map((b) => ({ ...b, bucket: iso(b.bucket) }));
35
35
  }
36
+ /** Several series of one summable quantity added up on a regular step (`aggregate()`), each read as `resample()` reads it. */
37
+ export async function aggregate(db, seriesIds, from, to, step, options = {}) {
38
+ const r = await db.query(`select bucket, value, series, samples, expected, quality from aggregate($1::uuid[], $2::timestamptz, $3::timestamptz, $4::interval, $5)`, [seriesIds, from, to, step, options.timeZone ?? null]);
39
+ return r.rows.map((b) => ({ ...b, bucket: iso(b.bucket) }));
40
+ }
36
41
  /** The stored values themselves, in time order (`window()`): how a register's index is read. */
37
42
  export async function window(db, seriesId, from, to, limit = 100_000) {
38
43
  const r = await db.query(`select at, value, quality from nexgen.window($1, $2::timestamptz, $3::timestamptz, $4)`, [seriesId, from, to, limit]);
package/dist/time.d.ts CHANGED
@@ -1,6 +1 @@
1
- /**
2
- * Offset of a time zone from UTC at an instant, minutes east (Brussels in
3
- * winter: 60). Throws `time_zone_unknown` for a name that is not an IANA
4
- * time zone.
5
- */
6
- export declare function offsetAt(timeZone: string, ms: number): number;
1
+ export { offsetAt } from '@nexgen-os/solar';
package/dist/time.js CHANGED
@@ -1,25 +1,4 @@
1
- // Time zones, read through the platform's `Intl`: what a module needs to cut
2
- // days, weeks and months in a participant's own time, without a dependency.
3
- const formatters = new Map();
4
- /**
5
- * Offset of a time zone from UTC at an instant, minutes east (Brussels in
6
- * winter: 60). Throws `time_zone_unknown` for a name that is not an IANA
7
- * time zone.
8
- */
9
- export function offsetAt(timeZone, ms) {
10
- let format = formatters.get(timeZone);
11
- if (!format) {
12
- try {
13
- format = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' });
14
- }
15
- catch {
16
- throw new Error(`time_zone_unknown: ${timeZone} is not an IANA time zone`);
17
- }
18
- formatters.set(timeZone, format);
19
- }
20
- const name = format.formatToParts(new Date(ms)).find((p) => p.type === 'timeZoneName')?.value ?? 'GMT';
21
- const m = /^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(name);
22
- if (!m)
23
- throw new Error(`time_zone_unknown: ${timeZone} gives the offset ${name}`);
24
- return m[1] ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : 0;
25
- }
1
+ // Time zones: `offsetAt()` lives with the computations of `@nexgen-os/solar`
2
+ // (MIT, decision 0063), which cut local days and years without the core; the
3
+ // core reads the same function, so that there is one implementation.
4
+ export { offsetAt } from '@nexgen-os/solar';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexgen-os/core",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "What the code of Nexgen OS shares: the database seam, the standard place and the geocoder chain, the series API, the connector interfaces, the engine glue, and the importers and exporters of the file formats.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -17,6 +17,7 @@
17
17
  },
18
18
  "files": [
19
19
  "dist",
20
+ "schema",
20
21
  "README.md",
21
22
  "LICENSE"
22
23
  ],
@@ -32,11 +33,17 @@
32
33
  "build": "tsc -p tsconfig.build.json && node ../../scripts/copy-license.mjs"
33
34
  },
34
35
  "dependencies": {
35
- "@nexgen-os/enedis-r6x": "^0.4.0",
36
- "@nexgen-os/energy-bill": "^0.4.0",
37
- "@nexgen-os/geojson": "^0.4.0",
38
- "@nexgen-os/homeassistant": "^0.4.0",
39
- "@nexgen-os/weather-files": "^0.4.0"
36
+ "@nexgen-os/connector": "^0.6.0",
37
+ "@nexgen-os/dsmr": "^0.6.0",
38
+ "@nexgen-os/enedis-r6x": "^0.6.0",
39
+ "@nexgen-os/energy-bill": "^0.6.0",
40
+ "@nexgen-os/evcc": "^0.6.0",
41
+ "@nexgen-os/geojson": "^0.6.0",
42
+ "@nexgen-os/homeassistant": "^0.6.0",
43
+ "@nexgen-os/project-sheet": "^0.6.0",
44
+ "@nexgen-os/pvsol": "^0.6.0",
45
+ "@nexgen-os/solar": "^0.6.0",
46
+ "@nexgen-os/weather-files": "^0.6.0"
40
47
  },
41
48
  "peerDependencies": {
42
49
  "pg": "^8.23.1"