@quran-lab/tajweedformer 0.0.0-stage → 2.0.1

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 (51) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/LICENSE +148 -0
  3. package/README.md +121 -2
  4. package/dist/tajweedformer-opus.mjs +2 -0
  5. package/dist/tajweedformer-opus.wasm +0 -0
  6. package/dist/tajweedformer-scorer.mjs +2 -0
  7. package/dist/tajweedformer-scorer.wasm +0 -0
  8. package/dist/tajweedformer.mjs +2 -0
  9. package/dist/tajweedformer.wasm +0 -0
  10. package/docs/api.md +167 -0
  11. package/examples/browser.html +69 -0
  12. package/examples/node.mjs +37 -0
  13. package/package.json +81 -6
  14. package/web/consent/copy.js +51 -0
  15. package/web/consent/decks.js +470 -0
  16. package/web/consent/element.js +170 -0
  17. package/web/consent/index.d.ts +128 -0
  18. package/web/consent/index.js +239 -0
  19. package/web/consent/state.js +162 -0
  20. package/web/consent/theme.js +31 -0
  21. package/web/consent/wording.js +126 -0
  22. package/web/index.d.ts +4 -0
  23. package/web/index.js +10 -0
  24. package/web/platform/client.js +484 -0
  25. package/web/platform/contributor-key.js +112 -0
  26. package/web/platform/index.d.ts +148 -0
  27. package/web/platform/index.js +8 -0
  28. package/web/platform/storage.js +50 -0
  29. package/web/platform/telemetry.js +314 -0
  30. package/web/platform/update-notice.js +60 -0
  31. package/web/scorer.d.ts +4 -0
  32. package/web/scorer.js +10 -0
  33. package/web/sharing/bitrate.js +69 -0
  34. package/web/sharing/encoder.js +176 -0
  35. package/web/sharing/index.d.ts +262 -0
  36. package/web/sharing/index.js +287 -0
  37. package/web/sharing/oggopus.js +325 -0
  38. package/web/sharing/outbox.js +670 -0
  39. package/web/sharing/resampler.js +122 -0
  40. package/web/sharing/uploader.js +178 -0
  41. package/web/tajweed/decode.js +213 -0
  42. package/web/tajweed/delivery.js +317 -0
  43. package/web/tajweed/engine.js +600 -0
  44. package/web/tajweed/heads.js +73 -0
  45. package/web/tajweed/index.d.ts +737 -0
  46. package/web/tajweed/index.js +12 -0
  47. package/web/tajweed/manifest.js +452 -0
  48. package/web/tajweed/node.d.ts +3 -0
  49. package/web/tajweed/node.js +59 -0
  50. package/web/tajweed/settings.js +483 -0
  51. package/web/tajweed/tajweedformer.js +369 -0
