@tech4good/platform-logging 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-alpha.0
4
+
5
+ - Extract injector-owned runtime logging from generated applications.
6
+ - Provide scoped loggers, namespace controls and configurable structured output.
7
+ - Support opt-in browser persistence and DevTools controls without requiring a browser.
8
+ - Replace platform-data's dedicated logging hook with the shared `data` namespace.
package/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # @tech4good/platform-logging
2
+
3
+ Shared runtime logging for Angular 21 applications and platform packages. Owns
4
+ namespace filtering, configurable output, optional browser persistence and
5
+ DevTools controls. No dependency on platform-data, Firebase, Material or tooling.
6
+ Initial version: `0.1.0-alpha.0`, prepared locally; nothing publishes automatically.
7
+
8
+ ## Configure once in the app
9
+
10
+ ```ts
11
+ import { providePlatformLogging } from '@tech4good/platform-logging';
12
+
13
+ // In appConfig.providers, using your app's environment:
14
+ providePlatformLogging({
15
+ enabled: ['data', 'auth'],
16
+ persist: !environment.production,
17
+ exposeDebugConsole: !environment.production,
18
+ });
19
+ ```
20
+
21
+ Without configuration, logging is disabled and touches no storage/browser globals.
22
+ Generated apps opt in to persistence/DevTools only in development, and start with
23
+ output disabled unless saved settings enable it. `enabled: true` enables every
24
+ namespace. All levels (`log`, `warn`, `error`) follow the namespace filter.
25
+
26
+ `platform-data` uses the `data` namespace. There is no `DATA_LOGGER` provider or
27
+ logging option in `providePlatformData`; the logging provider configures it all.
28
+
29
+ ## Request a logger
30
+
31
+ ```ts
32
+ import { Injectable } from '@angular/core';
33
+ import { injectLogger } from '@tech4good/platform-logging';
34
+
35
+ @Injectable({ providedIn: 'root' })
36
+ export class ExampleService {
37
+ private readonly logger = injectLogger('auth');
38
+
39
+ signedIn() {
40
+ this.logger.log('Session ready');
41
+ }
42
+ }
43
+ ```
44
+
45
+ Call `injectLogger` in an Angular injection context (field initializer/provider
46
+ factory). Retain the returned `Logger` for later callbacks and async methods.
47
+ Non-injectable helpers receive a `Logger` explicitly; `NOOP_LOGGER` supplies an
48
+ optional silent default. `LoggingService.scoped(namespace)` is also available.
49
+
50
+ Namespaces match exactly: `data` does not enable `database` or `data.cache`.
51
+ Commas and `*`, `true`, `false` are reserved filter values.
52
+
53
+ ## Runtime controls
54
+
55
+ Inject `LoggingService` or use the optional DevTools handle:
56
+
57
+ ```js
58
+ debugLogger.enable(); // All namespaces
59
+ debugLogger.enable('data,auth'); // Only these names
60
+ debugLogger.disable();
61
+ debugLogger.toggle(); // Disabled <-> all namespaces
62
+ debugLogger.isEnabled('data');
63
+ ```
64
+
65
+ Existing loggers follow changes immediately. State belongs to the Angular
66
+ injector, not a module-global reference. An explicitly configured child injector
67
+ gets its own logger; otherwise it inherits its parent normally. Destroyed
68
+ instances stop emitting.
69
+
70
+ With `persist: true`, settings are read on initialization and saved by these
71
+ controls under localStorage's `debug_logs` key. Use `storageKey` to separate apps
72
+ sharing an origin. Saved settings override configured defaults. Disable saves
73
+ `false`, so that choice survives an enabled default. Storage failure falls back
74
+ to in-memory operation; server rendering requires no browser globals. Manual
75
+ storage edits take effect on next initialization.
76
+
77
+ `exposeDebugConsole` eagerly installs `window.debugLogger` and removes its own
78
+ handle on injector destruction. An existing handle is left untouched if multiple
79
+ apps share a page. Internal loggers never use that handle to find their instance.
80
+
81
+ ## Custom output and tests
82
+
83
+ The default sink writes `[namespace]` followed by the original arguments to the
84
+ matching console method. Supply a `LogSink` to capture structured events:
85
+
86
+ ```ts
87
+ const entries: unknown[] = [];
88
+ providePlatformLogging({
89
+ enabled: ['data'],
90
+ sink: entry => { entries.push(entry); }, // { namespace, level, values }
91
+ });
92
+ ```
93
+
94
+ The app owns output routing, redaction and delivery. A sink receives only enabled
95
+ messages and returns synchronously. It must handle failures of any async delivery
96
+ it starts. Synchronous sink errors are contained so diagnostics cannot break the
97
+ operation being logged. The app's analytics event service remains separate.
98
+
99
+ ## Migration
100
+
101
+ 1. Replace local `core/logging/logging.service` imports with direct package imports.
102
+ Remove the copied service/tests after updating callers; no reexports are needed.
103
+ 2. Replace global `getLogger('query')` lookups with `injectLogger('data')` in an
104
+ injection context. Other app namespaces can retain their names. Pass loggers
105
+ explicitly to non-injectable helpers.
106
+ 3. Remove `DATA_LOGGER` providers and `providePlatformData({ logger: ... })`.
107
+ Configure `providePlatformLogging` once. Replace `DataLogger` with `Logger`.
108
+ 4. Replace tests spying on `LoggingService.logForNamespace` with a custom sink.
109
+ 5. Update saved `query` filters to `data`, e.g. `debugLogger.enable('data')`.
110
+ All-namespace values (`true`, `*`, empty string) still work. New generated apps
111
+ disable persistence/DevTools in production; apps can choose their own policy.
112
+
113
+ ## Build, test and try locally
114
+
115
+ Use Node.js 22 or later. From the package repository root:
116
+
117
+ ```bash
118
+ npm install
119
+ npm run test:logging
120
+ npm run pack:logging
121
+ ```
122
+
123
+ This builds Angular Package Format output in `packages/logging/dist`, tests the
124
+ built public API, and creates `tech4good-platform-logging-0.1.0-alpha.0.tgz`.
125
+ The source manifest points at local build output for workspace resolution;
126
+ published consumers use ng-packagr's generated exports.
127
+
128
+ To try data and logging together before publishing:
129
+
130
+ ```bash
131
+ # Package repository
132
+ npm run pack:logging
133
+ npm run pack:data
134
+
135
+ # Consumer repository: install both snapshots together to satisfy unpublished peers.
136
+ npm install --save-exact /path/to/tech4good-platform-logging-0.1.0-alpha.0.tgz /path/to/tech4good-platform-data-0.1.0-alpha.0.tgz
137
+ ```
138
+
139
+ Rebuild/repack/reinstall after edits. Keep local tarball paths out of release
140
+ commits. Logging-only consumers need only the logging tarball.
141
+
142
+ ## Release and publish
143
+
144
+ For the first publication, retain `0.1.0-alpha.0`. From the repository root:
145
+
146
+ ```bash
147
+ npm test
148
+ npm run build:logging
149
+ npm pack ./packages/logging/dist --dry-run
150
+ npm login
151
+ npm publish ./packages/logging/dist --access public --tag alpha
152
+ npm view @tech4good/platform-logging@0.1.0-alpha.0 version
153
+ ```
154
+
155
+ Build before publishing the **built directory**; a guard rejects publishing the
156
+ source workspace. Publish logging before the data/schematics versions requiring it.
157
+
158
+ For the next alpha, choose an unused version and update the package version, the
159
+ logging peer in `packages/data/package.json`, the generated dependency in
160
+ `src/ng-add/files/package.json.template`, and the workspace lockfile:
161
+
162
+ ```bash
163
+ npm version 0.1.0-alpha.1 --workspace @tech4good/platform-logging --no-git-tag-version --ignore-scripts
164
+ # Update dependent manifests described above, then:
165
+ npm install
166
+ npm test
167
+ npm run build:logging
168
+ npm pack ./packages/logging/dist --dry-run
169
+ ```
170
+
171
+ Review/commit the intended changes, then publish the selected version. Already
172
+ published data/schematics packages need new versions when their logging
173
+ requirement changes.
@@ -0,0 +1,176 @@
1
+ import * as i0 from '@angular/core';
2
+ import { InjectionToken, inject, DestroyRef, signal, Injectable, makeEnvironmentProviders, provideEnvironmentInitializer } from '@angular/core';
3
+
4
+ /** Useful when constructing non-injectable helpers without diagnostic output. */
5
+ const NOOP_LOGGER = Object.freeze({ log() { }, warn() { }, error() { } });
6
+ /** Default browser/server console destination, retaining namespace and argument structure. */
7
+ const CONSOLE_LOG_SINK = ({ namespace, level, values }) => {
8
+ console[level](`[${namespace}]`, ...values);
9
+ };
10
+
11
+ // Internal configuration token. Consumers configure it through providePlatformLogging.
12
+ const PLATFORM_LOGGING_OPTIONS = new InjectionToken('PlatformLoggingOptions');
13
+ function selection(value) {
14
+ if (typeof value === 'boolean')
15
+ return value;
16
+ if (typeof value === 'string' && value === 'false')
17
+ return false;
18
+ const names = (typeof value === 'string' ? value.split(',') : [...value]).map(name => name.trim()).filter(Boolean);
19
+ if (typeof value === 'string' && names.length === 0 || names.includes('*') || names.includes('true'))
20
+ return true;
21
+ return names.length ? [...new Set(names)] : false;
22
+ }
23
+ /**
24
+ * Injector-owned logging state shared by scoped loggers in that injector.
25
+ * Without configuration it is silent and touches no browser storage/global.
26
+ * Loggers capture this instance, so creating a second app or test cannot redirect
27
+ * an existing logger. Browser persistence and DevTools exposure are optional.
28
+ *
29
+ * With exposeDebugConsole: true in providePlatformLogging, the browser's DevTools
30
+ * console can control logging at runtime:
31
+ * - Enable all logs: debugLogger.enable()
32
+ * - Enable specific namespaces: debugLogger.enable('data,auth')
33
+ * - Disable logs: debugLogger.disable()
34
+ * - Toggle logs: debugLogger.toggle()
35
+ * Set persist: true as well if those choices should survive a page reload.
36
+ */
37
+ class LoggingService {
38
+ options = inject(PLATFORM_LOGGING_OPTIONS, { optional: true }) ?? {};
39
+ destroyRef = inject(DestroyRef);
40
+ namespaces = signal(selection(this.options.enabled ?? false), ...(ngDevMode ? [{ debugName: "namespaces" }] : /* istanbul ignore next */ []));
41
+ sink = this.options.sink ?? CONSOLE_LOG_SINK;
42
+ storageKey = this.options.storageKey ?? 'debug_logs';
43
+ destroyed = false;
44
+ constructor() {
45
+ if (this.options.persist) {
46
+ try {
47
+ const saved = typeof window === 'undefined' ? null : window.localStorage.getItem(this.storageKey);
48
+ if (saved !== null)
49
+ this.namespaces.set(selection(saved));
50
+ }
51
+ catch {
52
+ // Browser storage can be unavailable; in-memory configuration still works.
53
+ }
54
+ }
55
+ this.destroyRef.onDestroy(() => { this.destroyed = true; });
56
+ this.exposeDebugConsole();
57
+ }
58
+ /**
59
+ * Get a logger usable after leaving an injection context, including callbacks.
60
+ * A namespace is an exact category name, such as data, auth or onboarding.
61
+ * Existing scoped loggers observe enable/disable changes without being recreated.
62
+ */
63
+ scoped(namespace) {
64
+ if (!namespace || namespace.trim() !== namespace || namespace.includes(',') || ['*', 'true', 'false'].includes(namespace)) {
65
+ throw new Error('Logger namespaces must be nonempty names without commas or reserved filter values.');
66
+ }
67
+ return {
68
+ log: (...values) => this.write(namespace, 'log', values),
69
+ warn: (...values) => this.write(namespace, 'warn', values),
70
+ error: (...values) => this.write(namespace, 'error', values),
71
+ };
72
+ }
73
+ /** Enable all output, or exact comma-separated/array namespace names. */
74
+ enable(namespaces = '*') {
75
+ this.namespaces.set(selection(namespaces));
76
+ this.persist();
77
+ }
78
+ /** Disable every level, including warnings/errors, and persist that choice when enabled. */
79
+ disable() {
80
+ this.namespaces.set(false);
81
+ this.persist();
82
+ }
83
+ /** Toggle between disabled and all namespaces. */
84
+ toggle() { if (this.isEnabled())
85
+ this.disable();
86
+ else
87
+ this.enable(); }
88
+ /** Reactive read of global enablement, or whether a particular namespace is enabled. */
89
+ isEnabled(namespace) {
90
+ if (this.destroyed)
91
+ return false;
92
+ const current = this.namespaces();
93
+ return current === true || Array.isArray(current) && (namespace === undefined || current.includes(namespace));
94
+ }
95
+ write(namespace, level, values) {
96
+ if (!this.isEnabled(namespace))
97
+ return;
98
+ try {
99
+ this.sink({ namespace, level, values });
100
+ }
101
+ catch {
102
+ // Diagnostics are best effort. A failing sink must not fail the app operation
103
+ // being logged, or recursively call the same failing destination.
104
+ }
105
+ }
106
+ persist() {
107
+ if (!this.options.persist || this.destroyed)
108
+ return;
109
+ try {
110
+ if (typeof window === 'undefined')
111
+ return;
112
+ const current = this.namespaces();
113
+ window.localStorage.setItem(this.storageKey, typeof current === 'boolean' ? String(current) : current.join(','));
114
+ }
115
+ catch {
116
+ // Retain the in-memory setting even if storage is denied or full.
117
+ }
118
+ }
119
+ exposeDebugConsole() {
120
+ if (!this.options.exposeDebugConsole || typeof window === 'undefined')
121
+ return;
122
+ try {
123
+ // This is only a debugging handle; scoped loggers never read it. Do not
124
+ // replace another app's handle, and remove ours when this injector dies.
125
+ if ('debugLogger' in window)
126
+ return;
127
+ const target = window;
128
+ Object.defineProperty(target, 'debugLogger', { value: this, configurable: true, writable: true });
129
+ this.destroyRef.onDestroy(() => {
130
+ if (target['debugLogger'] === this)
131
+ delete target['debugLogger'];
132
+ });
133
+ }
134
+ catch {
135
+ // Nonextensible browser globals must not prevent app initialization.
136
+ }
137
+ }
138
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: LoggingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
139
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: LoggingService, providedIn: 'root' });
140
+ }
141
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: LoggingService, decorators: [{
142
+ type: Injectable,
143
+ args: [{ providedIn: 'root' }]
144
+ }], ctorParameters: () => [] });
145
+ /**
146
+ * Request a scoped logger in an Angular injection context, such as a field
147
+ * initializer or provider factory. Retain it for later event/async callbacks.
148
+ * @example
149
+ * private readonly logger = injectLogger('auth');
150
+ */
151
+ function injectLogger(namespace) {
152
+ return inject(LoggingService).scoped(namespace);
153
+ }
154
+
155
+ /**
156
+ * Configure logging once at the application's root. Supplying this provider in
157
+ * another environment injector creates independent logging state there.
158
+ * Initialization eagerly restores settings/exposes optional DevTools controls,
159
+ * even before any feature requests a logger. All browser features are opt-in.
160
+ */
161
+ function providePlatformLogging(options = {}) {
162
+ return makeEnvironmentProviders([
163
+ { provide: PLATFORM_LOGGING_OPTIONS, useValue: options },
164
+ LoggingService,
165
+ provideEnvironmentInitializer(() => { inject(LoggingService); }),
166
+ ]);
167
+ }
168
+
169
+ /** Shared runtime logging. No data, Firebase, Material or Node tooling dependency. */
170
+
171
+ /**
172
+ * Generated bundle index. Do not edit.
173
+ */
174
+
175
+ export { CONSOLE_LOG_SINK, LoggingService, NOOP_LOGGER, injectLogger, providePlatformLogging };
176
+ //# sourceMappingURL=tech4good-platform-logging.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tech4good-platform-logging.mjs","sources":["../../src/logger.ts","../../src/logging.service.ts","../../src/providers.ts","../../src/public-api.ts","../../src/tech4good-platform-logging.ts"],"sourcesContent":["/** A namespace-bound logger. Arguments retain their original values for the output sink. */\nexport interface Logger {\n log(...values: unknown[]): void;\n warn(...values: unknown[]): void;\n error(...values: unknown[]): void;\n}\n\nexport type LogLevel = 'log' | 'warn' | 'error';\n\n/** One accepted log call, after namespace filtering. No serialization is imposed. */\nexport interface LogEntry {\n readonly namespace: string;\n readonly level: LogLevel;\n readonly values: readonly unknown[];\n}\n\n/** Synchronous destination for messages. Applications can queue remote delivery here. */\nexport type LogSink = (entry: LogEntry) => void;\n\n/** Useful when constructing non-injectable helpers without diagnostic output. */\nexport const NOOP_LOGGER: Logger = Object.freeze({ log() {}, warn() {}, error() {} });\n\n/** Default browser/server console destination, retaining namespace and argument structure. */\nexport const CONSOLE_LOG_SINK: LogSink = ({ namespace, level, values }) => {\n console[level](`[${namespace}]`, ...values);\n};\n","import { DestroyRef, Injectable, InjectionToken, inject, signal } from '@angular/core';\nimport { CONSOLE_LOG_SINK, Logger, LogLevel, LogSink } from './logger';\n\n/** Configuration belongs to the application; the package never imports app environments. */\nexport interface PlatformLoggingOptions {\n /** False by default; true enables all namespaces, an array enables exact names. */\n enabled?: boolean | readonly string[];\n /** Replace console output with an application-owned destination. */\n sink?: LogSink;\n /** Restore/save namespace settings in browser localStorage. Off by default. */\n persist?: boolean;\n /** Use separate keys for apps sharing an origin. Defaults to debug_logs. */\n storageKey?: string;\n /** Opt in to window.debugLogger controls; normally enabled only in development. */\n exposeDebugConsole?: boolean;\n}\n\n// Internal configuration token. Consumers configure it through providePlatformLogging.\nexport const PLATFORM_LOGGING_OPTIONS = new InjectionToken<PlatformLoggingOptions>('PlatformLoggingOptions');\n\ntype NamespaceSelection = boolean | readonly string[];\n\nfunction selection(value: boolean | string | readonly string[]): NamespaceSelection {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'string' && value === 'false') return false;\n const names = (typeof value === 'string' ? value.split(',') : [...value]).map(name => name.trim()).filter(Boolean);\n if (typeof value === 'string' && names.length === 0 || names.includes('*') || names.includes('true')) return true;\n return names.length ? [...new Set(names)] : false;\n}\n\n/**\n * Injector-owned logging state shared by scoped loggers in that injector.\n * Without configuration it is silent and touches no browser storage/global.\n * Loggers capture this instance, so creating a second app or test cannot redirect\n * an existing logger. Browser persistence and DevTools exposure are optional.\n *\n * With exposeDebugConsole: true in providePlatformLogging, the browser's DevTools\n * console can control logging at runtime:\n * - Enable all logs: debugLogger.enable()\n * - Enable specific namespaces: debugLogger.enable('data,auth')\n * - Disable logs: debugLogger.disable()\n * - Toggle logs: debugLogger.toggle()\n * Set persist: true as well if those choices should survive a page reload.\n */\n@Injectable({ providedIn: 'root' })\nexport class LoggingService {\n private readonly options = inject(PLATFORM_LOGGING_OPTIONS, { optional: true }) ?? {};\n private readonly destroyRef = inject(DestroyRef);\n private readonly namespaces = signal<NamespaceSelection>(selection(this.options.enabled ?? false));\n private readonly sink = this.options.sink ?? CONSOLE_LOG_SINK;\n private readonly storageKey = this.options.storageKey ?? 'debug_logs';\n private destroyed = false;\n\n constructor() {\n if (this.options.persist) {\n try {\n const saved = typeof window === 'undefined' ? null : window.localStorage.getItem(this.storageKey);\n if (saved !== null) this.namespaces.set(selection(saved));\n } catch {\n // Browser storage can be unavailable; in-memory configuration still works.\n }\n }\n this.destroyRef.onDestroy(() => { this.destroyed = true; });\n this.exposeDebugConsole();\n }\n\n /**\n * Get a logger usable after leaving an injection context, including callbacks.\n * A namespace is an exact category name, such as data, auth or onboarding.\n * Existing scoped loggers observe enable/disable changes without being recreated.\n */\n scoped(namespace: string): Logger {\n if (!namespace || namespace.trim() !== namespace || namespace.includes(',') || ['*', 'true', 'false'].includes(namespace)) {\n throw new Error('Logger namespaces must be nonempty names without commas or reserved filter values.');\n }\n return {\n log: (...values) => this.write(namespace, 'log', values),\n warn: (...values) => this.write(namespace, 'warn', values),\n error: (...values) => this.write(namespace, 'error', values),\n };\n }\n\n /** Enable all output, or exact comma-separated/array namespace names. */\n enable(namespaces: string | readonly string[] = '*'): void {\n this.namespaces.set(selection(namespaces));\n this.persist();\n }\n\n /** Disable every level, including warnings/errors, and persist that choice when enabled. */\n disable(): void {\n this.namespaces.set(false);\n this.persist();\n }\n\n /** Toggle between disabled and all namespaces. */\n toggle(): void { if (this.isEnabled()) this.disable(); else this.enable(); }\n\n /** Reactive read of global enablement, or whether a particular namespace is enabled. */\n isEnabled(namespace?: string): boolean {\n if (this.destroyed) return false;\n const current = this.namespaces();\n return current === true || Array.isArray(current) && (namespace === undefined || current.includes(namespace));\n }\n\n private write(namespace: string, level: LogLevel, values: unknown[]): void {\n if (!this.isEnabled(namespace)) return;\n try { this.sink({ namespace, level, values }); }\n catch {\n // Diagnostics are best effort. A failing sink must not fail the app operation\n // being logged, or recursively call the same failing destination.\n }\n }\n\n private persist(): void {\n if (!this.options.persist || this.destroyed) return;\n try {\n if (typeof window === 'undefined') return;\n const current = this.namespaces();\n window.localStorage.setItem(this.storageKey, typeof current === 'boolean' ? String(current) : current.join(','));\n } catch {\n // Retain the in-memory setting even if storage is denied or full.\n }\n }\n\n private exposeDebugConsole(): void {\n if (!this.options.exposeDebugConsole || typeof window === 'undefined') return;\n try {\n // This is only a debugging handle; scoped loggers never read it. Do not\n // replace another app's handle, and remove ours when this injector dies.\n if ('debugLogger' in window) return;\n const target = window as unknown as Record<string, unknown>;\n Object.defineProperty(target, 'debugLogger', { value: this, configurable: true, writable: true });\n this.destroyRef.onDestroy(() => {\n if (target['debugLogger'] === this) delete target['debugLogger'];\n });\n } catch {\n // Nonextensible browser globals must not prevent app initialization.\n }\n }\n}\n\n/**\n * Request a scoped logger in an Angular injection context, such as a field\n * initializer or provider factory. Retain it for later event/async callbacks.\n * @example\n * private readonly logger = injectLogger('auth');\n */\nexport function injectLogger(namespace: string): Logger {\n return inject(LoggingService).scoped(namespace);\n}\n","import { EnvironmentProviders, inject, makeEnvironmentProviders, provideEnvironmentInitializer } from '@angular/core';\nimport { LoggingService, PLATFORM_LOGGING_OPTIONS, PlatformLoggingOptions } from './logging.service';\n\n/**\n * Configure logging once at the application's root. Supplying this provider in\n * another environment injector creates independent logging state there.\n * Initialization eagerly restores settings/exposes optional DevTools controls,\n * even before any feature requests a logger. All browser features are opt-in.\n */\nexport function providePlatformLogging(options: PlatformLoggingOptions = {}): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: PLATFORM_LOGGING_OPTIONS, useValue: options },\n LoggingService,\n provideEnvironmentInitializer(() => { inject(LoggingService); }),\n ]);\n}\n","/** Shared runtime logging. No data, Firebase, Material or Node tooling dependency. */\nexport * from './logger';\nexport { LoggingService, injectLogger } from './logging.service';\nexport type { PlatformLoggingOptions } from './logging.service';\nexport { providePlatformLogging } from './providers';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;AAmBA;MACa,WAAW,GAAW,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,GAAA,EAAI,CAAC,EAAE,IAAI,KAAI,CAAC,EAAE,KAAK,GAAA,EAAI,CAAC,EAAE;AAEpF;AACO,MAAM,gBAAgB,GAAY,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,KAAI;IACxE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA,CAAA,EAAI,SAAS,CAAA,CAAA,CAAG,EAAE,GAAG,MAAM,CAAC;AAC7C;;ACRA;AACO,MAAM,wBAAwB,GAAG,IAAI,cAAc,CAAyB,wBAAwB,CAAC;AAI5G,SAAS,SAAS,CAAC,KAA2C,EAAA;IAC5D,IAAI,OAAO,KAAK,KAAK,SAAS;AAAE,QAAA,OAAO,KAAK;AAC5C,IAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,OAAO;AAAE,QAAA,OAAO,KAAK;AAChE,IAAA,MAAM,KAAK,GAAG,CAAC,OAAO,KAAK,KAAK,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,EAAE,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;IAClH,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,KAAK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ACJ;AAAE,QAAA,MAAM;;QAER;IACF;wGA7FW,cAAc,EAAA,IAAA,EAAA,EAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,UAAA,EAAA,CAAA;AAAd,IAAA,OAAA,KAAA,GAAA,EAAA,CAAA,qBAAA,CAAA,EAAA,UAAA,EAAA,QAAA,EAAA,OAAA,EAAA,SAAA,EAAA,QAAA,EAAA,EAAA,EAAA,IAAA,EAAA,cAAc,cADD,MAAM,EAAA,CAAA;;4FACnB,cAAc,EAAA,UAAA,EAAA,CAAA;kBAD1B,UAAU;mBAAC,EAAE,UAAU,EAAE,MAAM,EAAE;;AAiGlC;;;;;AAKG;AACG,SAAU,YAAY,CAAC,SAAiB,EAAA;IAC5C,OAAO,MAAM,CAAC,cAAc,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC;AACjD;;AClJA;;;;;AAKG;AACG,SAAU,sBAAsB,CAAC,OAAA,GAAkC,EAAE,EAAA;AACzE,IAAA,OAAO,wBAAwB,CAAC;AAC9B,QAAA,EAAE,OAAO,EAAE,wBAAwB,EAAE,QAAQ,EAAE,OAAO,EAAE;QACxD,cAAc;QACd,6BAA6B,CAAC,MAAK,EAAG,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;AACjE,KAAA,CAAC;AACJ;;ACfA;;ACAA;;AAEG;;"}
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@tech4good/platform-logging",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Shared runtime logging and namespace controls for Tech4Good Angular applications.",
5
+ "license": "MIT",
6
+ "sideEffects": false,
7
+ "typings": "types/tech4good-platform-logging.d.ts",
8
+ "peerDependencies": {
9
+ "@angular/core": "^21.0.0"
10
+ },
11
+ "dependencies": {
12
+ "tslib": "^2.3.0"
13
+ },
14
+ "module": "fesm2022/tech4good-platform-logging.mjs",
15
+ "exports": {
16
+ "./package.json": {
17
+ "default": "./package.json"
18
+ },
19
+ ".": {
20
+ "types": "./types/tech4good-platform-logging.d.ts",
21
+ "default": "./fesm2022/tech4good-platform-logging.mjs"
22
+ }
23
+ },
24
+ "type": "module"
25
+ }
@@ -0,0 +1,97 @@
1
+ import * as i0 from '@angular/core';
2
+ import { EnvironmentProviders } from '@angular/core';
3
+
4
+ /** A namespace-bound logger. Arguments retain their original values for the output sink. */
5
+ interface Logger {
6
+ log(...values: unknown[]): void;
7
+ warn(...values: unknown[]): void;
8
+ error(...values: unknown[]): void;
9
+ }
10
+ type LogLevel = 'log' | 'warn' | 'error';
11
+ /** One accepted log call, after namespace filtering. No serialization is imposed. */
12
+ interface LogEntry {
13
+ readonly namespace: string;
14
+ readonly level: LogLevel;
15
+ readonly values: readonly unknown[];
16
+ }
17
+ /** Synchronous destination for messages. Applications can queue remote delivery here. */
18
+ type LogSink = (entry: LogEntry) => void;
19
+ /** Useful when constructing non-injectable helpers without diagnostic output. */
20
+ declare const NOOP_LOGGER: Logger;
21
+ /** Default browser/server console destination, retaining namespace and argument structure. */
22
+ declare const CONSOLE_LOG_SINK: LogSink;
23
+
24
+ /** Configuration belongs to the application; the package never imports app environments. */
25
+ interface PlatformLoggingOptions {
26
+ /** False by default; true enables all namespaces, an array enables exact names. */
27
+ enabled?: boolean | readonly string[];
28
+ /** Replace console output with an application-owned destination. */
29
+ sink?: LogSink;
30
+ /** Restore/save namespace settings in browser localStorage. Off by default. */
31
+ persist?: boolean;
32
+ /** Use separate keys for apps sharing an origin. Defaults to debug_logs. */
33
+ storageKey?: string;
34
+ /** Opt in to window.debugLogger controls; normally enabled only in development. */
35
+ exposeDebugConsole?: boolean;
36
+ }
37
+ /**
38
+ * Injector-owned logging state shared by scoped loggers in that injector.
39
+ * Without configuration it is silent and touches no browser storage/global.
40
+ * Loggers capture this instance, so creating a second app or test cannot redirect
41
+ * an existing logger. Browser persistence and DevTools exposure are optional.
42
+ *
43
+ * With exposeDebugConsole: true in providePlatformLogging, the browser's DevTools
44
+ * console can control logging at runtime:
45
+ * - Enable all logs: debugLogger.enable()
46
+ * - Enable specific namespaces: debugLogger.enable('data,auth')
47
+ * - Disable logs: debugLogger.disable()
48
+ * - Toggle logs: debugLogger.toggle()
49
+ * Set persist: true as well if those choices should survive a page reload.
50
+ */
51
+ declare class LoggingService {
52
+ private readonly options;
53
+ private readonly destroyRef;
54
+ private readonly namespaces;
55
+ private readonly sink;
56
+ private readonly storageKey;
57
+ private destroyed;
58
+ constructor();
59
+ /**
60
+ * Get a logger usable after leaving an injection context, including callbacks.
61
+ * A namespace is an exact category name, such as data, auth or onboarding.
62
+ * Existing scoped loggers observe enable/disable changes without being recreated.
63
+ */
64
+ scoped(namespace: string): Logger;
65
+ /** Enable all output, or exact comma-separated/array namespace names. */
66
+ enable(namespaces?: string | readonly string[]): void;
67
+ /** Disable every level, including warnings/errors, and persist that choice when enabled. */
68
+ disable(): void;
69
+ /** Toggle between disabled and all namespaces. */
70
+ toggle(): void;
71
+ /** Reactive read of global enablement, or whether a particular namespace is enabled. */
72
+ isEnabled(namespace?: string): boolean;
73
+ private write;
74
+ private persist;
75
+ private exposeDebugConsole;
76
+ static ɵfac: i0.ɵɵFactoryDeclaration<LoggingService, never>;
77
+ static ɵprov: i0.ɵɵInjectableDeclaration<LoggingService>;
78
+ }
79
+ /**
80
+ * Request a scoped logger in an Angular injection context, such as a field
81
+ * initializer or provider factory. Retain it for later event/async callbacks.
82
+ * @example
83
+ * private readonly logger = injectLogger('auth');
84
+ */
85
+ declare function injectLogger(namespace: string): Logger;
86
+
87
+ /**
88
+ * Configure logging once at the application's root. Supplying this provider in
89
+ * another environment injector creates independent logging state there.
90
+ * Initialization eagerly restores settings/exposes optional DevTools controls,
91
+ * even before any feature requests a logger. All browser features are opt-in.
92
+ */
93
+ declare function providePlatformLogging(options?: PlatformLoggingOptions): EnvironmentProviders;
94
+
95
+ export { CONSOLE_LOG_SINK, LoggingService, NOOP_LOGGER, injectLogger, providePlatformLogging };
96
+ export type { LogEntry, LogLevel, LogSink, Logger, PlatformLoggingOptions };
97
+ //# sourceMappingURL=tech4good-platform-logging.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tech4good-platform-logging.d.ts","sources":["../../src/logger.ts","../../src/logging.service.ts","../../src/providers.ts"],"mappings":";;;AAAA;UACiB,MAAM;;;;AAItB;AAEK,KAAM,QAAQ;AAEpB;UACiB,QAAQ;AACvB;AACA,oBAAgB,QAAQ;AACxB;AACD;AAED;AACM,KAAM,OAAO,WAAW,QAAQ;AAEtC;AACA,cAAa,WAAW,EAAE,MAA2D;AAErF;AACA,cAAa,gBAAgB,EAAE,OAE9B;;ACtBD;UACiB,sBAAsB;;AAErC;;WAEO,OAAO;;;;;;;AAOf;AAeD;;;;;;;;;;;;;AAaG;AACH,cACa,cAAc;AACzB;AACA;AACA;AACA;AACA;;;AAgBA;;;;AAIG;AACH,+BAA2B,MAAM;;;;AAkBjC;;AAMA;;AAGA;AAMA;AASA;AAWA;yCA/EW,cAAc;6CAAd,cAAc;AA8F1B;AAED;;;;;AAKG;AACH,iBAAgB,YAAY,qBAAqB,MAAM;;AChJvD;;;;;AAKG;AACH,iBAAgB,sBAAsB,WAAU,sBAA2B,GAAG,oBAAoB;;","names":[]}