@didask/scol-r 2.13.0 → 2.15.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@didask/scol-r",
3
- "version": "2.13.0",
3
+ "version": "2.15.0",
4
4
  "description": "Shareable Cross-Origin Learning Resources",
5
5
  "main": "index.html",
6
6
  "types": "lib/index.d.ts",
@@ -42,4 +42,4 @@
42
42
  "pre-commit": "jest && tsc"
43
43
  }
44
44
  }
45
- }
45
+ }
@@ -1,6 +0,0 @@
1
- export interface HTMLGeneratorProps {
2
- dataSource: string;
3
- libPath?: string;
4
- hashIdentifiers?: boolean;
5
- }
6
- export declare function HTMLGenerator(props: HTMLGeneratorProps): string;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTMLGenerator = void 0;
4
- function HTMLGenerator(props) {
5
- var dataSource = props.dataSource, _a = props.libPath, libPath = _a === void 0 ? "lib" : _a, _b = props.hashIdentifiers, hashIdentifiers = _b === void 0 ? false : _b;
6
- return "<!DOCTYPE html>\n <html>\n <head>\n <title>SCO local endpoint</title>\n <meta charset=\"UTF-8\"/>\n <script>var exports = {};</script>\n <script type=\"text/javascript\" src=\"".concat(libPath, "/hashString.js\"></script>\n <script type=\"text/javascript\" src=\"").concat(libPath, "/SCORMAdapter.js\"></script>\n <script type=\"text/javascript\" src=\"").concat(libPath, "/MessageHandler.js\"></script>\n <script type=\"text/javascript\" src=\"").concat(libPath, "/loadContent.js\"></script>\n <style type=\"text/css\">\n html, body { margin: 0; padding:0; overflow:hidden; width: 100%; height: 100%; }\n body {\n font-size: 20px;\n font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n color: #1d1046;\n }\n #wrapper { display: flex; flex-direction: column; height: 100%; }\n .container { width: 80%; max-width: 1200px; padding: 15px; margin: auto; }\n #wrapper .header {\n padding-top: 20px; padding-bottom: 20px;\n background-color: #f3f4f5;\n }\n #wrapper .messages { flex-grow: 1; padding-top: 20px; padding-bottom: 20px; }\n #wrapper .messages p { color: red; }\n #title-error-messages { color: #1d1046; }\n #wrapper .footer {\n background-color: #1d1046; color: white;\n padding-top: 10px; padding-bottom: 10px;\n }\n #wrapper .footer a { color: white; }\n\n iframe { overflow: hidden; height: 100%; width: 100%; }\n iframe + #wrapper { display: none; }\n #runtime-error {\n position: fixed;\n left: 20px; bottom: 20px; padding: 15px;\n background-color: #f44a3d; color: white;\n font-size: 16px;\n }\n #runtime-error h6, #runtime-error p { margin: 0 0 10px;}\n #runtime-error p:last-child { margin: 0;}\n #runtime-error:empty { display: none; }\n </style>\n </head>\n <!-- Set the body's data-source attribute to the SCO's remote endpoint. -->\n <body onload=\"loadContent({hashIdentifiers: ").concat(hashIdentifiers, "});\" data-source=\"").concat(dataSource, "\">\n <div id=\"wrapper\">\n <div class=\"header\"><div class=\"container\">\n <h1 id=\"title\">Your content is loading...</h1>\n <p id=\"subtitle\">Please wait, or if your content doesn't appear, try closing and opening this window again.</p>\n </div></div>\n <div class=\"messages container\">\n <h2 id=\"title-error-messages\">If the initialization fails, error messages will appear below:</h2>\n </div>\n <div class=\"footer\"><div class=\"container\" id=\"footer-content\">\n This content is loaded via <a href=\"https://github.com/Didask/scol-r\" target=\"_blank\">SCOL-R</a>, a cross-domain SCORM connector created by <a href=\"https://www.didask.com\" target=\"_blank\">Didask</a>.\n </div></div>\n </div>\n <div id=\"runtime-error\"></div>\n </body>\n </html>");
7
- }
8
- exports.HTMLGenerator = HTMLGenerator;
@@ -1,28 +0,0 @@
1
- import { scormVersions } from ".";
2
- export declare class Sco {
3
- scoID: string;
4
- scoTitle: string;
5
- scoHref: `./${string}`;
6
- author: string;
7
- learningTime: number;
8
- resources: string[];
9
- constructor(props: {
10
- scoID: string;
11
- scoTitle: string;
12
- author: string;
13
- learningTime: number;
14
- scoHref: `./${string}`;
15
- resources: string[];
16
- });
17
- }
18
- export interface ManifestGeneratorProps {
19
- courseId: string;
20
- courseTitle: string;
21
- courseAuthor: string;
22
- scoList?: Sco[];
23
- sharedResources?: string[];
24
- totalLearningTime?: number;
25
- dataFromLms?: string;
26
- scormVersion?: (typeof scormVersions)[number];
27
- }
28
- export declare function ManifestGenerator({ courseId, scoList, sharedResources, totalLearningTime, dataFromLms, scormVersion, ...props }: ManifestGeneratorProps): string;
@@ -1,78 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __rest = (this && this.__rest) || function (s, e) {
14
- var t = {};
15
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
- t[p] = s[p];
17
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
- t[p[i]] = s[p[i]];
21
- }
22
- return t;
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.ManifestGenerator = exports.Sco = void 0;
26
- var Sco = /** @class */ (function () {
27
- function Sco(props) {
28
- this.scoID = props.scoID;
29
- this.scoTitle = props.scoTitle;
30
- this.author = props.author;
31
- this.learningTime = props.learningTime;
32
- this.resources = props.resources;
33
- this.scoHref = props.scoHref;
34
- }
35
- return Sco;
36
- }());
37
- exports.Sco = Sco;
38
- var formatLearningTime = function (learningTime) {
39
- var intHours = Math.floor(learningTime / 60);
40
- var hours = intHours > 10 ? intHours : "0".concat(intHours);
41
- var intMinutes = intHours > 0 ? learningTime - intHours * 60 : learningTime;
42
- var minutes = intMinutes > 10 ? intMinutes : "0".concat(intMinutes);
43
- return "".concat(hours, ":").concat(minutes, ":00");
44
- };
45
- var removeSpecialChars = function (obj) {
46
- return Object.entries(obj).reduce(function (acc, _a) {
47
- var _b;
48
- var key = _a[0], value = _a[1];
49
- return (__assign(__assign({}, acc), (_b = {}, _b[key] = value.replace(/&/g, "-"), _b)));
50
- }, {});
51
- };
52
- function ManifestGenerator(_a) {
53
- var courseId = _a.courseId, _b = _a.scoList, scoList = _b === void 0 ? [] : _b, _c = _a.sharedResources, sharedResources = _c === void 0 ? [] : _c, _d = _a.totalLearningTime, totalLearningTime = _d === void 0 ? 0 : _d, dataFromLms = _a.dataFromLms, _e = _a.scormVersion, scormVersion = _e === void 0 ? "1.2" : _e, props = __rest(_a, ["courseId", "scoList", "sharedResources", "totalLearningTime", "dataFromLms", "scormVersion"]);
54
- var _f = removeSpecialChars(props), courseTitle = _f.courseTitle, courseAuthor = _f.courseAuthor;
55
- var courseGlobalLearningTime = scoList.length
56
- ? scoList.reduce(function (acc, sco) { return acc + sco.learningTime; }, 0)
57
- : totalLearningTime;
58
- return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n <manifest xmlns=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2\" identifier=\"".concat(courseId, "\" version=\"1.0\" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_rootv1p2p1\" xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_rootv1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd\">\n <metadata>\n <schema>ADL SCORM</schema>\n <schemaversion>").concat(scormVersion, "</schemaversion>\n <imsmd:lom xmlns=\"http://ltsc.ieee.org/xsd/LOM\">\n <imsmd:general>\n <imsmd:identifier>").concat(courseId, "</imsmd:identifier>\n <imsmd:title>\n <imsmd:langstring xml:lang=\"fr\">").concat(courseTitle, "</imsmd:langstring>\n </imsmd:title>\n </imsmd:general>\n <imsmd:lifecycle>\n <imsmd:contribute>\n <imsmd:role>\n <imsmd:source>\n <imsmd:langstring xml:lang=\"fr\">LOMv1.0</imsmd:langstring>\n </imsmd:source>\n <imsmd:value>\n <imsmd:langstring xml:lang=\"fr\">Author</imsmd:langstring>\n </imsmd:value>\n </imsmd:role>\n <imsmd:centity>\n <imsmd:vcard>\n begin:vcard\n fn:").concat(courseAuthor, "\n end:vcard\n </imsmd:vcard>\n </imsmd:centity>\n </imsmd:contribute>\n </imsmd:lifecycle>\n <imsmd:metametadata>\n <imsmd:metadatascheme>ADL SCORM 1.2</imsmd:metadatascheme>\n </imsmd:metametadata>\n <imsmd:rights>\n <imsmd:cost>\n <imsmd:source>\n <imsmd:langstring xml:lang=\"fr\">LOMv1.0</imsmd:langstring>\n </imsmd:source>\n <imsmd:value>\n <imsmd:langstring xml:lang=\"fr\">yes</imsmd:langstring>\n </imsmd:value>\n </imsmd:cost>\n <imsmd:copyrightandotherrestrictions>\n <imsmd:source>\n <imsmd:langstring xml:lang=\"fr\">LOMv1.0</imsmd:langstring>\n </imsmd:source>\n <imsmd:value>\n <imsmd:langstring xml:lang=\"fr\">yes</imsmd:langstring>\n </imsmd:value>\n </imsmd:copyrightandotherrestrictions>\n </imsmd:rights>\n <imsmd:educational>\n <imsmd:typicallearningtime>\n <imsmd:datetime>").concat(formatLearningTime(courseGlobalLearningTime), "</imsmd:datetime>\n </imsmd:typicallearningtime>\n </imsmd:educational>\n </imsmd:lom>\n </metadata>\n <organizations default=\"Org1\">\n <organization identifier=\"Org1\">\n <title>").concat(courseTitle, "</title>\n ").concat(scoList
59
- .map(function (_a) {
60
- var scoID = _a.scoID, learningTime = _a.learningTime, resources = _a.resources, props = __rest(_a, ["scoID", "learningTime", "resources"]);
61
- var _b = removeSpecialChars(props), scoTitle = _b.scoTitle, author = _b.author;
62
- return "<item identifier=\"".concat(scoTitle, "\" identifierref=\"resource_").concat(scoID, "\" isvisible=\"true\">\n <title>").concat(scoTitle, "</title>\n <adlcp:dataFromLMS>").concat(dataFromLms !== null && dataFromLms !== void 0 ? dataFromLms : courseId + ":" + scoID, "</adlcp:dataFromLMS>\n <metadata>\n <imsmd:lom xmlns=\"http://ltsc.ieee.org/xsd/LOM\">\n <imsmd:general>\n <imsmd:identifier>").concat(scoID, "</imsmd:identifier>\n </imsmd:general>\n <imsmd:lifecycle>\n <imsmd:contribute>\n <imsmd:role>\n <imsmd:source>\n <imsmd:langstring xml:lang=\"fr\">LOMv1.0</imsmd:langstring>\n </imsmd:source>\n <imsmd:value>\n <imsmd:langstring xml:lang=\"fr\">Author</imsmd:langstring>\n </imsmd:value>\n </imsmd:role>\n <imsmd:centity>\n <imsmd:vcard>\n begin:vcard\n fn:").concat(author, "\n end:vcard\n </imsmd:vcard>\n </imsmd:centity>\n </imsmd:contribute>\n </imsmd:lifecycle>\n <imsmd:educational>\n <imsmd:typicallearningtime>\n <imsmd:datetime>").concat(formatLearningTime(learningTime), "</imsmd:datetime>\n </imsmd:typicallearningtime>\n </imsmd:educational>\n </imsmd:lom>\n </metadata>\n </item>");
63
- })
64
- .join("\n"), "\n </organization>\n </organizations>\n <resources>\n ").concat((sharedResources === null || sharedResources === void 0 ? void 0 : sharedResources.length)
65
- ? "<resource adlcp:scormtype=\"asset\" type=\"webcontent\" identifier=\"shared_resources\">\n ".concat(sharedResources
66
- .map(function (resource) { return "<file href=\"".concat(resource, "\"/>"); })
67
- .join("\n"), "\n </resource>")
68
- : "", "\n ").concat(scoList
69
- .map(function (sco) {
70
- return "<resource adlcp:scormtype=\"sco\" type=\"webcontent\" identifier=\"resource_".concat(sco.scoID, "\" href=\"").concat(sco.scoHref, "\">\n ").concat((sharedResources === null || sharedResources === void 0 ? void 0 : sharedResources.length)
71
- ? '<dependency identifierref="shared_resources"/>'
72
- : "", "\n ").concat(sco.resources
73
- .map(function (resource) { return "<file href=\"".concat(resource, "\"/>"); })
74
- .join("\n"), "\n </resource>");
75
- })
76
- .join("\n"), "\n </resources>\n </manifest>");
77
- }
78
- exports.ManifestGenerator = ManifestGenerator;
@@ -1,27 +0,0 @@
1
- export declare class MessageReceiver {
2
- private readonly adapter;
3
- constructor(win: Window, sourceOrigin: string, adapter: any);
4
- commit(): void;
5
- setTitle(title: string): void;
6
- setScore(score: string): void;
7
- setStudent(studentId: string, studentName: string): void;
8
- setLessonStatus(lessonStatus: string): void;
9
- setObjectives(objectivesIds: string[]): void;
10
- setObjectiveScore(objectiveId: string, score: number): void;
11
- setObjectiveStatus(objectiveId: string, status: string): void;
12
- }
13
- export declare class MessageEmitter {
14
- private currentWindow;
15
- private lmsOrigin;
16
- constructor(lmsOrigin: string);
17
- private sendMessage;
18
- setStudent({ id, name }: {
19
- id: string;
20
- name: string;
21
- }): void;
22
- setLessonStatus(status: string): void;
23
- setScore(score: number): void;
24
- setObjectives(objectives: string[]): void;
25
- setObjectiveScore(objectiveId: string, score: number): void;
26
- setObjectiveStatus(objectiveId: string, status: "completed" | "incomplete"): void;
27
- }
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MessageEmitter = exports.MessageReceiver = void 0;
4
- var MessageReceiver = /** @class */ (function () {
5
- function MessageReceiver(win, sourceOrigin, adapter) {
6
- this.adapter = adapter;
7
- var timeoutId = null;
8
- win.addEventListener("message", function (e) {
9
- var _this = this;
10
- if (e.origin !== sourceOrigin)
11
- return;
12
- var functionName = e.data["function"];
13
- var functionArgs = e.data["arguments"];
14
- if (functionName &&
15
- functionArgs &&
16
- typeof this[functionName] === "function") {
17
- // @ts-ignore
18
- this[functionName].apply(this, functionArgs);
19
- if (timeoutId) {
20
- clearTimeout(timeoutId);
21
- }
22
- timeoutId = setTimeout(function () {
23
- _this.commit();
24
- timeoutId = null;
25
- }, 500);
26
- }
27
- }.bind(this));
28
- }
29
- MessageReceiver.prototype.commit = function () {
30
- this.adapter.LMSCommit();
31
- };
32
- MessageReceiver.prototype.setTitle = function (title) {
33
- document.title = title;
34
- };
35
- MessageReceiver.prototype.setScore = function (score) {
36
- this.adapter.setScore(score);
37
- };
38
- MessageReceiver.prototype.setStudent = function (studentId, studentName) {
39
- this.adapter.setStudent(studentId, studentName);
40
- };
41
- MessageReceiver.prototype.setLessonStatus = function (lessonStatus) {
42
- this.adapter.setLessonStatus(lessonStatus);
43
- this.adapter.LMSCommit(); // We commit the changes to the LMS each time the lesson status is updated.
44
- };
45
- MessageReceiver.prototype.setObjectives = function (objectivesIds) {
46
- if (this.adapter.objectivesAreAvailable) {
47
- this.adapter.setObjectives(objectivesIds);
48
- }
49
- };
50
- MessageReceiver.prototype.setObjectiveScore = function (objectiveId, score) {
51
- if (this.adapter.objectivesAreAvailable) {
52
- this.adapter.setObjectiveScore(objectiveId, score);
53
- }
54
- };
55
- MessageReceiver.prototype.setObjectiveStatus = function (objectiveId, status) {
56
- if (this.adapter.objectivesAreAvailable) {
57
- this.adapter.setObjectiveStatus(objectiveId, status);
58
- }
59
- };
60
- return MessageReceiver;
61
- }());
62
- exports.MessageReceiver = MessageReceiver;
63
- var MessageEmitter = /** @class */ (function () {
64
- function MessageEmitter(lmsOrigin) {
65
- this.currentWindow = window.parent || window.opener;
66
- this.lmsOrigin = lmsOrigin;
67
- }
68
- MessageEmitter.prototype.sendMessage = function (name, values) {
69
- this.currentWindow.postMessage({
70
- function: name,
71
- arguments: values,
72
- }, this.lmsOrigin);
73
- };
74
- MessageEmitter.prototype.setStudent = function (_a) {
75
- var id = _a.id, name = _a.name;
76
- this.sendMessage("setStudent", [id, name]);
77
- };
78
- MessageEmitter.prototype.setLessonStatus = function (status) {
79
- this.sendMessage("setLessonStatus", [status]);
80
- };
81
- MessageEmitter.prototype.setScore = function (score) {
82
- this.sendMessage("setScore", [score]);
83
- };
84
- MessageEmitter.prototype.setObjectives = function (objectives) {
85
- this.sendMessage("setObjectives", [objectives]);
86
- };
87
- MessageEmitter.prototype.setObjectiveScore = function (objectiveId, score) {
88
- this.sendMessage("setObjectiveScore", [objectiveId, score]);
89
- };
90
- MessageEmitter.prototype.setObjectiveStatus = function (objectiveId, status) {
91
- this.sendMessage("setObjectiveStatus", [objectiveId, status]);
92
- };
93
- return MessageEmitter;
94
- }());
95
- exports.MessageEmitter = MessageEmitter;
@@ -1,47 +0,0 @@
1
- export declare class SCORMAdapter {
2
- private _API;
3
- private _isSCORM2004;
4
- private _errorCallback;
5
- private _lastRequest;
6
- private _ignorableErrorCodes;
7
- constructor(errorCallback?: Function);
8
- get foundAPI(): boolean;
9
- private _initialize;
10
- private _findAndSetAPI;
11
- private _findAPIInWindow;
12
- private _callAPIFunction;
13
- private _handleError;
14
- private _warnNOAPI;
15
- private validateResult;
16
- LMSInitialize(): true | void;
17
- LMSTerminate(): true | void;
18
- LMSGetValue(name: string): any;
19
- LMSSetValue(name: string, value: string | number): true | void;
20
- LMSCommit(): true | undefined;
21
- LMSGetLastError(): number;
22
- LMSGetErrorString(errorCode: number): any;
23
- LMSGetDiagnostic(errorCode: number): any;
24
- get lastRequest(): {
25
- method?: "get" | "set" | undefined;
26
- key: string;
27
- } | null;
28
- getDataFromLMS(): any;
29
- getLearnerId(): any;
30
- getLearnerName(): any;
31
- setStudent(studentId: string, studentName: string): void;
32
- setScore(score: number): void;
33
- getScore(): any;
34
- getLessonStatus(): any;
35
- setLessonStatus(lessonStatus: string): void;
36
- setSessionTime(msSessionTime: number): void;
37
- get objectivesAreAvailable(): boolean;
38
- setObjectives(objectivesIds: string[]): void;
39
- get objectives(): any[];
40
- setObjectiveScore(objectiveId: string, score: number): void;
41
- setObjectiveStatus(objectiveId: string, status: "completed" | "incomplete"): void;
42
- getObjectiveScore(objectiveId: string): any;
43
- setSuspendData(data: string): void;
44
- get suspendData(): any;
45
- }
46
- export declare const convertToTimeInterval: (milliseconds: number) => string;
47
- export declare const convertMsToCMITimespan: (milliseconds: number) => string;
@@ -1,424 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.convertMsToCMITimespan = exports.convertToTimeInterval = exports.SCORMAdapter = void 0;
4
- var SCORMAdapter = /** @class */ (function () {
5
- function SCORMAdapter(errorCallback) {
6
- if (errorCallback === void 0) { errorCallback = function () { }; }
7
- var _this = this;
8
- this._ignorableErrorCodes = [
9
- { code: 0, getShouldBeIgnored: function () { return true; } },
10
- {
11
- code: 403,
12
- getShouldBeIgnored: function () { return _this._isSCORM2004; },
13
- },
14
- {
15
- code: 401,
16
- getShouldBeIgnored: function () {
17
- return !_this._isSCORM2004 &&
18
- !!_this._lastRequest &&
19
- _this._lastRequest.method === "get" &&
20
- _this._lastRequest.key === "cmi.objectives._children";
21
- },
22
- },
23
- {
24
- code: 402,
25
- getShouldBeIgnored: function () {
26
- return _this._isSCORM2004 &&
27
- !!_this._lastRequest &&
28
- _this._lastRequest.method === "get" &&
29
- _this._lastRequest.key === "cmi.objectives._children";
30
- },
31
- },
32
- {
33
- code: 351,
34
- getShouldBeIgnored: function () {
35
- var _a;
36
- return ((_a = _this._lastRequest) === null || _a === void 0 ? void 0 : _a.method) === "set" &&
37
- new RegExp("^cmi.objectives.\\d+.id$").test(_this._lastRequest.key) &&
38
- !!_this.LMSGetValue(_this._lastRequest.key);
39
- },
40
- },
41
- {
42
- code: 113,
43
- getShouldBeIgnored: function () { var _a; return ((_a = _this._lastRequest) === null || _a === void 0 ? void 0 : _a.key) === "Terminate"; },
44
- },
45
- ];
46
- this._API = null;
47
- this._isSCORM2004 = false;
48
- this._errorCallback = errorCallback;
49
- this._lastRequest = null;
50
- this._findAndSetAPI();
51
- }
52
- Object.defineProperty(SCORMAdapter.prototype, "foundAPI", {
53
- get: function () {
54
- return !!this._API;
55
- },
56
- enumerable: false,
57
- configurable: true
58
- });
59
- SCORMAdapter.prototype._initialize = function () {
60
- if (this._isSCORM2004) {
61
- this.LMSSetValue("cmi.score.min", 0);
62
- this.LMSSetValue("cmi.score.max", 100);
63
- }
64
- else {
65
- this.LMSSetValue("cmi.core.score.min", 0);
66
- this.LMSSetValue("cmi.core.score.max", 100);
67
- }
68
- };
69
- SCORMAdapter.prototype._findAndSetAPI = function () {
70
- if (typeof window === "undefined") {
71
- console.error("Unable to find an API adapter");
72
- }
73
- else {
74
- var theAPI = this._findAPIInWindow(window);
75
- if (theAPI == null &&
76
- window.opener != null &&
77
- typeof window.opener != "undefined") {
78
- theAPI = this._findAPIInWindow(window.opener);
79
- }
80
- if (theAPI == null) {
81
- console.error("Unable to find an API adapter");
82
- }
83
- else {
84
- this._API = theAPI["API"];
85
- this._isSCORM2004 = theAPI["isSCORM2004"];
86
- }
87
- if (this._API == null) {
88
- console.error("Couldn't find the API!");
89
- }
90
- }
91
- };
92
- SCORMAdapter.prototype._findAPIInWindow = function (win) {
93
- var findAPITries = 0;
94
- while (win.API == null &&
95
- win.API_1484_11 == null &&
96
- win.parent != null &&
97
- win.parent != win) {
98
- findAPITries++;
99
- if (findAPITries > 7) {
100
- console.error("Error finding API -- too deeply nested.");
101
- return null;
102
- }
103
- win = win.parent;
104
- }
105
- if (win.API) {
106
- return {
107
- API: win.API,
108
- isSCORM2004: false,
109
- };
110
- }
111
- else if (win.API_1484_11) {
112
- return {
113
- API: win.API_1484_11,
114
- isSCORM2004: true,
115
- };
116
- }
117
- return null;
118
- };
119
- SCORMAdapter.prototype._callAPIFunction = function (fun, args) {
120
- if (args === void 0) { args = [""]; }
121
- if (this._API == null) {
122
- this._warnNOAPI();
123
- return;
124
- }
125
- if (this._isSCORM2004 && fun.indexOf("LMS") == 0) {
126
- fun = fun.substr(3);
127
- }
128
- else if (!this._isSCORM2004 && !(fun.indexOf("LMS") == 0)) {
129
- fun = "LMS" + fun;
130
- }
131
- var result = this._API[fun].apply(this._API, args);
132
- console.info("[SCOL-R] ".concat(fun, "(").concat(args.join(", "), ") = ").concat(JSON.stringify(result)));
133
- return result;
134
- };
135
- SCORMAdapter.prototype._handleError = function (functionName) {
136
- var lastErrorCode = this.LMSGetLastError();
137
- var lastErrorString = this.LMSGetErrorString(lastErrorCode);
138
- var lastErrorDiagnostic = this.LMSGetDiagnostic(lastErrorCode);
139
- if (!this._ignorableErrorCodes.some(function (_a) {
140
- var code = _a.code, getShouldBeIgnored = _a.getShouldBeIgnored;
141
- return code === lastErrorCode && getShouldBeIgnored();
142
- })) {
143
- console.warn(functionName, "An error occured on the SCORM API: code ".concat(lastErrorCode, ", message: ").concat(lastErrorString), lastErrorDiagnostic);
144
- this._errorCallback(lastErrorString, lastErrorDiagnostic && lastErrorDiagnostic != lastErrorCode
145
- ? lastErrorDiagnostic
146
- : null);
147
- }
148
- };
149
- SCORMAdapter.prototype._warnNOAPI = function () {
150
- console.warn("Cannot execute this function because the SCORM API is not available.");
151
- this._errorCallback("apiNotFound");
152
- };
153
- SCORMAdapter.prototype.validateResult = function (result) {
154
- if (typeof result === "string") {
155
- return result === "true";
156
- }
157
- else if (typeof result === "boolean") {
158
- return result;
159
- }
160
- return false;
161
- };
162
- SCORMAdapter.prototype.LMSInitialize = function () {
163
- var functionName = "Initialize";
164
- var result = this._callAPIFunction(functionName);
165
- var lastErrorCode = this.LMSGetLastError();
166
- var success = this.validateResult(result) ||
167
- (this._isSCORM2004
168
- ? lastErrorCode === 103 // 103 in 2004.* = already initialized
169
- : lastErrorCode === 101); // 101 in 1.2 = already initialized
170
- if (success) {
171
- this._initialize();
172
- }
173
- return success || this._handleError(functionName);
174
- };
175
- SCORMAdapter.prototype.LMSTerminate = function () {
176
- this._lastRequest = { key: "Terminate" };
177
- var functionName = this._isSCORM2004 ? "Terminate" : "Finish";
178
- var result = this._callAPIFunction(functionName);
179
- var success = this.validateResult(result);
180
- return success || this._handleError(functionName);
181
- };
182
- SCORMAdapter.prototype.LMSGetValue = function (name) {
183
- this._lastRequest = { method: "get", key: name };
184
- var functionName = "GetValue";
185
- var value = this._callAPIFunction(functionName, [name]);
186
- var success = this.LMSGetLastError() === 0;
187
- return success ? value : this._handleError("".concat(functionName, ": ").concat(name));
188
- };
189
- SCORMAdapter.prototype.LMSSetValue = function (name, value) {
190
- this._lastRequest = { method: "set", key: name };
191
- var functionName = "SetValue";
192
- var result = this._callAPIFunction(functionName, [name, value]);
193
- var success = this.validateResult(result);
194
- return success || this._handleError("".concat(functionName, ": {").concat(name, ": ").concat(value, "}"));
195
- };
196
- SCORMAdapter.prototype.LMSCommit = function () {
197
- var _this = this;
198
- var result = this._callAPIFunction("Commit");
199
- if (this.validateResult(result)) {
200
- return true;
201
- }
202
- else if (typeof result === "object" &&
203
- "then" in result &&
204
- typeof result.then === "function") {
205
- result.then(function (success) {
206
- if (!_this.validateResult(success)) {
207
- _this._errorCallback("commitFailed");
208
- }
209
- });
210
- return true;
211
- }
212
- this._errorCallback("commitFailed");
213
- };
214
- SCORMAdapter.prototype.LMSGetLastError = function () {
215
- return parseInt(this._callAPIFunction("GetLastError"));
216
- };
217
- SCORMAdapter.prototype.LMSGetErrorString = function (errorCode) {
218
- return this._callAPIFunction("GetErrorString", [errorCode]);
219
- };
220
- SCORMAdapter.prototype.LMSGetDiagnostic = function (errorCode) {
221
- return this._callAPIFunction("GetDiagnostic", [errorCode]);
222
- };
223
- Object.defineProperty(SCORMAdapter.prototype, "lastRequest", {
224
- get: function () {
225
- return this._lastRequest;
226
- },
227
- enumerable: false,
228
- configurable: true
229
- });
230
- SCORMAdapter.prototype.getDataFromLMS = function () {
231
- return this.LMSGetValue("cmi.launch_data");
232
- };
233
- SCORMAdapter.prototype.getLearnerId = function () {
234
- var CMIVariableName = this._isSCORM2004
235
- ? "cmi.learner_id"
236
- : "cmi.core.student_id";
237
- return this.LMSGetValue(CMIVariableName);
238
- };
239
- SCORMAdapter.prototype.getLearnerName = function () {
240
- var CMIVariableName = this._isSCORM2004
241
- ? "cmi.learner_name"
242
- : "cmi.core.student_name";
243
- return this.LMSGetValue(CMIVariableName);
244
- };
245
- SCORMAdapter.prototype.setStudent = function (studentId, studentName) {
246
- if (this._isSCORM2004) {
247
- this.LMSSetValue("cmi.learner_id", studentId);
248
- this.LMSSetValue("cmi.learner_name", studentName);
249
- }
250
- else {
251
- this.LMSSetValue("cmi.core.student_id", studentId);
252
- this.LMSSetValue("cmi.core.student_name", studentName);
253
- }
254
- };
255
- SCORMAdapter.prototype.setScore = function (score) {
256
- if (this._isSCORM2004) {
257
- this.LMSSetValue("cmi.score.raw", score);
258
- this.LMSSetValue("cmi.score.scaled", score / 100);
259
- }
260
- else {
261
- this.LMSSetValue("cmi.core.score.raw", score);
262
- }
263
- };
264
- SCORMAdapter.prototype.getScore = function () {
265
- var CMIVariableName = this._isSCORM2004
266
- ? "cmi.score.raw"
267
- : "cmi.core.score.raw";
268
- var score = this.LMSGetValue(CMIVariableName);
269
- return score;
270
- };
271
- SCORMAdapter.prototype.getLessonStatus = function () {
272
- var CMIVariableName = this._isSCORM2004
273
- ? "cmi.completion_status"
274
- : "cmi.core.lesson_status";
275
- return this.LMSGetValue(CMIVariableName);
276
- };
277
- SCORMAdapter.prototype.setLessonStatus = function (lessonStatus) {
278
- if (this._isSCORM2004) {
279
- var successStatus = "unknown";
280
- if (lessonStatus === "passed" || lessonStatus === "failed")
281
- successStatus = lessonStatus;
282
- this.LMSSetValue("cmi.success_status", successStatus);
283
- var completionStatus = "unknown";
284
- if (lessonStatus === "passed" || lessonStatus === "completed") {
285
- completionStatus = "completed";
286
- }
287
- else if (lessonStatus === "incomplete") {
288
- completionStatus = "incomplete";
289
- }
290
- else if (lessonStatus === "not attempted" ||
291
- lessonStatus === "browsed") {
292
- completionStatus = "not attempted";
293
- }
294
- this.LMSSetValue("cmi.completion_status", completionStatus);
295
- }
296
- else {
297
- this.LMSSetValue("cmi.core.lesson_status", lessonStatus);
298
- }
299
- };
300
- SCORMAdapter.prototype.setSessionTime = function (msSessionTime) {
301
- if (this._isSCORM2004) {
302
- var duration = (0, exports.convertToTimeInterval)(msSessionTime);
303
- this.LMSSetValue("cmi.session_time", duration);
304
- }
305
- else {
306
- var duration = (0, exports.convertMsToCMITimespan)(msSessionTime);
307
- this.LMSSetValue("cmi.core.session_time", duration);
308
- }
309
- };
310
- Object.defineProperty(SCORMAdapter.prototype, "objectivesAreAvailable", {
311
- get: function () {
312
- var objectivesFields = !!this.LMSGetValue("cmi.objectives._children");
313
- return objectivesFields && this.LMSGetLastError() === 0;
314
- },
315
- enumerable: false,
316
- configurable: true
317
- });
318
- SCORMAdapter.prototype.setObjectives = function (objectivesIds) {
319
- var _this = this;
320
- objectivesIds.forEach(function (objectiveId, index) {
321
- _this.LMSSetValue("cmi.objectives.".concat(index, ".id"), objectiveId);
322
- });
323
- };
324
- Object.defineProperty(SCORMAdapter.prototype, "objectives", {
325
- get: function () {
326
- var objectives = [];
327
- var objectivesNbr = this.LMSGetValue("cmi.objectives._count");
328
- for (var index = 0; index < objectivesNbr; index++) {
329
- objectives.push(this.LMSGetValue("cmi.objectives.".concat(index, ".id")));
330
- }
331
- return objectives;
332
- },
333
- enumerable: false,
334
- configurable: true
335
- });
336
- SCORMAdapter.prototype.setObjectiveScore = function (objectiveId, score) {
337
- var objectivesNbr = this.LMSGetValue("cmi.objectives._count");
338
- for (var index = 0; index < objectivesNbr; index++) {
339
- var storedObjectiveId = this.LMSGetValue("cmi.objectives.".concat(index, ".id"));
340
- if (objectiveId === storedObjectiveId) {
341
- this.LMSSetValue("cmi.objectives.".concat(index, ".score.raw"), score);
342
- return;
343
- }
344
- }
345
- };
346
- SCORMAdapter.prototype.setObjectiveStatus = function (objectiveId, status) {
347
- var objectivesNbr = this.LMSGetValue("cmi.objectives._count");
348
- for (var index = 0; index < objectivesNbr; index++) {
349
- var storedObjectiveId = this.LMSGetValue("cmi.objectives.".concat(index, ".id"));
350
- if (objectiveId === storedObjectiveId) {
351
- if (this._isSCORM2004) {
352
- this.LMSSetValue("cmi.objectives.".concat(index, ".success_status"), status === "completed" ? "passed" : "unknown");
353
- this.LMSSetValue("cmi.objectives.".concat(index, ".completion_status"), status === "completed" ? "completed" : "incomplete");
354
- }
355
- else {
356
- this.LMSSetValue("cmi.objectives.".concat(index, ".status"), status === "completed" ? "passed" : "incomplete");
357
- }
358
- return;
359
- }
360
- }
361
- };
362
- SCORMAdapter.prototype.getObjectiveScore = function (objectiveId) {
363
- var objectivesNbr = this.LMSGetValue("cmi.objectives._count");
364
- for (var index = 0; index < objectivesNbr; index++) {
365
- var storedObjectiveId = this.LMSGetValue("cmi.objectives.".concat(index, ".id"));
366
- if (objectiveId === storedObjectiveId) {
367
- return this.LMSGetValue("cmi.objectives.".concat(index, ".score.raw"));
368
- }
369
- }
370
- };
371
- SCORMAdapter.prototype.setSuspendData = function (data) {
372
- this.LMSSetValue("cmi.suspend_data", data);
373
- };
374
- Object.defineProperty(SCORMAdapter.prototype, "suspendData", {
375
- get: function () {
376
- return this.LMSGetValue("cmi.suspend_data");
377
- },
378
- enumerable: false,
379
- configurable: true
380
- });
381
- return SCORMAdapter;
382
- }());
383
- exports.SCORMAdapter = SCORMAdapter;
384
- var convertToTimeInterval = function (milliseconds) {
385
- // timeinterval (second,10,2),
386
- var data = getDurationData(milliseconds);
387
- var days = data.days;
388
- var hours = data.hours % 24;
389
- var minutes = data.minutes % 60;
390
- var seconds = data.seconds % 60;
391
- var cents = data.cents % 100;
392
- var daysString = days ? days + "D" : "";
393
- var hoursString = hours ? hours + "H" : "";
394
- var minutesString = minutes ? minutes + "M" : "";
395
- var secondsString = (seconds || "0" + (cents ? "." + cents : "")) + "S";
396
- var hms = [hoursString, minutesString, secondsString].join("");
397
- return "P" + daysString + "T" + hms;
398
- };
399
- exports.convertToTimeInterval = convertToTimeInterval;
400
- var convertMsToCMITimespan = function (milliseconds) {
401
- // CMITimespan "0000:00:00.00"
402
- var _a = getDurationData(milliseconds), seconds = _a.seconds, minutes = _a.minutes, hours = _a.hours, cents = _a.cents;
403
- var h = pad(hours, 4);
404
- var m = pad(minutes % 60, 2);
405
- var s = pad(seconds % 60, 2);
406
- var c = pad(cents % 100, 2);
407
- return "".concat(h, ":").concat(m, ":").concat(s, ".").concat(c);
408
- };
409
- exports.convertMsToCMITimespan = convertMsToCMITimespan;
410
- var getDurationData = function (milliseconds) {
411
- var cents = Math.floor(milliseconds / 10);
412
- var seconds = Math.floor(milliseconds / 1000);
413
- var minutes = Math.floor(seconds / 60);
414
- var hours = Math.floor(minutes / 60);
415
- var days = Math.floor(hours / 24);
416
- return { days: days, hours: hours, minutes: minutes, seconds: seconds, cents: cents };
417
- };
418
- var pad = function (value, targetLength) {
419
- var text = value.toString();
420
- var padLength = targetLength - text.length;
421
- if (padLength <= 0)
422
- return text;
423
- return "0".repeat(padLength) + text;
424
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var bun_test_1 = require("bun:test");
4
- var SCORMAdapter_1 = require("./SCORMAdapter");
5
- bun_test_1.test('convertMsToCMITimespan ("0000:00:00.00")', function () {
6
- var milliseconds = (36 * 60 * 60 * 1000) + (6 * 60 * 1000) + (2 * 1000) + (23 * 10);
7
- var CMITimespan = SCORMAdapter_1.convertMsToCMITimespan(milliseconds);
8
- bun_test_1.expect(CMITimespan).toBe('0036:06:02.23');
9
- });
10
- bun_test_1.test('convertToTimeInterval', function () {
11
- var milliseconds = (36 * 60 * 60 * 1000) + (6 * 60 * 1000) + (2 * 1000) + (23 * 10);
12
- var timeInterval = SCORMAdapter_1.convertToTimeInterval(milliseconds);
13
- bun_test_1.expect(timeInterval).toBe('P1DT12H6M2');
14
- });
@@ -1 +0,0 @@
1
- export declare function hashString(string: string): Promise<string>;
package/lib/hashString.js DELETED
@@ -1,57 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.hashString = void 0;
40
- function hashString(string) {
41
- return __awaiter(this, void 0, void 0, function () {
42
- var utf8, hashBuffer;
43
- return __generator(this, function (_a) {
44
- switch (_a.label) {
45
- case 0:
46
- utf8 = new TextEncoder().encode(string);
47
- return [4 /*yield*/, crypto.subtle.digest("SHA-256", utf8)];
48
- case 1:
49
- hashBuffer = _a.sent();
50
- return [2 /*return*/, Array.from(new Uint8Array(hashBuffer))
51
- .map(function (bytes) { return bytes.toString(16).padStart(2, "0"); })
52
- .join("")];
53
- }
54
- });
55
- });
56
- }
57
- exports.hashString = hashString;
package/lib/index.d.ts DELETED
@@ -1,14 +0,0 @@
1
- export * from "./ManifestGenerator";
2
- export * from "./SCORMAdapter";
3
- export * from "./HTMLGenerator";
4
- export { MessageEmitter } from "./MessageHandler";
5
- export declare const libFiles: readonly ["loadContent.js", "MessageHandler.js", "SCORMAdapter.js", "hashString.js"];
6
- export declare const scormVersions: readonly ["1.2", "2004 3rd Edition", "2004 4th Edition"];
7
- export declare enum LessonStatus {
8
- Passed = "passed",
9
- Failed = "failed",
10
- Completed = "completed",
11
- Incomplete = "incomplete",
12
- NotAttempted = "not attempted",
13
- Browsed = "browsed"
14
- }
package/lib/index.js DELETED
@@ -1,42 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.LessonStatus = exports.scormVersions = exports.libFiles = exports.MessageEmitter = void 0;
18
- __exportStar(require("./ManifestGenerator"), exports);
19
- __exportStar(require("./SCORMAdapter"), exports);
20
- __exportStar(require("./HTMLGenerator"), exports);
21
- var MessageHandler_1 = require("./MessageHandler");
22
- Object.defineProperty(exports, "MessageEmitter", { enumerable: true, get: function () { return MessageHandler_1.MessageEmitter; } });
23
- exports.libFiles = [
24
- "loadContent.js",
25
- "MessageHandler.js",
26
- "SCORMAdapter.js",
27
- "hashString.js",
28
- ];
29
- exports.scormVersions = [
30
- "1.2",
31
- "2004 3rd Edition",
32
- "2004 4th Edition",
33
- ];
34
- var LessonStatus;
35
- (function (LessonStatus) {
36
- LessonStatus["Passed"] = "passed";
37
- LessonStatus["Failed"] = "failed";
38
- LessonStatus["Completed"] = "completed";
39
- LessonStatus["Incomplete"] = "incomplete";
40
- LessonStatus["NotAttempted"] = "not attempted";
41
- LessonStatus["Browsed"] = "browsed";
42
- })(LessonStatus || (exports.LessonStatus = LessonStatus = {}));
@@ -1,3 +0,0 @@
1
- export function loadContent({ hashIdentifiers }?: {
2
- hashIdentifiers?: boolean | undefined;
3
- }): Promise<void>;
@@ -1,196 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.loadContent = void 0;
40
- function loadContent(_a) {
41
- var _b = _a === void 0 ? {} : _a, _c = _b.hashIdentifiers, hashIdentifiers = _c === void 0 ? false : _c;
42
- return __awaiter(this, void 0, void 0, function () {
43
- var messages, localizeMessage, displayInitError, displayRuntimeError, ADAPTER, lessonStatus, sourceUrl, sourceUrlParser, learnerId, learnerName, iframe, sessionStart, host, sourceOrigin, sessionStart;
44
- return __generator(this, function (_d) {
45
- switch (_d.label) {
46
- case 0:
47
- messages = {
48
- en: {
49
- pageTitle: "Your content is loading...",
50
- pageSubtitle: "Please wait, or if your content doesn't appear, try closing and opening this window again.",
51
- pageErrorMessagesTitle: "If the initialization fails, error messages will appear below:",
52
- pageFooter: 'This content is loaded via <a href="https://github.com/Didask/scol-r" target="_blank">SCOL-R</a>, a cross-domain SCORM connector created by <a href="https://www.didask.com" target="_blank">Didask</a>.',
53
- apiNotFound: "<p>We were not able to contact your LMS: please close this window and try again later.</p>",
54
- couldNotInitialize: "<p>We were not able to initialize the connection with your LMS: please close this window and try again later.</p>",
55
- learnerIdMissing: "<p>We could not get your learner ID from the LMS: please close this window and try again later.</p>",
56
- sourceUrlMissing: "<p>We could find the address of the remote resource: it looks like this module is invalid, please contact your LMS administrator.</p>",
57
- runtimeErrorTitle: "An error occurred:",
58
- commitFailed: "The intermediate recording could not succeed. Please close the window and try again later, or contact your administrator if the problem keeps occurring.",
59
- },
60
- fr: {
61
- pageTitle: "Votre contenu est en cours de chargement...",
62
- pageSubtitle: "Merci de patienter&nbsp;; si votre contenu ne se charge pas, veuillez essayer de fermer et d'ouvrir cette fenêtre à nouveau.",
63
- pageErrorMessagesTitle: "Si l'initialisation échoue, les messages d'erreur apparaîtront ci-dessous&nbsp;:",
64
- pageFooter: 'Ce contenu est chargé via <a href="https://github.com/Didask/scol-r" target="_blank">SCOL-R</a>, un connecteur SCORM cross-domaine créé par <a href="https://www.didask.com" target="_blank">Didask</a>.',
65
- apiNotFound: "<p>Nous n'avons pas pu contacter votre LMS&nbsp;: veuillez fermer cette fenêtre et réessayer plus tard.</p>",
66
- couldNotInitialize: "<p>Nous n'avons pas pu initialiser la connection avec votre LMS&nbsp;: veuillez fermer cette fenêtre et réessayer plus tard.</p>",
67
- learnerIdMissing: "<p>Nous n'avons pas pu obtenir votre identifiant depuis le LMS&nbsp;: veuillez fermer cette fenêtre et réessayer plus tard.</p>",
68
- sourceUrlMissing: "<p>Nous n'avons pas pu trouver l'adresse de la ressource distante&nbsp;: il semble que ce module est invalide, veuillez contacter l'administrateur de votre LMS.</p>",
69
- runtimeErrorTitle: "Une erreur s'est produite&nbsp;:",
70
- commitFailed: "La sauvegarde automatique intermédiaire n’a pu aboutir. Si cette erreur se produit fréquemment veuillez fermer votre contenu et retenter plus tard ou contacter votre administrateur.",
71
- },
72
- };
73
- localizeMessage = function (message) {
74
- var locale = navigator.language || navigator.userLanguage;
75
- if (locale)
76
- locale = locale.split(/[_-]/)[0];
77
- if (!messages.hasOwnProperty(locale))
78
- locale = "en";
79
- var localizedMessages = messages[locale];
80
- return localizedMessages.hasOwnProperty(message)
81
- ? localizedMessages[message]
82
- : message;
83
- };
84
- document.getElementById("title").innerHTML = localizeMessage("pageTitle");
85
- document.getElementById("subtitle").innerHTML =
86
- localizeMessage("pageSubtitle");
87
- document.getElementById("footer-content").innerHTML =
88
- localizeMessage("pageFooter");
89
- document.getElementById("title-error-messages").innerHTML = localizeMessage("pageErrorMessagesTitle");
90
- displayInitError = function (message) {
91
- var messagesContainer = document.getElementsByClassName("messages");
92
- var newMessage = document.createElement("p");
93
- var localizedMessage = localizeMessage(message);
94
- newMessage.innerHTML = localizedMessage;
95
- messagesContainer.length && messagesContainer[0].appendChild(newMessage);
96
- console.error(localizedMessage);
97
- };
98
- displayRuntimeError = function () {
99
- var errorContainer = document.getElementById("runtime-error");
100
- if (!(arguments && arguments.length)) {
101
- errorContainer.innerHTML = "";
102
- return;
103
- }
104
- errorContainer.innerHTML =
105
- "<h6>" + localizeMessage("runtimeErrorTitle") + "</h6>";
106
- for (var i = 0; i < arguments.length; i++) {
107
- if (!arguments[i])
108
- continue;
109
- var thisError = document.createElement("p");
110
- thisError.innerHTML = localizeMessage(arguments[i]);
111
- errorContainer.appendChild(thisError);
112
- }
113
- // Remove the messages after 6 seconds
114
- setTimeout(function () {
115
- errorContainer.innerHTML = "";
116
- }, 6000);
117
- };
118
- ADAPTER = new SCORMAdapter(displayRuntimeError);
119
- if (!ADAPTER.foundAPI) {
120
- displayInitError("apiNotFound");
121
- return [2 /*return*/];
122
- }
123
- if (!ADAPTER.LMSInitialize()) {
124
- displayInitError("couldNotInitialize");
125
- return [2 /*return*/];
126
- }
127
- lessonStatus = ADAPTER.getLessonStatus();
128
- if (lessonStatus === "not attempted") {
129
- ADAPTER.setLessonStatus("incomplete");
130
- }
131
- sourceUrl = document.body.getAttribute("data-source");
132
- if (!sourceUrl) {
133
- displayInitError("sourceUrlMissing");
134
- return [2 /*return*/];
135
- }
136
- sourceUrlParser = document.createElement("a");
137
- sourceUrlParser.href = sourceUrl;
138
- learnerId = ADAPTER.getLearnerId();
139
- learnerName = ADAPTER.getLearnerName();
140
- if (learnerId == null) {
141
- displayInitError("learnerIdMissing");
142
- return [2 /*return*/];
143
- }
144
- if (!hashIdentifiers) return [3 /*break*/, 3];
145
- return [4 /*yield*/, hashString(learnerId)];
146
- case 1:
147
- learnerId = _d.sent();
148
- return [4 /*yield*/, hashString(learnerName)];
149
- case 2:
150
- learnerName = _d.sent();
151
- _d.label = 3;
152
- case 3:
153
- sourceUrlParser.search +=
154
- (sourceUrlParser.search.startsWith("?") ? "&" : "?") +
155
- "scorm" +
156
- "&learner_id=".concat(learnerId) +
157
- "&learner_name=".concat(learnerName) +
158
- "&lms_origin=".concat(encodeURIComponent(location.origin)) +
159
- "&are_identifiers_hashed=".concat(hashIdentifiers);
160
- iframe = document.createElement("iframe");
161
- iframe.setAttribute("src", sourceUrlParser.href);
162
- iframe.setAttribute("frameborder", "0");
163
- iframe.setAttribute("height", "100%");
164
- iframe.setAttribute("width", "100%");
165
- iframe.setAttribute("allow", "microphone");
166
- document.body.insertBefore(iframe, document.getElementById("wrapper"));
167
- sessionStart = new Date();
168
- host = sourceUrlParser.host;
169
- // The `host` variable may or may not contain the port number depending on the browser.
170
- // We remove it if it wasnt' explicitly set.
171
- if (host.indexOf(":") > -1 &&
172
- sourceUrl.indexOf(host) !== sourceUrlParser.protocol.length + 2) {
173
- host = host.slice(0, host.indexOf(":"));
174
- }
175
- sourceOrigin = sourceUrlParser.protocol + "//" + host;
176
- new MessageReceiver(window, sourceOrigin, ADAPTER);
177
- sessionStart = new Date().getTime();
178
- /*
179
- * In case the beforeunload event is not triggered, we still want to send the session time to the LMS.
180
- * This is why we send the session time every 10 seconds.
181
- */
182
- setInterval(function () {
183
- var now = new Date().getTime();
184
- ADAPTER.setSessionTime(now - sessionStart);
185
- }, 10000);
186
- window.addEventListener("beforeunload", function (e) {
187
- var sessionEnd = new Date().getTime();
188
- ADAPTER.setSessionTime(sessionEnd - sessionStart);
189
- ADAPTER.LMSTerminate();
190
- });
191
- return [2 /*return*/];
192
- }
193
- });
194
- });
195
- }
196
- exports.loadContent = loadContent;