@@ -0,0 +1,162 @@
1
+ // The sharing state machine: when to ask,
2
+ // how often to re-ask, the guardian variant, settings, the thank-you. Plain JS, no DOM.
3
+ //
4
+ // Asking, since 2.0.1:
5
+ // - the sheet is shown at most MAX_ASKS times per install, ever (the first ask and, after "Not now", re-asks
6
+ // REASK_GAP sessions apart); the count is of asks handed out (the SDK's sheet or an app's own UI), stored, and
7
+ // carried over from 2.0.0's `asks`;
8
+ // - a yes ends asking for good: the grant keeps the consent version (and, for an app's own wording, the text hash)
9
+ // recorded when the learner agreed, across copy decks, wordings and SDK upgrades. There is no version re-ask
10
+ // and nothing pauses sharing when the wording in force changes;
11
+ // - turning sharing off ends asking for good; only the settings switch (setSharing) turns it on or off then.
12
+ //
13
+ // Stored under SHARING_STATE_KEY, the same object 2.0.0 stored: { v: 1, consent: 'unknown' | 'granted' |
14
+ // 'declined' | 'final', asks, lastAskSession, sessions, thanked, decidedAt, consentVersion, guardian } plus
15
+ // consentTextSha256 (2.0.1). 2.0.0's `versionAsked` is left as it is and no longer read.
16
+
17
+ export const SHARING_STATE_KEY = 'sharing.v1';
18
+ const FRESH = { v: 1, consent: 'unknown', asks: 0, lastAskSession: 0, sessions: 0, thanked: false, decidedAt: null,
19
+ consentVersion: null, consentTextSha256: null, guardian: false };
20
+ /** Sheets shown in all, ever: the first ask and at most two re-asks after "Not now". */
21
+ export const MAX_ASKS = 3;
22
+ /** Sessions between asks. */
23
+ export const REASK_GAP = 7;
24
+ /** The consent version of the copy deck the web SDK 2.0.0 bundled: a 2.0.0 grant stored without a version was
25
+ * given to it. */
26
+ export const LEGACY_CONSENT_VERSION = 'share-2026-11-07';
27
+
28
+ export class SharingState {
29
+ /**
30
+ * @param {{ get(k): any, set(k, v): void }} state persistence (per origin in browsers)
31
+ * @param {{ enabled: () => boolean, consentVersion?: string, consentTextSha256?: string|null, audience?: string,
32
+ * clock?: () => number }} o consentVersion: the version a new grant records (the deck's, or custom-...
33
+ * for an app's own wording, with its text hash)
34
+ */
35
+ constructor(state, o = {}) {
36
+ this.state = state;
37
+ this.enabledFn = o.enabled || (() => false);
38
+ this.consentVersion = o.consentVersion || null;
39
+ this.consentTextSha256 = o.consentTextSha256 || null;
40
+ this.audience = o.audience || 'general';
41
+ this.clock = o.clock || Date.now;
42
+ this.listeners = new Set();
43
+ }
44
+ get s() {
45
+ const s = { ...FRESH, ...(this.state.get(SHARING_STATE_KEY) || {}) };
46
+ if (!Number.isFinite(s.asks) || s.asks < 0) s.asks = 0;
47
+ // a 2.0.0 grant without a version was given to the deck 2.0.0 bundled
48
+ if (s.consent === 'granted' && !s.consentVersion) { s.consentVersion = LEGACY_CONSENT_VERSION; s.consentTextSha256 = null; }
49
+ return s;
50
+ }
51
+ _put(s) { this.state.set(SHARING_STATE_KEY, s); for (const f of this.listeners) f(s); }
52
+ onChange(f) { this.listeners.add(f); return () => this.listeners.delete(f); }
53
+ _today() { return new Date(this.clock()).toISOString().slice(0, 10); }
54
+
55
+ /** Uploads may run: enabled by the app and the signed config, and the learner said yes (to whichever
56
+ * version: a grant is never paused by a newer deck or wording). */
57
+ get sharing() {
58
+ return this.enabledFn() && this.s.consent === 'granted';
59
+ }
60
+ get guardianVariant() { return this.audience === 'children'; }
61
+
62
+ /** Asking has not ended: no yes, not turned off, and fewer than MAX_ASKS sheets shown. */
63
+ get asking() {
64
+ const s = this.s;
65
+ return (s.consent === 'unknown' || s.consent === 'declined') && s.asks < MAX_ASKS;
66
+ }
67
+
68
+ /** The version a NEW grant records (an app changed its wording, or a new deck). A learner who already agreed
69
+ * keeps the version recorded then, keeps sharing and is not asked again. */
70
+ setConsent(version, textSha256 = null) {
71
+ this.consentVersion = version || null;
72
+ this.consentTextSha256 = textSha256 || null;
73
+ for (const f of this.listeners) f(this.s);
74
+ }
75
+
76
+ /** The consent version the current grant was given to (null when not granted): what each session of this
77
+ * grant sends as consent_version. */
78
+ get grantVersion() { const s = this.s; return s.consent === 'granted' ? s.consentVersion : null; }
79
+
80
+ /** The hash of the custom wording the current grant was given to (null for a deck's own wording, or when
81
+ * not sharing): what each session of this grant sends as consent_text_sha256. */
82
+ get grantTextSha256() {
83
+ if (!this.sharing) return null;
84
+ const s = this.s;
85
+ return s.consentVersion && s.consentVersion.startsWith('custom-') ? s.consentTextSha256 || null : null;
86
+ }
87
+
88
+ _ask(s) {
89
+ if (!(s.consent === 'unknown' || s.consent === 'declined') || s.asks >= MAX_ASKS) return null;
90
+ if (s.asks > 0 && s.sessions - s.lastAskSession < REASK_GAP) return null;
91
+ return s.consent === 'declined' ? 'reask' : 'first';
92
+ }
93
+
94
+ /**
95
+ * A session ended. Returns null, or the ask to show: { variant: 'first' | 'reask', guardian: boolean }
96
+ * (counted as shown). The caller shows the sheet and calls answer().
97
+ * @param {{ feedback: boolean }} o feedback: the learner was shown the model's verdicts
98
+ */
99
+ sessionCompleted({ feedback = false } = {}) {
100
+ const s = this.s;
101
+ s.sessions += 1;
102
+ const ask = this.enabledFn() && feedback ? this._ask(s) : null;
103
+ if (ask) { s.asks += 1; s.lastAskSession = s.sessions; }
104
+ this._put(s);
105
+ return ask ? { variant: ask, guardian: this.guardianVariant } : null;
106
+ }
107
+
108
+ /** The app asks now (its own timing; the disclosure lines stay the SDK's). Counted as shown; null once asking
109
+ * has ended (a yes, sharing turned off, or MAX_ASKS sheets shown). The REASK_GAP spacing is the app's to keep. */
110
+ askNow() {
111
+ const s = this.s;
112
+ if (!(s.consent === 'unknown' || s.consent === 'declined') || s.asks >= MAX_ASKS) return null;
113
+ const variant = s.consent === 'declined' ? 'reask' : 'first';
114
+ s.asks += 1; s.lastAskSession = s.sessions;
115
+ this._put(s);
116
+ return { variant, guardian: this.guardianVariant };
117
+ }
118
+
119
+ /**
120
+ * The learner answered the sheet. yes: share, recording the version in force now; no (or dismissed): not now
121
+ * (final after the last ask). guardianConfirmed must be true for a yes in the guardian variant. After a yes or
122
+ * a switch turned off this changes nothing (the recorded grant stays as it is): use setSharing.
123
+ */
124
+ answer(yes, { guardianConfirmed = false } = {}) {
125
+ const s = this.s;
126
+ if (s.consent === 'granted' || s.consent === 'final') return s.consent;
127
+ if (yes) {
128
+ if (this.guardianVariant && !guardianConfirmed) throw new Error('the guardian variant needs the parent or guardian confirmation');
129
+ Object.assign(s, { consent: 'granted', decidedAt: this._today(), consentVersion: this.consentVersion,
130
+ consentTextSha256: this.consentTextSha256, guardian: !!guardianConfirmed });
131
+ } else {
132
+ s.consent = s.asks >= MAX_ASKS ? 'final' : 'declined';
133
+ s.decidedAt = this._today();
134
+ }
135
+ this._put(s);
136
+ return s.consent;
137
+ }
138
+
139
+ /** The settings switch. On records the version in force now (an existing grant keeps its own). Off is final
140
+ * until the learner turns it on again here, and is never asked about again. */
141
+ setSharing(on, { guardianConfirmed = false } = {}) {
142
+ const s = this.s;
143
+ if (on) {
144
+ if (s.consent === 'granted') return;
145
+ if (this.guardianVariant && !guardianConfirmed) throw new Error('the guardian variant needs the parent or guardian confirmation');
146
+ Object.assign(s, { consent: 'granted', consentVersion: this.consentVersion, consentTextSha256: this.consentTextSha256,
147
+ guardian: !!guardianConfirmed, decidedAt: this._today() });
148
+ } else {
149
+ s.consent = 'final';
150
+ }
151
+ this._put(s);
152
+ }
153
+
154
+ /** The thank-you is due (first shared session uploaded): returns true once. */
155
+ takeThanks() {
156
+ const s = this.s;
157
+ if (s.consent !== 'granted' || s.thanked) return false;
158
+ s.thanked = true;
159
+ this._put(s);
160
+ return true;
161
+ }
162
+ }
@@ -0,0 +1,31 @@
1
+ // The look of the SDK's sharing sheets (consent, guardian, thanks, settings): the same theme keys as the Swift
2
+ // SDK's SharingTheme, set as CSS custom properties on each element (an app can also set the properties in its
3
+ // own CSS). A theme changes colours, corner radius and fonts, never the words or the consent version.
4
+
5
+ /** Theme key -> the CSS custom property it sets. */
6
+ export const THEME_PROPERTIES = Object.freeze({
7
+ accent: '--ql-accent', accentText: '--ql-accent-fg', background: '--ql-bg', text: '--ql-fg', secondaryText: '--ql-muted',
8
+ cornerRadius: '--ql-radius', titleFont: '--ql-title-font', bodyFont: '--ql-font',
9
+ });
10
+
11
+ /** A theme as CSS custom properties ({ '--ql-accent': '#2a3b8f', ... }); a number cornerRadius is in px. An
12
+ * unknown key or a value that is not a plain CSS value throws a TypeError; null or {} is the default look. */
13
+ export function themeProperties(theme) {
14
+ if (theme === null || theme === undefined) return {};
15
+ if (typeof theme !== 'object' || Array.isArray(theme)) throw new TypeError('theme: an object');
16
+ const out = {};
17
+ for (const [k, v] of Object.entries(theme)) {
18
+ if (!(k in THEME_PROPERTIES)) throw new TypeError(`theme: unknown key ${k} (${Object.keys(THEME_PROPERTIES).join(', ')})`);
19
+ if (v === null || v === undefined || v === '') continue;
20
+ if (k === 'cornerRadius' && typeof v === 'number') { out[THEME_PROPERTIES[k]] = `${v}px`; continue; }
21
+ if (typeof v !== 'string' || /[;{}<>]/.test(v)) throw new TypeError(`theme: ${k} must be a CSS value`);
22
+ out[THEME_PROPERTIES[k]] = v;
23
+ }
24
+ return out;
25
+ }
26
+
27
+ /** Sets a theme's properties on an element (its shadow tree inherits them). */
28
+ export function applyTheme(el, theme) {
29
+ for (const [k, v] of Object.entries(themeProperties(theme))) el.style.setProperty(k, v);
30
+ return el;
31
+ }
@@ -0,0 +1,126 @@
1
+ // An app's own wording for the sharing copy (SDK 2.0.1; the platform client doc, "Your own wording"). When an
2
+ // app replaces deck strings, the learner agrees to that text, so the grant is recorded under a version derived
3
+ // from it and every session of that grant sends the text's hash for Quran Lab to review:
4
+ //
5
+ // canonical = "quranlab.consent-text/1\n" + "base " + <deck consent_version> + "\n"
6
+ // + for each replaced key, sorted by its UTF-8 bytes: key + "\t" + escaped text + "\n"
7
+ // escaped = \ -> \\, newline -> \n, carriage return -> \r, tab -> \t (nothing else, no normalisation)
8
+ // consent_text_sha256 = SHA-256 of the canonical UTF-8 bytes, lower-case hex
9
+ // consent_version = "custom-" + its first 24 hex digits
10
+ //
11
+ // The same derivation in every SDK, pinned by the shared vector consent_text.json. Synchronous (a small
12
+ // SHA-256 here) so the consent state can compare versions at any moment.
13
+ // Tried and rejected: WebCrypto's digest (async: the version would not be known when a sheet answer or a
14
+ // settings switch has to be recorded); JSON canonicalisation (encoders escape differently across platforms).
15
+
16
+ import { DECKS } from './decks.js';
17
+
18
+ export const CONSENT_TEXT_FORMAT = 'quranlab.consent-text/1';
19
+ /** CLDR plural categories a plural line may be given for (`impact.minutes.one`, ...). */
20
+ export const PLURAL_CATEGORIES = Object.freeze(['zero', 'one', 'two', 'few', 'many', 'other']);
21
+
22
+ const utf8 = (s) => new TextEncoder().encode(s);
23
+
24
+ // ------------------------------------------------------------------------------------------------
25
+ // SHA-256 (FIPS 180-4), synchronous
26
+
27
+ const K = new Uint32Array([
28
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
29
+ 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
30
+ 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
31
+ 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
32
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
33
+ 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
34
+ ]);
35
+
36
+ /** SHA-256 of bytes, lower-case hex. */
37
+ export function sha256HexSync(bytes) {
38
+ const len = bytes.length;
39
+ const blocks = Math.ceil((len + 9) / 64);
40
+ const m = new Uint8Array(blocks * 64);
41
+ m.set(bytes);
42
+ m[len] = 0x80;
43
+ const dv = new DataView(m.buffer);
44
+ dv.setUint32(m.length - 8, Math.floor(len / 0x20000000), false);
45
+ dv.setUint32(m.length - 4, (len * 8) >>> 0, false);
46
+ const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
47
+ const w = new Uint32Array(64);
48
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
49
+ for (let b = 0; b < blocks; b++) {
50
+ for (let i = 0; i < 16; i++) w[i] = dv.getUint32(b * 64 + i * 4, false);
51
+ for (let i = 16; i < 64; i++) {
52
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
53
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
54
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
55
+ }
56
+ let [a, bb, c, d, e, f, g, hh] = h;
57
+ for (let i = 0; i < 64; i++) {
58
+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
59
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) >>> 0;
60
+ hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = bb; bb = a; a = (t1 + t2) >>> 0;
61
+ }
62
+ h[0] += a; h[1] += bb; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
63
+ }
64
+ return [...h].map((x) => x.toString(16).padStart(8, '0')).join('');
65
+ }
66
+
67
+ // ------------------------------------------------------------------------------------------------
68
+
69
+ /** The keys an app may replace: every string key of the decks, and each plural line by category. */
70
+ export function wordingKeys() {
71
+ const keys = new Set();
72
+ for (const d of Object.values(DECKS)) {
73
+ for (const [k, v] of Object.entries(d.strings)) {
74
+ if (typeof v === 'string') keys.add(k);
75
+ else if (v && typeof v === 'object') for (const c of PLURAL_CATEGORIES) keys.add(`${k}.${c}`);
76
+ }
77
+ }
78
+ return keys;
79
+ }
80
+
81
+ const compareUtf8 = (a, b) => {
82
+ const x = utf8(a), y = utf8(b);
83
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
84
+ return x.length - y.length;
85
+ };
86
+ const escape = (t) => t.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
87
+
88
+ /**
89
+ * Checks an app's overrides: an object of deck keys to non-blank strings. Throws a TypeError naming the
90
+ * first problem (an unknown key, a text that is not a string, empty or blank); returns a frozen copy.
91
+ * null, undefined or {} mean no overrides.
92
+ */
93
+ export function validateWording(overrides) {
94
+ if (overrides === null || overrides === undefined) return Object.freeze({});
95
+ if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('wording: an object of {key: text}');
96
+ const keys = wordingKeys();
97
+ const out = {};
98
+ for (const [k, v] of Object.entries(overrides)) {
99
+ if (!keys.has(k)) throw new TypeError(`wording: unknown key ${JSON.stringify(k)}`);
100
+ if (typeof v !== 'string') throw new TypeError(`wording: ${k} is not a string`);
101
+ if (!v.length) throw new TypeError(`wording: ${k} is empty`);
102
+ if (/^\s*$/u.test(v)) throw new TypeError(`wording: ${k} is blank`);
103
+ out[k] = v;
104
+ }
105
+ return Object.freeze(out);
106
+ }
107
+
108
+ /** The canonical text of a wording (a string; its UTF-8 bytes are what is hashed), or null without overrides. */
109
+ export function canonicalConsentText(base, overrides) {
110
+ const keys = Object.keys(overrides || {});
111
+ if (!keys.length) return null;
112
+ let out = `${CONSENT_TEXT_FORMAT}\nbase ${base}\n`;
113
+ for (const k of keys.sort(compareUtf8)) out += `${k}\t${escape(overrides[k])}\n`;
114
+ return out;
115
+ }
116
+
117
+ /**
118
+ * The consent a learner gives under a deck and an app's overrides:
119
+ * { version, textSha256, canonicalText }; without overrides the deck's version and nulls.
120
+ */
121
+ export function deriveConsent(base, overrides) {
122
+ const canonicalText = canonicalConsentText(base, overrides);
123
+ if (canonicalText === null) return Object.freeze({ version: base, textSha256: null, canonicalText: null });
124
+ const textSha256 = sha256HexSync(utf8(canonicalText));
125
+ return Object.freeze({ version: `custom-${textSha256.slice(0, 24)}`, textSha256, canonicalText });
126
+ }
package/web/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ // Type definitions for @quran-lab/tajweedformer: the V4 TajweedFormer API (SDK 2.0.1).
2
+ export * from './tajweed/index.js';
3
+ import { TajweedFormer } from './tajweed/index.js';
4
+ export default TajweedFormer;
package/web/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // @quran-lab/tajweedformer: TajweedFormer V4 for browsers and Node. The exact engine in WebAssembly
2
+ // (single thread, SIMD128; works everywhere with no special headers), the model delivery (shared
3
+ // cache, resumable, hashed), the decoded and tajweed layers, and the Quran Lab platform client.
4
+ // import { TajweedFormer } from '@quran-lab/tajweedformer';
5
+ import createTajweedFormer from '../dist/tajweedformer.mjs';
6
+ import { bindTajweed } from './tajweed/tajweedformer.js';
7
+ export * from './tajweed/index.js';
8
+
9
+ export const TajweedFormer = bindTajweed(createTajweedFormer);
10
+ export default TajweedFormer;